main.py 647 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import NamedTuple, cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.ext.asyncio import AsyncSession
  26. from sqlalchemy.orm.exc import StaleDataError
  27. from backend.app.api.routes import (
  28. ams_history,
  29. announcements,
  30. api_keys,
  31. archive_purge,
  32. archives,
  33. auth,
  34. bug_report,
  35. bulk,
  36. camera,
  37. camwall,
  38. cloud,
  39. connected_apps,
  40. discovery,
  41. external_links,
  42. filaments,
  43. finance,
  44. firmware,
  45. github_backup,
  46. groups,
  47. ha_sensors,
  48. inventory,
  49. kprofiles,
  50. label_templates,
  51. labels,
  52. library,
  53. library_tags,
  54. library_trash,
  55. library_variants,
  56. local_backup,
  57. local_presets,
  58. location_ha_sensors,
  59. maintenance,
  60. makerworld,
  61. manyfold,
  62. metrics,
  63. mfa,
  64. notification_templates,
  65. notifications,
  66. obico,
  67. octoeverywhere,
  68. orca_cloud,
  69. overlay_branding,
  70. pending_uploads,
  71. pipeline_runs,
  72. print_log,
  73. print_queue,
  74. printer_locations,
  75. printer_sensor_history,
  76. printers,
  77. projects,
  78. scheduled_dryings,
  79. settings as settings_routes,
  80. slice_jobs,
  81. slicer_pipelines,
  82. slicer_presets,
  83. smart_plugs,
  84. sponsor_prompt,
  85. spoolbuddy,
  86. spoolman,
  87. spoolman_inventory,
  88. support,
  89. system,
  90. updates,
  91. user_notifications,
  92. users,
  93. virtual_printers,
  94. webhook,
  95. websocket,
  96. )
  97. from backend.app.api.routes.maintenance import (
  98. _get_printer_maintenance_internal,
  99. ensure_default_types,
  100. maintenance_alert_values,
  101. )
  102. from backend.app.api.routes.support import init_debug_logging
  103. from backend.app.core.config import APP_VERSION, settings as app_settings
  104. from backend.app.core.database import async_session, engine, init_db
  105. from backend.app.core.static_assets import AssetStaticFiles
  106. from backend.app.core.tasks import spawn_background_task
  107. from backend.app.core.websocket import ws_manager
  108. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  109. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  110. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  111. from backend.app.services.archive_cost_estimate import (
  112. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  113. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  114. )
  115. from backend.app.services.archive_purge import archive_purge_service
  116. from backend.app.services.bambu_ftp import (
  117. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  118. FileNotOnPrinterError,
  119. cache_3mf_download,
  120. clear_3mf_cache,
  121. download_file_async,
  122. download_file_try_paths_async,
  123. ftps_handshake_blocked,
  124. get_cached_3mf,
  125. get_ftp_retry_settings,
  126. normalize_3mf_name,
  127. with_ftp_retry,
  128. )
  129. from backend.app.services.bambu_mqtt import PrinterState
  130. from backend.app.services.camera_light import camera_light
  131. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  132. from backend.app.services.github_backup import github_backup_service
  133. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  134. from backend.app.services.hms_errors import hms_fault_counts as _hms_fault_counts
  135. from backend.app.services.library_trash import library_trash_service
  136. from backend.app.services.local_backup import local_backup_service
  137. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  138. from backend.app.services.mqtt_relay import mqtt_relay
  139. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  140. from backend.app.services.notification_service import notification_service
  141. from backend.app.services.notify_live_activities import notify_live_activities
  142. from backend.app.services.notify_widgets import notify_widgets
  143. from backend.app.services.obico_detection import obico_detection_service
  144. from backend.app.services.octoeverywhere_detection import octoeverywhere_detection_service
  145. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  146. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  147. from backend.app.services.print_scheduler import scheduler as print_scheduler
  148. from backend.app.services.print_storage import (
  149. REASON_FTP_TRANSFER_FAILED,
  150. REASON_FTPS_COOLOFF,
  151. external_storage_present,
  152. ftp_probe_paths,
  153. print_file_reachable_over_ftp,
  154. )
  155. from backend.app.services.printer_manager import (
  156. init_printer_connections,
  157. parse_plate_id,
  158. printer_manager,
  159. printer_state_to_dict,
  160. printer_tray_layout,
  161. resolve_plate_id,
  162. )
  163. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  164. from backend.app.services.slot_nozzle import (
  165. nozzle_diameter_for_extruder,
  166. nozzle_flow_for_extruder,
  167. )
  168. from backend.app.services.smart_plug_manager import smart_plug_manager
  169. from backend.app.services.spool_assignment_notifications import (
  170. notify_missing_spool_assignments_on_print_start,
  171. )
  172. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  173. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  174. from backend.app.services.spoolman_tracking import (
  175. cleanup_tracking as _cleanup_spoolman_tracking,
  176. release_archived_slot_rows as _release_archived_spoolman_slots,
  177. report_usage as _report_spoolman_usage,
  178. store_print_data as _store_spoolman_print_data,
  179. )
  180. from backend.app.services.telegram_reactions import telegram_reaction_poller
  181. from backend.app.services.wled import wled_manager
  182. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  183. from backend.app.utils.ams_humidity import ams_humidity_percent
  184. from backend.app.utils.filament_types import printer_filament_type
  185. from backend.app.utils.fts_routing import extruder_for_inlet
  186. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  187. from backend.app.utils.print_jobs import is_internal_printer_job
  188. from backend.app.utils.tray_ids import AmsType, TrayLayout, external_tray_id, unit_ams_type, unit_label
  189. # =============================================================================
  190. # Dependency Check - runs before other imports to give helpful error messages
  191. # =============================================================================
  192. def _start_error_server(missing_packages: list):
  193. """Start a minimal HTTP server to display dependency errors in browser."""
  194. import os
  195. import signal
  196. from http.server import BaseHTTPRequestHandler, HTTPServer
  197. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  198. html = f"""<!DOCTYPE html>
  199. <html>
  200. <head>
  201. <title>Bambuddy - Setup Required</title>
  202. <style>
  203. body {{
  204. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  205. background: #0f172a; color: #e2e8f0;
  206. display: flex; justify-content: center; align-items: center;
  207. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  208. }}
  209. .container {{
  210. background: #1e293b; border-radius: 12px; padding: 40px;
  211. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  212. }}
  213. h1 {{ color: #f87171; margin-bottom: 10px; }}
  214. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  215. .packages {{
  216. background: #0f172a; border-radius: 8px; padding: 20px;
  217. margin: 20px 0; text-align: left;
  218. }}
  219. .packages ul {{ margin: 0; padding-left: 20px; }}
  220. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  221. .command {{
  222. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  223. margin: 15px 0; font-family: monospace; color: #4ade80;
  224. text-align: left; overflow-x: auto;
  225. }}
  226. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  227. </style>
  228. </head>
  229. <body>
  230. <div class="container">
  231. <h1>Setup Required</h1>
  232. <h2>Missing Python packages</h2>
  233. <div class="packages"><ul>{packages_html}</ul></div>
  234. <p>To fix, run this command on your server:</p>
  235. <div class="command">pip install -r requirements.lock</div>
  236. <p>Or if using a virtual environment:</p>
  237. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  238. <p class="note">After installing, restart Bambuddy:<br>
  239. <code>sudo systemctl restart bambuddy</code></p>
  240. </div>
  241. </body>
  242. </html>"""
  243. class ErrorHandler(BaseHTTPRequestHandler):
  244. def do_GET(self):
  245. self.send_response(503)
  246. self.send_header("Content-type", "text/html")
  247. self.end_headers()
  248. self.wfile.write(html.encode())
  249. def log_message(self, format, *args):
  250. print(f"[Error Server] {args[0]}")
  251. port = int(os.environ.get("PORT", 8000))
  252. print(f"\nStarting error server on http://0.0.0.0:{port}")
  253. print("Visit this URL in your browser to see the error details.\n")
  254. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  255. def shutdown(signum, frame):
  256. print("\nShutting down error server...")
  257. raise SystemExit(0)
  258. signal.signal(signal.SIGTERM, shutdown)
  259. signal.signal(signal.SIGINT, shutdown)
  260. server.serve_forever()
  261. def check_dependencies():
  262. """Check that all required packages are installed."""
  263. missing = []
  264. # Map of import name -> package name (for pip install)
  265. required = {
  266. "jwt": "PyJWT",
  267. "fastapi": "fastapi",
  268. "uvicorn": "uvicorn",
  269. "sqlalchemy": "sqlalchemy",
  270. "aiosqlite": "aiosqlite",
  271. "pydantic": "pydantic",
  272. "paho.mqtt": "paho-mqtt",
  273. }
  274. for module, package in required.items():
  275. try:
  276. __import__(module)
  277. except ImportError:
  278. missing.append(package)
  279. if missing:
  280. print("\n" + "=" * 60)
  281. print("ERROR: Missing required Python packages!")
  282. print("=" * 60)
  283. print(f"\nMissing packages: {', '.join(missing)}")
  284. print("\nTo fix, run:")
  285. print(" pip install -r requirements.lock")
  286. print("\nOr if using a virtual environment:")
  287. print(" ./venv/bin/pip install -r requirements.lock")
  288. print("=" * 60 + "\n")
  289. _start_error_server(missing)
  290. check_dependencies()
  291. # =============================================================================
  292. # Import settings first for logging configuration
  293. # Configure logging based on settings
  294. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  295. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  296. log_level = getattr(logging, log_level_str, logging.INFO)
  297. # Trace ID column ([-] when no request scope is active — startup, MQTT
  298. # callbacks, scheduled tasks not chained from a request — so the column
  299. # stays visually aligned and missing values are obvious in grep). See
  300. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  301. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  302. # Create root logger
  303. root_logger = logging.getLogger()
  304. root_logger.setLevel(log_level)
  305. # Trace-ID injection: this filter populates record.trace_id from the
  306. # per-request ContextVar so the format string above can reference it.
  307. # Attached to each HANDLER (not the root logger) because Python's
  308. # logging semantics only invoke a logger's filters on records that
  309. # *originated* at that logger — records propagated up from child
  310. # loggers (every named logger in the app) never trigger root's filter.
  311. # Putting it on the handlers means every record any handler emits gets
  312. # trace_id injected just before the formatter runs, regardless of which
  313. # logger created the record. Without this, the formatter raises
  314. # KeyError on every child-logger record and the record is silently
  315. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  316. # partially" bug we hit. See backend/app/core/trace.py for the
  317. # ContextVar the filter reads.
  318. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  319. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  320. from backend.app.core.trace import TraceIDFilter
  321. _trace_id_filter = TraceIDFilter()
  322. # Console handler - always enabled
  323. console_handler = logging.StreamHandler()
  324. console_handler.setLevel(log_level)
  325. console_handler.setFormatter(logging.Formatter(log_format))
  326. console_handler.addFilter(_trace_id_filter)
  327. # A refused header's value (often a token) masked before the line is written.
  328. _refused_header_filter = RefusedHeaderRedactFilter()
  329. console_handler.addFilter(_refused_header_filter)
  330. root_logger.addHandler(console_handler)
  331. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  332. """Send uvicorn's own loggers to bambuddy.log as well.
  333. Neither reaches the root handler: uvicorn.access has propagate=False, and
  334. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  335. uvicorn.access is the record of which endpoint changed server state;
  336. uvicorn.error is where an unhandled route error is logged with its
  337. traceback ("Exception in ASGI application").
  338. """
  339. for name in ("uvicorn.access", "uvicorn.error"):
  340. logging.getLogger(name).addHandler(handler)
  341. # File handler - only in production or if explicitly enabled
  342. if app_settings.log_to_file:
  343. log_file = app_settings.log_dir / "bambuddy.log"
  344. file_handler = RotatingFileHandler(
  345. log_file,
  346. maxBytes=app_settings.log_max_bytes,
  347. backupCount=app_settings.log_backup_count,
  348. encoding="utf-8",
  349. )
  350. file_handler.setLevel(log_level)
  351. file_handler.setFormatter(logging.Formatter(log_format))
  352. file_handler.addFilter(_trace_id_filter)
  353. file_handler.addFilter(_refused_header_filter)
  354. root_logger.addHandler(file_handler)
  355. logging.info("Logging to file: %s", log_file)
  356. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  357. # access logger with propagate=False by default, so without this attach
  358. # there is no on-disk record of which endpoint triggered a server-state
  359. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  360. # for exactly this reason. Filtered to write methods only
  361. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  362. # frontend don't churn the rotation window faster than it's useful.
  363. from backend.app.core.logging_filters import (
  364. CancelledPoolNoiseFilter,
  365. WriteRequestsOnlyFilter,
  366. )
  367. _attach_file_handler_to_uvicorn(file_handler)
  368. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  369. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  370. # Uvicorn's access logger has propagate=False (its own default), so the
  371. # root-attached TraceIDFilter never sees these records. Attach a
  372. # second instance directly so HTTP access lines carry the same trace
  373. # ID column as the application logs they correlate with.
  374. uvicorn_access_logger.addFilter(TraceIDFilter())
  375. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  376. # BaseHTTPMiddleware cancelling the inner task scope on client
  377. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  378. # underlying transaction leak; this filter only suppresses the residual
  379. # log records that pre-existing pools still emit during their cleanup.
  380. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  381. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  382. # handler (console included), whether or not file logging is on.
  383. from backend.app.core.logging_filters import ( # noqa: E402
  384. QueryTokenRedactFilter,
  385. ShutdownCancelledRequestFilter,
  386. )
  387. # First, so the traceback of a stream cancelled at shutdown is dropped before
  388. # the filters below render it.
  389. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  390. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  391. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  392. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  393. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  394. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  395. # keys in the query). Same as the runtime log-level toggle in support.py.
  396. logging.getLogger("httpcore").setLevel(logging.WARNING)
  397. logging.getLogger("httpx").setLevel(logging.WARNING)
  398. # aiosqlite logs every statement with its parameters at DEBUG.
  399. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  400. # Reduce noise from third-party libraries in production
  401. if not app_settings.debug:
  402. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  403. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  404. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  405. # Track active prints: {(printer_id, filename): archive_id}
  406. _active_prints: dict[tuple[int, str], int] = {}
  407. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  408. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  409. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  410. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  411. # instead of running its own grab-now chain when present, so the finish photo
  412. # captures the better-framed pre-bed-drop moment without us having to force
  413. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  414. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  415. #
  416. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  417. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  418. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  419. # bank and the others are not — so the consumer can't tell them apart and
  420. # must not rotate again.
  421. _stage22_finish_frames: dict[int, bytes] = {}
  422. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  423. # `finally` block (whether it captured a frame or not). The consumer in
  424. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  425. # so the FINISH-state fallback path — where moment and completion are dispatched
  426. # back-to-back — doesn't race past the producer with an empty pop, and the
  427. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  428. # grab (Bambu printers allow only one RTSP client at a time).
  429. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  430. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  431. # layer-change and on print-progress advances (#2547) while the model is still
  432. # printing, then consumed by the FINISH-state finish-photo path when the
  433. # dispatcher recorded that it injected End G-code into this print. Bambu
  434. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  435. # plate-swap) has run, so a live grab there would capture the swapped/empty
  436. # plate.
  437. #
  438. # The load-bearing property: both drivers are print telemetry that stops before
  439. # the End G-code executes — no further layer_num increases, and mc_percent
  440. # freezes — so the last banked frame is always the finished print before the
  441. # swap. Anything added as a third driver must hold that same property.
  442. _inprint_frame_bank: dict[int, bytes] = {}
  443. # Monotonic timestamp of the last banked frame per printer — throttles banking
  444. # so tall prints don't add a camera grab on every layer.
  445. _inprint_frame_bank_ts: dict[int, float] = {}
  446. # Minimum seconds between banked frames, except the final object layer which
  447. # always refreshes for the best framing.
  448. _INPRINT_BANK_MIN_INTERVAL = 25.0
  449. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  450. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  451. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  452. # the first connected status update for that connection; transitions back
  453. # to False whenever we observe `state.connected = False` so the next
  454. # reconnect re-arms reconciliation. Keyed by printer_id.
  455. _printer_reconciled_since_connect: dict[int, bool] = {}
  456. # Same edge, same keying, for priming the printer's calibration table exactly
  457. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  458. # is otherwise filled only when someone opens the Profiles page or Configure
  459. # Slot, when a GitHub backup runs, or when the printer happens to answer
  460. # somebody else's query on the report topic. Until then the AMS slot card has
  461. # no K value to show on the printers whose trays carry none of their own
  462. # (#2854 — H2-series report cali_idx and nothing more).
  463. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  464. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  465. # {(printer_id, filename): archive_id}
  466. _expected_prints: dict[tuple[int, str], int] = {}
  467. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  468. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  469. # every print on_print_start archived, those started from Bambu Studio, Handy or
  470. # the printer's screen included, so it is no proof of ownership on its own.
  471. _owned_print_archive_ids: set[int] = set()
  472. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  473. # plates of one archive print on two printers at once, each with its own.
  474. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  475. # Used by usage tracker to map 3MF slots to physical AMS trays
  476. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  477. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  478. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  479. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  480. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  481. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  482. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  483. # for the queue path. Cleared on print completion or TTL eviction.
  484. _print_plate_ids: dict[tuple[int, int], int] = {}
  485. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  486. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  487. _last_progress_milestone: dict[int, int] = {}
  488. # Track whether first layer complete notification has been sent for current print
  489. _first_layer_notified: dict[int, bool] = {}
  490. # Track whether we already sent a kill-switch stop for the current unauthorized print
  491. _unauthorized_print_kill_sent: set[int] = set()
  492. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  493. # lookup briefly so an unknown active print does not query the database on
  494. # every status frame. A short TTL keeps settings changes responsive.
  495. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  496. _kill_switch_setting_cache: tuple[bool, float] | None = None
  497. # Provider notification started when the kill switch stops a print. The later
  498. # MQTT print-complete callback awaits this task and only sends its regular
  499. # provider notification when the immediate attempt failed.
  500. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  501. # HMS faults already notified, with when each was last seen:
  502. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  503. # fault that flickers beside a held notice was forgotten on every gap and
  504. # notified on every return (#3226). The window is long because the measured
  505. # gaps reach 64 s.
  506. _notified_hms_errors: dict[int, dict[str, float]] = {}
  507. _HMS_CLEAR_GRACE_SECONDS = 600.0
  508. # The print state each printer was last seen in, and the faults recorded before
  509. # it last changed, which are forgotten as soon as they are gone (see
  510. # _take_new_hms_faults).
  511. _hms_print_state: dict[int, str] = {}
  512. _hms_forget_when_gone: dict[int, set[str]] = {}
  513. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  514. # Used for snapshot-diff detection at print completion
  515. _timelapse_baselines: dict[int, set[str]] = {}
  516. # Printers whose baseline above was taken off a card that could not be read,
  517. # so it is empty without the card being empty (#3412).
  518. _timelapse_baselines_unread: set[int] = set()
  519. # Track printers waiting for bed to cool after print completion.
  520. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  521. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  522. _bed_cool_waiters: dict[int, dict] = {}
  523. # Track printers where the user explicitly stopped the print from the queue UI.
  524. # When on_print_complete fires with status "failed" for these printers we treat it
  525. # as "cancelled" (stopped by user) so the correct notification email is sent.
  526. _user_stopped_printers: set[int] = set()
  527. # Printers whose running print the kill switch stopped. Their completion is a
  528. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  529. _kill_switch_stopped: set[int] = set()
  530. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  531. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  532. # holds the previous observation so we only fire on the True → False edge (a
  533. # False → False repeat doesn't notify; an initial False at startup doesn't
  534. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  535. # holds the per-printer pending asyncio task that fires the notification
  536. # after a debounce window — cancelled if the printer reconnects before the
  537. # window elapses, so transient MQTT blips don't flood the user.
  538. _printer_last_connected: dict[int, bool] = {}
  539. # Printers whose relay offline event went out, so the reconnect publishes the
  540. # matching online event and a blip shorter than the debounce publishes neither.
  541. _printer_offline_published: set[int] = set()
  542. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  543. # Debounce: a printer must stay offline this long before we notify. Sized
  544. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  545. # so a single stale-trigger cooldown isn't enough to fire — only a real
  546. # offline that survives one reconnect attempt notifies.
  547. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  548. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  549. # when status="failed" to label the print's failure_reason in archives.
  550. #
  551. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  552. # which is wrong on two counts:
  553. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  554. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  555. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  556. # the public wiki) as part of its user-cancel sequence. Matching on the module
  557. # alone caused user-cancellations to be archived as "Layer shift" failures.
  558. # We now match by full short code only — anything not in this map leaves
  559. # failure_reason=None rather than guessing.
  560. # Values are the canonical camelCase failure-reason keys, NOT display labels
  561. # (issue #2974). The vocabulary is enforced on writes by
  562. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  563. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  564. # Statistics breakdown. Storing a label here instead put a second spelling of
  565. # the same cause into one column: the Failure Analysis widget groups on the raw
  566. # value, so a print the backend classified and an identical one a user
  567. # classified counted as two different reasons, and the label form could never
  568. # be translated because there was no key for ``t()`` to resolve.
  569. _HMS_FAILURE_REASONS: dict[str, str] = {
  570. # Layer shift / step loss
  571. "0300_4057": "layerShift",
  572. "0300_4068": "layerShift",
  573. "0300_800C": "layerShift",
  574. # Filament runout (printer-side & per-AMS-slot)
  575. "0300_8004": "filamentRunout",
  576. "0700_8011": "filamentRunout",
  577. "0701_8011": "filamentRunout",
  578. "0702_8011": "filamentRunout",
  579. "0703_8011": "filamentRunout",
  580. "0704_8011": "filamentRunout",
  581. "0705_8011": "filamentRunout",
  582. "0706_8011": "filamentRunout",
  583. "0707_8011": "filamentRunout",
  584. "07FF_8011": "filamentRunout",
  585. # Clogged nozzle / extruder
  586. "0300_4006": "cloggedNozzle",
  587. "0300_8016": "cloggedNozzle",
  588. "0300_801C": "cloggedNozzle",
  589. "0700_8003": "cloggedNozzle",
  590. "0700_8007": "cloggedNozzle",
  591. "0700_8013": "cloggedNozzle",
  592. "0701_8003": "cloggedNozzle",
  593. "0701_8007": "cloggedNozzle",
  594. "0701_8013": "cloggedNozzle",
  595. "0702_8003": "cloggedNozzle",
  596. # AI print monitoring — spaghetti / the model coming off the plate.
  597. # `spaghettiDetached` is a key the archive editor already offers for this
  598. # failure mode, not a new one, so a derived reason opens the dropdown on
  599. # that option rather than blank — and survives the next save, which clears
  600. # any value the editor does not recognise.
  601. #
  602. # A module-0x0C row is safe here despite the warning above: that warning is
  603. # about matching on the module alone, and 0C00_8042 is a full short code
  604. # with a documented meaning ("The AI print monitor has detected a spaghetti
  605. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  606. # cannot collide.
  607. #
  608. # 0300_8003's own text ends "before continuing your print", but on an X2D
  609. # it arrives with the print already paused, offering only
  610. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  611. #
  612. # Two neighbours are left out on purpose, so this does not get re-derived:
  613. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  614. # reads as a warning about a print that is still running, not a halt.
  615. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  616. # the waste chute. That is not the print failing.
  617. #
  618. # That line is drawn from the text, not from `severity`, because severity
  619. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  620. # module/error word with no level in it, and bambu_mqtt.py gives every
  621. # print_error entry a flat severity=3. Matching on the short code alone is
  622. # the right shape for derive_failure_reason, not an omission.
  623. "0300_8003": "spaghettiDetached",
  624. "0C00_8042": "spaghettiDetached",
  625. }
  626. def _hms_short_code(attr: int, code: int | str) -> str:
  627. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  628. if isinstance(code, str):
  629. code_int = int(code.replace("0x", ""), 16) if code else 0
  630. else:
  631. code_int = int(code or 0)
  632. attr_int = int(attr or 0)
  633. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  634. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  635. """Derive the failure_reason key for an archived print.
  636. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  637. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  638. no HMS code matches (don't guess — null is honest). The keys are the
  639. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  640. translated at render time.
  641. """
  642. if status in ("aborted", "cancelled"):
  643. return "userCancelled"
  644. if status != "failed":
  645. return None
  646. for err in hms_errors or []:
  647. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  648. if short_code in _HMS_FAILURE_REASONS:
  649. return _HMS_FAILURE_REASONS[short_code]
  650. return None
  651. # Track created_by_id for expected prints so the user email can be sent even when
  652. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  653. # {(printer_id, filename): created_by_id}
  654. _expected_print_creators: dict[tuple[int, str], int] = {}
  655. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  656. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  657. # tag tuple changes for the slot. Cleared when the slot is reported empty
  658. # so remove + reinsert reliably re-prompts the UI.
  659. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  660. async def _broadcast_unknown_tag(
  661. *,
  662. printer_id: int,
  663. ams_id: int,
  664. tray_id: int,
  665. tag_uid: str,
  666. tray_uuid: str,
  667. tray_type: str | None = None,
  668. tray_color: str | None = None,
  669. tray_sub_brands: str | None = None,
  670. tray_count: int | None = None,
  671. ) -> None:
  672. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  673. _logger = logging.getLogger(__name__)
  674. slot_key = (ams_id, tray_id)
  675. tag_key = (tag_uid or "", tray_uuid or "")
  676. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  677. if per_printer.get(slot_key) == tag_key:
  678. _logger.debug(
  679. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  680. printer_id,
  681. ams_id,
  682. tray_id,
  683. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  684. )
  685. return
  686. _logger.info(
  687. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  688. printer_id,
  689. ams_id,
  690. tray_id,
  691. tray_type,
  692. tray_color,
  693. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  694. )
  695. # Broadcast first; only commit the dedup if the WS write succeeds.
  696. # If broadcast raises, the next MQTT push retries instead of being
  697. # permanently silenced by a poisoned dedup entry.
  698. await ws_manager.broadcast(
  699. {
  700. "type": "unknown_tag",
  701. "printer_id": printer_id,
  702. "ams_id": ams_id,
  703. "tray_id": tray_id,
  704. "tag_uid": tag_uid,
  705. "tray_uuid": tray_uuid,
  706. "tray_type": tray_type,
  707. "tray_color": tray_color,
  708. "tray_sub_brands": tray_sub_brands,
  709. "tray_count": tray_count,
  710. }
  711. )
  712. per_printer[slot_key] = tag_key
  713. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  714. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  715. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  716. if per_printer is None:
  717. return
  718. per_printer.pop((ams_id, tray_id), None)
  719. # TTL for expected-print entries: evict registrations older than this to prevent
  720. # unbounded growth when a print is registered but never starts (e.g. printer
  721. # disconnect, app restart, print started from the printer panel).
  722. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  723. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  724. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  725. # Cleanup loop interval
  726. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  727. _expected_prints_cleanup_task: asyncio.Task | None = None
  728. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  729. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  730. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  731. possible_keys: list[tuple[int, str]] = []
  732. filename = (state.gcode_file or state.current_print or "").strip()
  733. subtask_name = (state.subtask_name or "").strip()
  734. if subtask_name:
  735. possible_keys.append((printer_id, subtask_name))
  736. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  737. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  738. if filename:
  739. base_name = filename.rsplit("/", 1)[-1]
  740. if base_name.endswith(".gcode.3mf"):
  741. root_name = base_name[: -len(".gcode.3mf")]
  742. possible_keys.append((printer_id, root_name))
  743. possible_keys.append((printer_id, base_name))
  744. possible_keys.append((printer_id, f"{root_name}.gcode"))
  745. possible_keys.append((printer_id, f"{root_name}.3mf"))
  746. elif base_name.endswith(".3mf"):
  747. root_name = base_name[: -len(".3mf")]
  748. possible_keys.append((printer_id, root_name))
  749. possible_keys.append((printer_id, base_name))
  750. elif base_name.endswith(".gcode"):
  751. root_name = base_name[: -len(".gcode")]
  752. possible_keys.append((printer_id, root_name))
  753. possible_keys.append((printer_id, f"{root_name}.3mf"))
  754. possible_keys.append((printer_id, base_name))
  755. else:
  756. possible_keys.append((printer_id, base_name))
  757. possible_keys.append((printer_id, f"{base_name}.3mf"))
  758. return possible_keys
  759. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  760. """The id of who started the print, unless that user has been deleted since.
  761. Deleting a user forgets them in printer_manager, but a print that ended a
  762. moment before still holds them.
  763. """
  764. if not print_user or print_user.get("user_id") is None:
  765. return None
  766. from backend.app.models.user import User
  767. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  768. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  769. """Check the cheap, process-local print ownership signals."""
  770. if printer_manager.get_current_print_user(printer_id):
  771. return True
  772. return any(
  773. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  774. for key in _build_status_print_keys(printer_id, state)
  775. )
  776. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  777. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  778. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  779. async def _printing_archive_without_job_id(
  780. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  781. ):
  782. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  783. An archive with a real id of its own is a print that reported one: a "0"
  784. print is not it, even under the same name (one whose completion was missed
  785. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  786. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  787. """
  788. from backend.app.models.archive import PrintArchive
  789. query = select(PrintArchive).where(
  790. PrintArchive.printer_id == printer_id,
  791. PrintArchive.status == "printing",
  792. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  793. )
  794. if dispatched_only:
  795. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  796. if live_only:
  797. query = query.where(PrintArchive.deleted_at.is_(None))
  798. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  799. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  800. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  801. """The archive of the print running on ``printer_id``, or None (#3327).
  802. By the print's subtask_id first, which the firmware mints per print; with
  803. ``printing_only`` only an archive that is still printing (a leftover row of
  804. a completion never seen must not stand in for another job). A print
  805. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  806. screen) reports subtask_id "0", which links it to nothing: the archive
  807. Bambuddy bound to the running print comes next, the one completion charges
  808. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  809. own prints, so with ``by_name`` a "0" print last falls back to its printing
  810. archive under the name the printer reports. That can be an earlier run of
  811. the same name whose completion was missed while Bambuddy was down: good
  812. enough for a plate label or a cover, not for which objects skip-objects
  813. offers, so those callers leave it off. None until the archive exists, and
  814. never a deleted one.
  815. """
  816. from backend.app.models.archive import PrintArchive
  817. from backend.app.services.print_log import open_run_on_printer
  818. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  819. if subtask_id not in ("", "0"):
  820. # The run open on the printer for this job: the archive row is shared
  821. # by every plate of it, its printer and job id the latest start's.
  822. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  823. if run is not None and run.archive_id is not None:
  824. archive = await db.scalar(
  825. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  826. )
  827. if archive is not None:
  828. return archive
  829. query = select(PrintArchive).where(
  830. PrintArchive.printer_id == printer_id,
  831. PrintArchive.subtask_id == subtask_id,
  832. PrintArchive.deleted_at.is_(None),
  833. )
  834. if printing_only:
  835. query = query.where(PrintArchive.status == "printing")
  836. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  837. if archive is not None:
  838. return archive
  839. bound = next(
  840. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  841. None,
  842. )
  843. if bound is not None:
  844. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  845. if not by_name or subtask_id != "0":
  846. return None
  847. reported = _reported_print_names(printer_id, state)
  848. if not reported:
  849. return None
  850. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  851. def _bind_active_print(
  852. printer_id: int,
  853. archive_id: int,
  854. archive_filename: str | None,
  855. filename: str | None = None,
  856. subtask_name: str | None = None,
  857. ) -> None:
  858. """Track a running print under every name its completion may report.
  859. One set for every path that binds a print (new archive, expected print,
  860. restart resume, fallback): the archive's file name, the name the printer
  861. reported, and the subtask with and without ``.3mf``. Paths that registered
  862. fewer names lost the bound archive at completion, and with it the plate
  863. restore's height (#3240), whenever MQTT reported a name they had left out.
  864. """
  865. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  866. if name:
  867. _active_prints[(printer_id, name)] = archive_id
  868. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  869. """The archive of the run open on the printer, if it is still there.
  870. With ``subtask_id``, only a run of that job."""
  871. try:
  872. from backend.app.models.archive import PrintArchive
  873. from backend.app.services.print_log import open_run_on_printer
  874. async with async_session() as db:
  875. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  876. if run is None or run.archive_id is None:
  877. return None
  878. return await db.scalar(
  879. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  880. )
  881. except Exception as e:
  882. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  883. return None
  884. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  885. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  886. each announced by run/started, now gone without an end."""
  887. if not discarded:
  888. return
  889. try:
  890. from backend.app.models.printer import Printer
  891. async with async_session() as db:
  892. printer = (
  893. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  894. ).first()
  895. if printer is not None:
  896. for run in discarded:
  897. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  898. except Exception as e:
  899. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  900. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  901. """Publish the run a print's end just wrote on the MQTT relay (archive
  902. redesign); nothing without one. Never in the way of the completion."""
  903. if run_id is None:
  904. return
  905. try:
  906. from backend.app.models.archive import PrintArchive
  907. from backend.app.models.print_log import PrintLogEntry
  908. from backend.app.models.printer import Printer
  909. async with async_session() as db:
  910. run = await db.get(PrintLogEntry, run_id)
  911. printer = (
  912. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  913. ).first()
  914. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  915. if run is not None and printer is not None:
  916. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  917. except Exception as e:
  918. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  919. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  920. """Write the run of the print that just started on the archive (archive
  921. redesign). In a session of its own and never in the way of the print
  922. start: until its readers move over, the archive still carries the print.
  923. The archive's start must be committed before. ``subtask_id`` is the
  924. printer's job, which finds the run again at a resume."""
  925. try:
  926. from backend.app.models.archive import PrintArchive
  927. from backend.app.models.printer import Printer
  928. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  929. async with async_session() as db:
  930. archive = await db.get(PrintArchive, archive_id)
  931. if archive is None:
  932. return
  933. printer = (
  934. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  935. ).first()
  936. printer_name = printer.name if printer is not None else None
  937. already = await open_run_on_printer(db, printer_id)
  938. before = run_snapshot(already) if already is not None else None
  939. run = await open_run(
  940. db,
  941. archive,
  942. printer_id=printer_id,
  943. printer_name=printer_name,
  944. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  945. subtask_id=subtask_id,
  946. )
  947. await db.commit()
  948. # Once per print: a resume or a repeated start finds the run it opened.
  949. # A new one replaced the run still open there (open_run): that one's
  950. # print ended unseen.
  951. # Compared by start too: SQLite can give the new run the id of the one
  952. # it replaced.
  953. replaced = (
  954. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  955. )
  956. if run is not None and printer is not None and (before is None or replaced):
  957. if replaced:
  958. await _announce_discarded_runs([before], printer_id)
  959. try:
  960. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  961. except Exception:
  962. pass # Don't fail the print start if MQTT fails
  963. except Exception as e:
  964. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  965. async def _drop_replaced_plate_videos(
  966. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  967. ) -> None:
  968. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  969. one the archive showed (when print start judged it this plate's), and
  970. those of the archive's earlier runs of the same plate. A plate keeps one
  971. video, as when the archive held the only one; another plate's stays. The
  972. runs that held them lose them. Commits."""
  973. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  974. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  975. runs = select(PrintLogEntry).where(
  976. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  977. )
  978. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  979. paths = {stale_relpath} if stale_relpath else set()
  980. if plate_id is not None:
  981. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  982. # A video another plate's run holds is that plate's.
  983. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  984. if not paths:
  985. return
  986. for run in with_video:
  987. if run.timelapse_path in paths:
  988. run.timelapse_path = None
  989. await db.commit()
  990. for relpath in sorted(p for p in paths if p):
  991. try:
  992. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  993. if stale_path.is_file():
  994. stale_path.unlink()
  995. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  996. except (OSError, PathTraversalError) as e:
  997. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  998. def _mark_owned_if_dispatched(archive) -> None:
  999. """Remember a running print's archive as Bambuddy's when it carries a
  1000. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  1001. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  1002. if archive.billing_run_id is not None or archive.created_by_id is not None:
  1003. _owned_print_archive_ids.add(archive.id)
  1004. async def _is_printer_kill_switch_enabled_cached() -> bool:
  1005. """Return the kill-switch setting without querying on every MQTT frame."""
  1006. global _kill_switch_setting_cache
  1007. now = time.monotonic()
  1008. if _kill_switch_setting_cache is not None:
  1009. enabled, expires_at = _kill_switch_setting_cache
  1010. if now < expires_at:
  1011. return enabled
  1012. async with async_session() as db:
  1013. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1014. enabled = await is_printer_kill_switch_enabled(db)
  1015. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1016. return enabled
  1017. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1018. """Resolve whether the current print was started by Bambuddy.
  1019. ``None`` means identity is not yet safe to decide. The kill switch must
  1020. defer in that case: stopping a print is irreversible, and the first status
  1021. frames after a restart may arrive before all subtask fields are populated.
  1022. """
  1023. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1024. return True
  1025. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1026. # printer's screen) play gcode from its read-only system partition, where no
  1027. # user file can be. Only that path counts: a calibration *name* proves
  1028. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1029. # path, and any print can be given that name.
  1030. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1031. return True
  1032. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1033. # which nothing distinguishes from a user's file given that name, so it is
  1034. # not exempt: with the kill switch on, calibrate on those printers with the
  1035. # switch off.
  1036. possible_keys = _build_status_print_keys(printer_id, state)
  1037. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1038. # is on disk. subtask_id is minted per print and pins the answer to the job
  1039. # actually running, rather than to an unrelated one that reuses a filename.
  1040. raw_subtask_id = getattr(state, "subtask_id", None)
  1041. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1042. if subtask_id == "":
  1043. # Not reported yet: the first frames after a restart can lack it.
  1044. return None
  1045. from backend.app.models.archive import PrintArchive
  1046. if subtask_id == "0":
  1047. # A print started outside the cloud from Bambu Studio, Handy or the
  1048. # printer's screen reports "0", so there is no id to match: one of
  1049. # Bambuddy's printing archives on this printer under the name the
  1050. # printer reports, compared as the printer echoes names (spaces become
  1051. # underscores). Nothing reported to compare yet: wait.
  1052. reported = _reported_print_names(printer_id, state)
  1053. if not reported:
  1054. return None
  1055. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1056. else:
  1057. from backend.app.services.print_log import open_run_on_printer
  1058. # This job's run open on the printer: the archive is shared by every
  1059. # plate of it, and its status, printer and job id are the latest
  1060. # start's, which may be another printer's.
  1061. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1062. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1063. if archive is None:
  1064. result = await db.execute(
  1065. select(PrintArchive)
  1066. .where(
  1067. PrintArchive.printer_id == printer_id,
  1068. PrintArchive.status == "printing",
  1069. PrintArchive.subtask_id == subtask_id,
  1070. )
  1071. .order_by(PrintArchive.created_at.desc())
  1072. .limit(1)
  1073. )
  1074. archive = result.scalar_one_or_none()
  1075. # An archive row on its own proves nothing: `on_print_start` archives every
  1076. # print it observes, including ones started from Bambu Studio or Handy, and
  1077. # stamps them with the same status and subtask_id. Authorizing on its mere
  1078. # existence would disable the kill switch the moment the 3MF finishes
  1079. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1080. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1081. # (carried over from the queue item that started it).
  1082. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1083. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1084. # both the archive filename and every normalized key reported by MQTT.
  1085. _owned_print_archive_ids.add(archive.id)
  1086. _active_prints[(printer_id, archive.filename)] = archive.id
  1087. for key in possible_keys:
  1088. _active_prints[key] = archive.id
  1089. return True
  1090. # No dispatch marker. Before calling this someone else's print, check whether
  1091. # Bambuddy has a job of its own running on this printer: a library-file
  1092. # dispatch has no archive at send time, and an archive created seconds later
  1093. # by `on_print_start` carries neither marker. The queue row, which the
  1094. # scheduler commits to status="printing" before the MQTT send, is the one
  1095. # durable record every Bambuddy print has. It cannot be tied to this
  1096. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1097. # print is irreversible, and refusing to act costs nothing but a log line.
  1098. from backend.app.models.print_queue import PrintQueueItem
  1099. dispatched_here = await db.scalar(
  1100. select(PrintQueueItem.id)
  1101. .where(
  1102. PrintQueueItem.printer_id == printer_id,
  1103. PrintQueueItem.status == "printing",
  1104. )
  1105. .limit(1)
  1106. )
  1107. if dispatched_here is not None:
  1108. return None
  1109. return False
  1110. async def _send_kill_switch_provider_notification(
  1111. printer_id: int,
  1112. printer_name: str,
  1113. data: dict,
  1114. ) -> bool:
  1115. """Send the immediate print-stopped provider notification.
  1116. Returning a success flag lets the normal MQTT completion path retry when
  1117. this early notification could not be delivered.
  1118. """
  1119. logger = logging.getLogger(__name__)
  1120. try:
  1121. async with async_session() as db:
  1122. from backend.app.services.print_log import open_run_on_printer
  1123. # The print it stopped, for {archive_id} / {run_id}: the completion
  1124. # that would name them skips its notification after this one.
  1125. run = await open_run_on_printer(db, printer_id)
  1126. await notification_service.on_print_complete(
  1127. printer_id,
  1128. printer_name,
  1129. "stopped",
  1130. data,
  1131. db,
  1132. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1133. )
  1134. return True
  1135. except Exception as e:
  1136. logger.warning(
  1137. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1138. printer_id,
  1139. e,
  1140. )
  1141. return False
  1142. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1143. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1144. if task is None:
  1145. return False
  1146. try:
  1147. return await task
  1148. except Exception as e:
  1149. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1150. return False
  1151. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1152. """At a resume: whether the print's run still lacks its energy start
  1153. reading. The archive's may be an earlier print's. Commits a reading
  1154. found on the archive for this run onto it."""
  1155. try:
  1156. from backend.app.services.print_log import run_needs_energy_start
  1157. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1158. await db.commit()
  1159. return needs
  1160. except Exception as e:
  1161. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1162. return archive.energy_start_kwh is None
  1163. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1164. """Capture the smart plug lifetime counter on the archive at print start.
  1165. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1166. tracking survives a backend restart mid-print. The print-end handler reads
  1167. this value back from the DB and computes the delta against the current
  1168. plug counter.
  1169. """
  1170. _logger = logging.getLogger(__name__)
  1171. try:
  1172. candidates = await energy_plug_candidates(db, printer_id)
  1173. if not candidates:
  1174. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1175. return False
  1176. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1177. if selected is None:
  1178. # Naming the plugs matters here: with several linked to one printer
  1179. # this is the difference between "the meter is offline" and "you
  1180. # linked only accessories" (#2859).
  1181. _logger.warning(
  1182. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1183. printer_id,
  1184. archive.id,
  1185. ", ".join(plug.name for plug in candidates),
  1186. )
  1187. return False
  1188. plug, energy = selected
  1189. archive.energy_start_kwh = float(energy["total"])
  1190. # With the plug's snapshots, what lets the cost follow the price over
  1191. # the print rather than take the price at its end (#1251). A price that
  1192. # can't be had must not cost the print its energy reading.
  1193. archive.energy_start_at = utcnow_naive()
  1194. archive.energy_start_plug_id = plug.id
  1195. try:
  1196. from backend.app.services.energy_price import current_price
  1197. archive.energy_start_price = await current_price(db)
  1198. except Exception as e:
  1199. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1200. archive.energy_start_price = None
  1201. try:
  1202. from backend.app.services.print_log import mirror_energy_start
  1203. await mirror_energy_start(db, archive, printer_id=printer_id)
  1204. except Exception as e:
  1205. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1206. await db.commit()
  1207. _logger.info(
  1208. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1209. f" ({context})" if context else "",
  1210. archive.id,
  1211. plug.name,
  1212. energy["total"],
  1213. )
  1214. return True
  1215. except Exception as e:
  1216. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1217. return False
  1218. def forget_print_creator(user_id: int) -> None:
  1219. """The print-start emails of a deleted user's jobs go to nobody, not to
  1220. whoever is given the id next (SQLite reuses it)."""
  1221. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1222. del _expected_print_creators[key]
  1223. async def forget_printer(printer_id: int) -> None:
  1224. """Drop what is kept for a deleted printer's id, here and in the services.
  1225. SQLite used to give the id to the next printer created, which inherited it
  1226. all: the running print's owner (its prints passed the kill switch and were
  1227. billed to that user), the plate-clear gate, pending and suppressed
  1228. notifications, the camera feed, the plate references. Ids are no longer
  1229. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1230. stay. Called after the delete is committed, and again by work that was in
  1231. flight and wrote state back.
  1232. Every printer-keyed map of this module is listed here or, with the reason,
  1233. in tests/unit/test_forget_printer.py.
  1234. """
  1235. from backend.app.api.routes import camera
  1236. from backend.app.services import (
  1237. bambu_ftp,
  1238. kprofile_drift,
  1239. layer_timelapse,
  1240. plate_detection,
  1241. print_dispatch_context,
  1242. usage_tracker,
  1243. )
  1244. from backend.app.services.notify_live_activities import notify_live_activities
  1245. from backend.app.services.obico_detection import obico_detection_service
  1246. from backend.app.services.printer_file_cache import printer_file_cache
  1247. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1248. archive_ids = set()
  1249. for tracked in (_active_prints, _expected_prints):
  1250. for key in [key for key in tracked if key[0] == printer_id]:
  1251. archive_ids.add(tracked.pop(key))
  1252. for archive_id in archive_ids:
  1253. _owned_print_archive_ids.discard(archive_id)
  1254. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1255. for key in [key for key in registered if key[0] == printer_id]:
  1256. del registered[key]
  1257. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1258. for key in [key for key in tracked if key[0] == printer_id]:
  1259. del tracked[key]
  1260. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1261. _ams_index_only_logged.discard(key)
  1262. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1263. del _ams_alarm_cooldown[key]
  1264. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1265. # A kill-switch notice is about a stop that happened and is left to finish.
  1266. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1267. task = tasks.pop(printer_id, None)
  1268. if task is not None:
  1269. task.cancel()
  1270. for keyed in (
  1271. _stage22_finish_frames,
  1272. _stage22_finish_in_flight,
  1273. _inprint_frame_bank,
  1274. _inprint_frame_bank_ts,
  1275. _printer_reconciled_since_connect,
  1276. _printer_kprofiles_primed_since_connect,
  1277. _last_progress_milestone,
  1278. _first_layer_notified,
  1279. _kill_switch_notification_tasks,
  1280. _notified_hms_errors,
  1281. _hms_print_state,
  1282. _hms_forget_when_gone,
  1283. _timelapse_baselines,
  1284. _bed_cool_waiters,
  1285. _printer_last_connected,
  1286. _unknown_tag_last_broadcast,
  1287. _last_status_broadcast,
  1288. _connection_watchdog_last_attempt,
  1289. ):
  1290. keyed.pop(printer_id, None)
  1291. for marked in (
  1292. _unauthorized_print_kill_sent,
  1293. _user_stopped_printers,
  1294. _kill_switch_stopped,
  1295. _printer_offline_published,
  1296. _nozzle_count_updated,
  1297. _runtime_seen_connected,
  1298. _timelapse_baselines_unread,
  1299. ):
  1300. marked.discard(printer_id)
  1301. printer_manager.forget_printer(printer_id)
  1302. printer_file_cache.forget_printer(printer_id)
  1303. print_dispatch_context.clear(printer_id)
  1304. kprofile_drift.forget_printer(printer_id, deleted=True)
  1305. layer_timelapse.cancel_session(printer_id)
  1306. usage_tracker.forget_printer(printer_id)
  1307. obico_detection_service.forget_printer(printer_id)
  1308. octoeverywhere_detection_service.forget_printer(printer_id)
  1309. bambu_ftp.clear_3mf_cache(printer_id)
  1310. await camera.forget_printer(printer_id)
  1311. printers.clear_cover_cache(printer_id)
  1312. print_scheduler.forget_printer(printer_id)
  1313. notify_live_activities.forget_printer(printer_id)
  1314. plate_detection.remove_printer_references(printer_id)
  1315. def register_expected_print(
  1316. printer_id: int,
  1317. filename: str,
  1318. archive_id: int,
  1319. ams_mapping: list[int] | None = None,
  1320. created_by_id: int | None = None,
  1321. cost_center_id: int | None = None,
  1322. plate_id: int | None = None,
  1323. ):
  1324. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1325. # Store with multiple filename variations to catch different naming patterns
  1326. _expected_prints[(printer_id, filename)] = archive_id
  1327. # Also store without .3mf extension if present
  1328. if filename.endswith(".3mf"):
  1329. base = filename[:-4]
  1330. _expected_prints[(printer_id, base)] = archive_id
  1331. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1332. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1333. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1334. # path attributes the whole file's filament total to the spool instead of just
  1335. # the printed plate (#1697). They describe this dispatch: one that has none
  1336. # drops what an earlier dispatch of the archive left (sent, never started),
  1337. # unless a plate of the archive is printing now and still needs them.
  1338. dispatch = (printer_id, archive_id)
  1339. archive_printing = _printing_here(printer_id, archive_id)
  1340. if ams_mapping is not None:
  1341. _print_ams_mappings[dispatch] = ams_mapping
  1342. elif not archive_printing:
  1343. _print_ams_mappings.pop(dispatch, None)
  1344. if cost_center_id is not None:
  1345. _print_cost_center_ids[dispatch] = cost_center_id
  1346. elif not archive_printing:
  1347. _print_cost_center_ids.pop(dispatch, None)
  1348. if plate_id is not None:
  1349. _print_plate_ids[dispatch] = plate_id
  1350. elif not archive_printing:
  1351. _print_plate_ids.pop(dispatch, None)
  1352. # Store created_by_id so the user start email can be sent even when the archive
  1353. # itself has no created_by_id (e.g. library-file-based queue prints)
  1354. if created_by_id is not None:
  1355. _expected_print_creators[(printer_id, filename)] = created_by_id
  1356. if filename.endswith(".3mf"):
  1357. base = filename[:-4]
  1358. _expected_print_creators[(printer_id, base)] = created_by_id
  1359. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1360. # Record registration time for TTL-based eviction
  1361. _registered_at = time.monotonic()
  1362. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1363. if filename.endswith(".3mf"):
  1364. base = filename[:-4]
  1365. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1366. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1367. logging.getLogger(__name__).info(
  1368. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1369. )
  1370. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1371. """Undo :func:`register_expected_print` when the print never went out.
  1372. Registration has to happen *before* the MQTT print command, because the
  1373. printer can report the print before the line after the send executes. So
  1374. every path that registers and then fails to send — a cancel winning the
  1375. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1376. between — leaves an expectation for a print that will never arrive.
  1377. The TTL sweep evicts those after two hours, which is far longer than it
  1378. takes a user to react to a failed dispatch by pressing print again: that
  1379. reprint would be folded into the *old* archive and take the stale
  1380. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1381. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1382. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1383. are keyed by printer and archive, not by file, so they may only be dropped
  1384. once no live key of the printer still points at that archive.
  1385. """
  1386. keys = [(printer_id, filename)]
  1387. if filename.endswith(".3mf"):
  1388. base = filename[:-4]
  1389. keys.append((printer_id, base))
  1390. keys.append((printer_id, f"{base}.gcode"))
  1391. removed = False
  1392. for key in keys:
  1393. if _expected_prints.pop(key, None) is not None:
  1394. removed = True
  1395. _expected_print_creators.pop(key, None)
  1396. _expected_print_registered_at.pop(key, None)
  1397. # Still needed by another expected print of the archive on the printer,
  1398. # or a plate of it printing there, as in the sweep.
  1399. if not _expected_or_printing_here(printer_id, archive_id):
  1400. _drop_dispatch(printer_id, archive_id)
  1401. if removed:
  1402. logging.getLogger(__name__).info(
  1403. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1404. printer_id,
  1405. filename,
  1406. archive_id,
  1407. )
  1408. def _compute_run_filament_grams(
  1409. status: str,
  1410. archive_filament_used_grams: float | None,
  1411. progress: float | int | None,
  1412. usage_results: list[dict] | None,
  1413. ) -> float | None:
  1414. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1415. Priority for every status:
  1416. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1417. weight delta — same source that drives "Total Consumed" on the
  1418. Inventory page, so Stats and Inventory totals stay aligned).
  1419. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1420. back to the canonical "this print used X" value).
  1421. 3. For partial statuses: ``estimate * progress%``.
  1422. 4. ``None`` if nothing is known.
  1423. """
  1424. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1425. if tracked_grams > 0:
  1426. return round(tracked_grams, 1)
  1427. if status == "completed":
  1428. return archive_filament_used_grams
  1429. if archive_filament_used_grams:
  1430. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1431. if scale > 0:
  1432. return round(archive_filament_used_grams * scale, 1)
  1433. return None
  1434. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1435. """Whether a plate of the archive is printing on the printer."""
  1436. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1437. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1438. """Whether a print of the archive is expected or printing on the printer."""
  1439. return _printing_here(printer_id, archive_id) or any(
  1440. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1441. )
  1442. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1443. """Forget what the dispatch of the archive to the printer registered."""
  1444. dispatch = (printer_id, archive_id)
  1445. _print_ams_mappings.pop(dispatch, None)
  1446. _print_cost_center_ids.pop(dispatch, None)
  1447. _print_plate_ids.pop(dispatch, None)
  1448. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1449. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1450. stored_ams_mapping = data.get("ams_mapping")
  1451. if not stored_ams_mapping and archive_id:
  1452. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1453. return stored_ams_mapping
  1454. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1455. """Resolve plate_id for print start without consuming stored direct-Print state.
  1456. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1457. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1458. read it back at print-start without popping (the entry is popped on print
  1459. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1460. """
  1461. if archive_id is None:
  1462. return None
  1463. return _print_plate_ids.get((printer_id, archive_id))
  1464. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1465. """The slicer's time for the plate this print prints, for its start
  1466. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1467. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1468. whole file's time when its plates are not known; None for a plate not
  1469. known of several, and the notification takes the printer's remaining
  1470. time."""
  1471. from backend.app.services.print_cost_estimate import run_estimate
  1472. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1473. estimate = run_estimate(archive, plate_id)
  1474. return estimate.seconds if estimate is not None else None
  1475. _plate_estimates_task: asyncio.Task | None = None
  1476. async def _fill_plate_estimates() -> None:
  1477. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1478. try:
  1479. filled = await fill_plate_estimates(async_session)
  1480. except asyncio.CancelledError:
  1481. raise
  1482. except Exception as exc:
  1483. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1484. return
  1485. if filled:
  1486. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1487. def _partial_progress_scale(progress: int | float | None) -> float:
  1488. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1489. Used by every site that multiplies a "would-have-used" slicer estimate
  1490. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1491. so the three sites in ``_background_notifications`` (and the per-plate
  1492. override helper) can't drift apart on the coercion shape.
  1493. """
  1494. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1495. def _scope_notification_archive_data_to_plate(
  1496. archive_data: dict,
  1497. archive_file_path: str | None,
  1498. plate_id: int | None,
  1499. print_status: str,
  1500. progress: int | float | None,
  1501. base_dir: Path,
  1502. ) -> dict:
  1503. """Override summed-across-plates totals in ``archive_data`` with the values
  1504. for ``plate_id`` so the completion notification reports what was actually
  1505. printed, not the whole project (#1785).
  1506. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1507. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1508. the archive card's "whole project" headline, wrong for the completion
  1509. notification of a single-plate print. The queue UI already re-reads the
  1510. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1511. notification payload (filament grams, time estimate, per-slot breakdown).
  1512. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1513. no per-plate values — in every fail case the original ``archive_data`` is
  1514. returned unchanged so the notification still sends.
  1515. """
  1516. if plate_id is None or not archive_file_path:
  1517. return archive_data
  1518. from backend.app.utils.threemf_tools import (
  1519. extract_filament_usage_from_3mf,
  1520. extract_print_time_from_3mf,
  1521. )
  1522. archive_path = base_dir / archive_file_path
  1523. if not archive_path.exists():
  1524. return archive_data
  1525. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1526. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1527. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1528. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1529. if plate_time:
  1530. archive_data["print_time_seconds"] = plate_time
  1531. # Gate both the grams headline AND the per-slot breakdown on the same
  1532. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1533. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1534. # to the project-level grams the archive columns already provide rather
  1535. # than ship a project-level headline next to an all-zero per-plate
  1536. # breakdown.
  1537. if plate_grams > 0:
  1538. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1539. archive_data["filament_slots"] = [
  1540. {
  1541. "slot_id": s.get("slot_id"),
  1542. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1543. "type": s.get("type", ""),
  1544. "color": s.get("color", ""),
  1545. }
  1546. for s in plate_slots
  1547. ]
  1548. return archive_data
  1549. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1550. """Best-effort filament metadata from the MQTT print-start snapshot.
  1551. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1552. file during print, see #1533) so the fallback PrintArchive still has
  1553. enough filament info to support the inventory views and AMS-expansion
  1554. planning the operator opens it for. Returns a dict with optional
  1555. ``filament_type`` and ``filament_color`` keys in the same
  1556. comma-separated format the 3MF extractor produces, so the rest of the
  1557. codebase treats the fallback archive identically to a normal one.
  1558. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1559. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1560. entries). When supplied, only the slots actually consumed by this
  1561. print contribute. Without it the function falls back to every loaded
  1562. AMS slot — less accurate but still useful.
  1563. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1564. that the unit tests pass directly, AND the on_print_start callback
  1565. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1566. bambu_mqtt service hands to main.py at runtime. The original
  1567. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1568. handled the inner shape and silently returned ``{}`` for every real
  1569. print start, leaving fallback archives' filament fields NULL — the
  1570. exact regression the fix was meant to close. Reported with a log
  1571. proving the AMS state was right there at
  1572. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1573. """
  1574. result: dict[str, str] = {}
  1575. # Look at the on_print_start wrapper first, then the inner shape.
  1576. raw_data = (data or {}).get("raw_data")
  1577. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1578. if not isinstance(ams_root, dict):
  1579. ams_root = (data or {}).get("ams") or {}
  1580. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1581. if not isinstance(ams_units, list) or not ams_units:
  1582. return result
  1583. from backend.app.services.print_scheduler import _global_tray_id
  1584. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1585. # is (utils.tray_ids).
  1586. layout = TrayLayout.from_units(ams_units)
  1587. loaded: dict[int, tuple[str, str]] = {}
  1588. for unit in ams_units:
  1589. if not isinstance(unit, dict):
  1590. continue
  1591. try:
  1592. unit_id = int(unit.get("id", 0))
  1593. except (TypeError, ValueError):
  1594. continue
  1595. for tray in unit.get("tray") or []:
  1596. if not isinstance(tray, dict):
  1597. continue
  1598. try:
  1599. tray_id = int(tray.get("id", 0))
  1600. except (TypeError, ValueError):
  1601. continue
  1602. ttype = (tray.get("tray_type") or "").strip()
  1603. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1604. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1605. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1606. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1607. if not ttype:
  1608. continue # Empty / unloaded slot.
  1609. loaded[_global_tray_id(unit_id, tray_id, layout)] = (ttype, tcolor)
  1610. if not loaded:
  1611. return result
  1612. if ams_mapping:
  1613. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1614. filaments = [loaded[g] for g in used_ids if g in loaded]
  1615. if not filaments:
  1616. return result # Mapping points entirely at slots we have no data for.
  1617. else:
  1618. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1619. types_joined = ",".join(f[0] for f in filaments)
  1620. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1621. # Column limits per backend/app/models/archive.py: filament_type=50,
  1622. # filament_color=200.
  1623. if types_joined:
  1624. result["filament_type"] = types_joined[:50]
  1625. if colors_joined:
  1626. result["filament_color"] = colors_joined[:200]
  1627. return result
  1628. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1629. """Start a layer-timelapse session for *archive_id* when the printer has
  1630. an external camera configured. Returns True if a session was started.
  1631. Three call sites in on_print_start (expected-archive promotion, fallback
  1632. archive creation, fresh-archive creation) used to inline this same
  1633. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1634. on the first pass). Centralising the conditional + call here makes the
  1635. contract testable in isolation and keeps the three sites locked in step.
  1636. """
  1637. if not (printer.external_camera_enabled and printer.external_camera_url):
  1638. return False
  1639. from backend.app.services.layer_timelapse import start_session
  1640. start_session(
  1641. printer_id,
  1642. archive_id,
  1643. printer.external_camera_url,
  1644. printer.external_camera_type or "mjpeg",
  1645. snapshot_url=printer.external_camera_snapshot_url,
  1646. rotation=getattr(printer, "camera_rotation", 0),
  1647. )
  1648. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1649. return True
  1650. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1651. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1652. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1653. — since #2926 — the description the parser already resolved, which is preferred
  1654. when present so the queue's failure reason reads the same as the status
  1655. response. The short code still produces the bracketed label, and still
  1656. resolves the sentence for a caller whose entries predate the field. An entry
  1657. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1658. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1659. label when no description is on file. Returns None for an empty list so
  1660. callers can leave error_message unset.
  1661. """
  1662. if not hms_errors:
  1663. return None
  1664. from backend.app.services.hms_errors import get_error_description
  1665. parts: list[str] = []
  1666. for err in hms_errors:
  1667. try:
  1668. # `_hms_short_code` rather than a local derivation: this one used to
  1669. # format the error without masking it to 16 bits, so an `hms[]` entry
  1670. # whose code carries an alert-level group produced a five-digit label
  1671. # like "0500_3000A" — not a code the user can look up, and never a
  1672. # catalogue key, so the sentence was lost with it.
  1673. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1674. except (TypeError, ValueError):
  1675. continue
  1676. description = err.get("description") or get_error_description(short_code)
  1677. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1678. # groups and is not a code anyone can look up; its full code in the
  1679. # printer screen's four groups is (#2728).
  1680. full_code = str(err.get("full_code") or "")
  1681. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1682. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1683. return "; ".join(parts) if parts else None
  1684. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1685. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1686. print completes successfully. Gated to status=='completed': failed, cancelled
  1687. and aborted prints do not count as usage. Caller is responsible for committing
  1688. the session. No-op when the queue item has no linked library file (e.g. reprints
  1689. from an archive). See #1008."""
  1690. if queue_status != "completed" or item.library_file_id is None:
  1691. return
  1692. from backend.app.models.library import LibraryFile
  1693. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1694. if lib_file is None:
  1695. return
  1696. lib_file.print_count = (lib_file.print_count or 0) + 1
  1697. lib_file.last_printed_at = datetime.now(timezone.utc)
  1698. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1699. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1700. When on_print_complete fires with status 'failed' for a printer in this set we
  1701. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1702. rather than a 'print failed' notification.
  1703. """
  1704. _user_stopped_printers.add(printer_id)
  1705. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1706. _last_status_broadcast: dict[int, str] = {}
  1707. # Track printers where we've updated nozzle_count
  1708. _nozzle_count_updated: set[int] = set()
  1709. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1710. """Wait the debounce window then fire `on_printer_offline` if the printer
  1711. is still offline.
  1712. Scheduled by `on_printer_status_change` on the connected → disconnected
  1713. edge (#1752). Cancelled by the same handler if the printer reconnects
  1714. before the window elapses, so a single MQTT blip + recovery doesn't
  1715. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1716. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1717. route through the same status-change callback, so this covers both.
  1718. """
  1719. logger = logging.getLogger(__name__)
  1720. try:
  1721. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1722. still_offline = not printer_manager.is_connected(printer_id)
  1723. logger.info(
  1724. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1725. printer_id,
  1726. still_offline,
  1727. )
  1728. if not still_offline:
  1729. return
  1730. async with async_session() as db:
  1731. from backend.app.models.printer import Printer
  1732. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1733. printer = result.scalar_one_or_none()
  1734. if not printer:
  1735. logger.warning(
  1736. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1737. printer_id,
  1738. )
  1739. return
  1740. # Recorded only when the relay can publish it, so the reconnect's
  1741. # online event always has an offline before it.
  1742. if mqtt_relay.enabled and mqtt_relay.connected:
  1743. _printer_offline_published.add(printer_id)
  1744. try:
  1745. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1746. except Exception as e:
  1747. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1748. logger.info(
  1749. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1750. printer_id,
  1751. printer.name,
  1752. )
  1753. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1754. except asyncio.CancelledError:
  1755. raise
  1756. except Exception as e:
  1757. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1758. finally:
  1759. _printer_offline_notify_tasks.pop(printer_id, None)
  1760. def _hms_notify_key(error) -> str:
  1761. """What identifies a fault for notification de-duplication.
  1762. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1763. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1764. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1765. and -0006 together) shared a key and only the first was ever notified. An
  1766. entry without a full code falls back to attr and code together.
  1767. """
  1768. full_code = getattr(error, "full_code", "") or ""
  1769. if full_code:
  1770. return full_code.upper()
  1771. return f"{error.attr:08X}:{error.code}"
  1772. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1773. """The new faults that count (see ``_hms_fault_counts``).
  1774. These go to the MQTT relay; the caller also needs a description before it
  1775. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1776. used to read ``severity >= 2`` when severity held the part byte; on the real
  1777. level that would drop the task-stopping errors (#2728).
  1778. """
  1779. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1780. # What each HMS module byte is about, read off Bambu's own texts for its codes
  1781. # (hms_catalog.json). The table used to call 0x05 "Nozzle/Extruder", 0x0C
  1782. # "Motion Controller" and 0x12 "Chamber", which titled USB and MQTT errors as
  1783. # nozzle faults and an A1 mini's AMS Lite runouts as chamber errors (#3486).
  1784. _HMS_MODULE_NAMES = {
  1785. 0x03: "Print/Task", # bed, nozzle temperatures, motors, the print itself
  1786. 0x05: "System", # USB/SD, network, firmware, files, AMS communication
  1787. 0x07: "AMS/Filament",
  1788. 0x08: "Toolhead",
  1789. 0x0C: "Camera", # cameras, lidar, first-layer and AI inspection
  1790. 0x12: "AMS Lite",
  1791. 0x18: "AMS-HT",
  1792. 0x1A: "Tool Changer",
  1793. 0x29: "Air Filter",
  1794. 0x2A: "AMS 3H",
  1795. }
  1796. def _hms_error_title(module: int) -> str:
  1797. """The notification title for a fault of *module*."""
  1798. name = _HMS_MODULE_NAMES.get(module)
  1799. return f"{name} Error" if name else "Printer Error"
  1800. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1801. """The faults on this printer not notified yet, and record them as notified.
  1802. Tracking is updated before anything is sent, so concurrent status callbacks
  1803. cannot notify the same fault twice. A notified fault is forgotten once it
  1804. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1805. and on is notified once (#3226), while one that clears and comes back much
  1806. later is notified again.
  1807. When ``print_state`` changes (a print resumed, started or finished), every
  1808. fault recorded so far is forgotten the first time it is gone, without the
  1809. wait: a runout fixed before resuming must be notified if it happens again a
  1810. few minutes later, while the printer sits paused. Not only the faults gone
  1811. at the change itself, because the update that flips the state can still
  1812. carry the old fault (a ``print_error`` entry stays until a payload brings
  1813. ``hms``).
  1814. """
  1815. now = time.time()
  1816. current = {_hms_notify_key(e) for e in errors}
  1817. seen = _notified_hms_errors.setdefault(printer_id, {})
  1818. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1819. if print_state is not None:
  1820. print_state = print_state.upper()
  1821. if _hms_print_state.get(printer_id, print_state) != print_state:
  1822. forget_when_gone.update(seen)
  1823. _hms_print_state[printer_id] = print_state
  1824. for key, last_seen in list(seen.items()):
  1825. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1826. del seen[key]
  1827. forget_when_gone.discard(key)
  1828. new = current - seen.keys()
  1829. for key in current:
  1830. seen[key] = now
  1831. if not seen:
  1832. _notified_hms_errors.pop(printer_id, None)
  1833. if not forget_when_gone:
  1834. _hms_forget_when_gone.pop(printer_id, None)
  1835. return _hms_errors_to_notify(errors, new)
  1836. async def _take_new_hms_faults_and_save(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1837. """``_take_new_hms_faults``, and store the notified set when it changed (#3486).
  1838. The set lives in memory, so without this every restart sent each fault the
  1839. printer still lists once more. A failed write only costs that protection
  1840. for the next restart, so it is logged and the notification goes ahead.
  1841. """
  1842. before = set(_notified_hms_errors.get(printer_id, ()))
  1843. new = _take_new_hms_faults(printer_id, errors, print_state)
  1844. if set(_notified_hms_errors.get(printer_id, ())) != before:
  1845. from backend.app.services.hms_notified import save_notified_hms_faults
  1846. try:
  1847. await save_notified_hms_faults(printer_id, lambda: _notified_hms_errors.get(printer_id, {}).keys())
  1848. except Exception as e:
  1849. logging.getLogger(__name__).warning(
  1850. "Could not store the notified HMS faults of printer %s: %s", printer_id, e
  1851. )
  1852. return new
  1853. async def _load_notified_hms_faults() -> None:
  1854. """Restore the faults notified before the restart (#3486).
  1855. Each counts as seen now: one still listed is not sent again, and one that
  1856. is gone is forgotten after the usual grace period.
  1857. """
  1858. from backend.app.services.hms_notified import load_notified_hms_faults
  1859. try:
  1860. loaded = await load_notified_hms_faults()
  1861. except Exception as e:
  1862. logging.getLogger(__name__).warning("Could not load the notified HMS faults: %s", e)
  1863. return
  1864. now = time.time()
  1865. for printer_id, keys in loaded.items():
  1866. seen = _notified_hms_errors.setdefault(printer_id, {})
  1867. for key in keys:
  1868. seen.setdefault(key, now)
  1869. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1870. # "Printing", -1 and 255 are "no stage" (#3211).
  1871. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1872. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1873. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1874. Records it as notified. Called only for a printing state with progress above 0.
  1875. Progress before the first layer is not progress through the print (#3211).
  1876. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1877. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1878. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1879. 75% notification together with Print Started, and since 75 was then on
  1880. record, 25 and 50 could never fire. So nothing counts while the printer
  1881. reports a layer count but has not started layer 1.
  1882. Without a layer count -- a print whose first frame carried no
  1883. ``total_layer_num``, until the pushall that asks for it is answered
  1884. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1885. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1886. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1887. reports neither keeps the old behaviour rather than never notifying.
  1888. """
  1889. if (state.layer_num or 0) < 1:
  1890. if (state.total_layers or 0) > 0:
  1891. return None
  1892. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1893. return None
  1894. progress = state.progress or 0
  1895. current_milestone = 0
  1896. if progress >= 75:
  1897. current_milestone = 75
  1898. elif progress >= 50:
  1899. current_milestone = 50
  1900. elif progress >= 25:
  1901. current_milestone = 25
  1902. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1903. _last_progress_milestone[printer_id] = current_milestone
  1904. return current_milestone
  1905. return None
  1906. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1907. """Handle printer status changes - broadcast via WebSocket."""
  1908. try:
  1909. notify_live_activities.observe(printer_id, state)
  1910. except Exception:
  1911. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1912. try:
  1913. pause_eta.observe(printer_id, state)
  1914. except Exception:
  1915. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1916. wled_manager.handle_status(
  1917. printer_id,
  1918. state,
  1919. awaiting_plate_clear=printer_manager.is_awaiting_plate_clear(printer_id),
  1920. )
  1921. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1922. # transitions disconnected → connected — which covers both Bambuddy
  1923. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1924. # `reconcile_stale_active_prints` exactly once for this connection so
  1925. # any archive still in `status="printing"` that can't actually be
  1926. # running anymore (printer IDLE / different subtask / empty subtask)
  1927. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1928. # finished during a disconnect window + a smart-plug power cycle
  1929. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1930. # next boot. Reconciliation runs concurrently — it must not block the
  1931. # WebSocket dedup / broadcast logic below, and the connected edge is
  1932. # marked True BEFORE the await so concurrent status updates inside
  1933. # the same connection don't re-trigger reconciliation.
  1934. #
  1935. # Wait for a real push_status before reconciling (#1679): MQTT
  1936. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1937. # the connection, BEFORE `_request_push_all` round-trips. At that
  1938. # instant the `PrinterState` is still on construction defaults — most
  1939. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1940. # If reconcile spawns here, every in-flight archive falls through to
  1941. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1942. # creates a duplicate archive on the real PRINT COMPLETE and
  1943. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1944. # keeps the #1542 mechanism intact: once the first real push_status
  1945. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1946. # fires again with the flag still False — reconcile then runs against
  1947. # actual evidence.
  1948. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1949. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1950. _printer_reconciled_since_connect[printer_id] = True
  1951. spawn_background_task(
  1952. reconcile_stale_active_prints(printer_id),
  1953. name=f"reconcile-stale-prints-{printer_id}",
  1954. )
  1955. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1956. # Re-arm so the next reconnect triggers reconciliation again.
  1957. _printer_reconciled_since_connect[printer_id] = False
  1958. # Same edge, for the calibration table the AMS card reads its K values from.
  1959. #
  1960. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1961. # tables to ask for. A `state_known` gate alone is not enough: the first
  1962. # real push_status is what makes the state known, and the nozzle fields do
  1963. # not always arrive in it. Latching there would spend this connection's one
  1964. # attempt on a printer that could not yet say what was fitted.
  1965. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1966. if (
  1967. state.connected
  1968. and state_known
  1969. and nozzle_known
  1970. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1971. ):
  1972. _printer_kprofiles_primed_since_connect[printer_id] = True
  1973. spawn_background_task(
  1974. prime_kprofile_table(printer_id),
  1975. name=f"prime-kprofiles-{printer_id}",
  1976. )
  1977. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1978. _printer_kprofiles_primed_since_connect[printer_id] = False
  1979. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1980. # else in the AMS report changing -- a power cycle does it to every slot --
  1981. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1982. # while the printer is idle; needs_check is cheap and throttled per slot.
  1983. # Guarded: nothing here may stop the status broadcast below.
  1984. try:
  1985. if not state.connected:
  1986. kprofile_drift.forget_printer(printer_id)
  1987. elif kprofile_drift.needs_check(printer_id, state):
  1988. spawn_background_task(
  1989. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1990. name=f"reapply-kprofiles-{printer_id}",
  1991. )
  1992. except Exception:
  1993. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1994. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1995. # connected → disconnected. The "back online" channel is already covered
  1996. # by the print-failure notification (firmware reports gcode_state=FAILED
  1997. # on reconnect of an interrupted print), so there is no online
  1998. # notification. The MQTT relay gets both: offline after the debounce, and
  1999. # online on the reconnect that follows a published offline.
  2000. prev_connected = _printer_last_connected.get(printer_id)
  2001. _printer_last_connected[printer_id] = state.connected
  2002. if prev_connected is True and not state.connected:
  2003. existing = _printer_offline_notify_tasks.get(printer_id)
  2004. if existing is None or existing.done():
  2005. logging.getLogger(__name__).info(
  2006. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  2007. printer_id,
  2008. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  2009. )
  2010. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  2011. _maybe_notify_printer_offline(printer_id),
  2012. name=f"printer-offline-notify-{printer_id}",
  2013. )
  2014. elif state.connected:
  2015. # Kept until the relay can actually send online: with its broker down
  2016. # now, the next status update after the reconnect sends it.
  2017. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  2018. _printer_offline_published.discard(printer_id)
  2019. printer_info = printer_manager.get_printer(printer_id)
  2020. if printer_info:
  2021. try:
  2022. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  2023. except Exception as e:
  2024. logging.getLogger(__name__).warning(
  2025. "MQTT relay online event failed for printer %s: %s", printer_id, e
  2026. )
  2027. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  2028. if pending is not None and not pending.done():
  2029. logging.getLogger(__name__).info(
  2030. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  2031. printer_id,
  2032. )
  2033. pending.cancel()
  2034. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  2035. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  2036. temps = state.temperatures or {}
  2037. nozzle_temp = round(temps.get("nozzle", 0))
  2038. bed_temp = round(temps.get("bed", 0))
  2039. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  2040. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  2041. # Auto-detect dual-nozzle printers from MQTT temperature data
  2042. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  2043. _nozzle_count_updated.add(printer_id)
  2044. # Update nozzle_count in database
  2045. async with async_session() as db:
  2046. from backend.app.models.printer import Printer
  2047. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2048. printer = result.scalar_one_or_none()
  2049. if printer and printer.nozzle_count != 2:
  2050. printer.nozzle_count = 2
  2051. await db.commit()
  2052. logging.getLogger(__name__).info(
  2053. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2054. )
  2055. # Include target temps for heating phase detection
  2056. bed_target = round(temps.get("bed_target", 0))
  2057. nozzle_target = round(temps.get("nozzle_target", 0))
  2058. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2059. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2060. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2061. #
  2062. # dry_countdown_stalled rides along because it is the one drying signal the
  2063. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2064. # dry_time stopped moving, so on the frame that flips it every other member
  2065. # of this key is identical and the push would be deduplicated away. Mid-print
  2066. # a temperature would eventually break the tie, but a parked command on an
  2067. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2068. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2069. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2070. ams_dry_key = (
  2071. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2072. if state.raw_data
  2073. else ()
  2074. )
  2075. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2076. #
  2077. # The filament identity fields are here because Configure Slot writes
  2078. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2079. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2080. # matched, this function returned before broadcasting, and the card kept
  2081. # showing the old filament until the 30s fallback poll or a page reload —
  2082. # even though the configure route asks the printer for a fresh pushall and
  2083. # that push does carry the new values. Reset always worked, because it
  2084. # clears tray_type.
  2085. #
  2086. # These fields only change when someone configures a slot or swaps a spool,
  2087. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2088. ams_tray_key = (
  2089. tuple(
  2090. (
  2091. t.get("id"),
  2092. t.get("tray_type", ""),
  2093. t.get("state"),
  2094. t.get("tray_color", ""),
  2095. t.get("tray_info_idx", ""),
  2096. t.get("tray_sub_brands", ""),
  2097. t.get("cali_idx"),
  2098. )
  2099. for a in (state.raw_data.get("ams") or [])
  2100. for t in a.get("tray", [])
  2101. )
  2102. if state.raw_data
  2103. else ()
  2104. )
  2105. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2106. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2107. # in the AMS change-hash (tray fields only, and widening that would fire
  2108. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2109. # screen changed no key at all and the card's inlet badges sat stale until a
  2110. # reload. Like the filament-backup flag, these only move when someone
  2111. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2112. fts_key = (
  2113. state.fila_switch.installed if state.fila_switch else False,
  2114. tuple(sorted(state.ams_switch_inlet.items())),
  2115. # Which hotend holds which slot. Unlike the two above this does move
  2116. # mid-print, on every filament change — but only between discrete slots,
  2117. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2118. # it live: it decides which hotend the Load dialog may offer and whether
  2119. # Unload has anything to act on.
  2120. tuple(
  2121. sorted(
  2122. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2123. # Sort on the extruder id alone: the other members are nullable
  2124. # and comparing None with an int raises.
  2125. key=lambda entry: entry[0],
  2126. )
  2127. ),
  2128. )
  2129. status_key = (
  2130. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2131. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2132. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2133. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2134. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2135. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2136. )
  2137. # Fields that change only when the machine does (a nozzle swap, a firmware
  2138. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2139. # but on an idle printer nothing else moves the key when they change.
  2140. machine_key = (
  2141. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2142. state.firmware_version,
  2143. state.developer_mode,
  2144. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2145. # Cooling/heating, switched on the printer's screen too: on an idle
  2146. # printer nothing else moves the key (PSF-4).
  2147. state.airduct_mode,
  2148. )
  2149. status_key = f"{status_key}:{machine_key}"
  2150. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2151. if not is_active_print:
  2152. _unauthorized_print_kill_sent.discard(printer_id)
  2153. elif printer_id in _unauthorized_print_kill_sent:
  2154. # stop_print() was already sent for this print; avoid all further
  2155. # ownership and settings work until the printer leaves an active state.
  2156. pass
  2157. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2158. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2159. _unauthorized_print_kill_sent.discard(printer_id)
  2160. else:
  2161. kill_switch_enabled = False
  2162. authorization: bool | None = None
  2163. status_logger = logging.getLogger(__name__)
  2164. try:
  2165. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2166. if kill_switch_enabled:
  2167. async with async_session() as db:
  2168. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2169. except Exception as e:
  2170. # Fail safe: a database/reconciliation error must never turn into an
  2171. # irreversible stop of a print whose ownership is still unknown.
  2172. authorization = None
  2173. status_logger.warning(
  2174. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2175. )
  2176. if not kill_switch_enabled or authorization is True:
  2177. _unauthorized_print_kill_sent.discard(printer_id)
  2178. elif authorization is None:
  2179. _unauthorized_print_kill_sent.discard(printer_id)
  2180. status_logger.debug(
  2181. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2182. printer_id,
  2183. )
  2184. else:
  2185. try:
  2186. stopped = printer_manager.stop_print(printer_id)
  2187. if stopped:
  2188. _unauthorized_print_kill_sent.add(printer_id)
  2189. _kill_switch_stopped.add(printer_id)
  2190. printer_info = printer_manager.get_printer(printer_id)
  2191. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2192. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2193. notification_data = {
  2194. "status": "stopped",
  2195. "filename": state.gcode_file or state.current_print or "",
  2196. "subtask_name": state.subtask_name or "",
  2197. "progress": state.progress,
  2198. "reason": "unauthorized_print",
  2199. }
  2200. status_logger.warning(
  2201. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2202. printer_id,
  2203. state.state,
  2204. )
  2205. try:
  2206. await ws_manager.broadcast(
  2207. {
  2208. "type": "kill_switch_triggered",
  2209. "printer_id": printer_id,
  2210. "printer_name": printer_name,
  2211. "filename": filename,
  2212. "reason": "unauthorized_print",
  2213. }
  2214. )
  2215. except Exception as e:
  2216. status_logger.warning(
  2217. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2218. )
  2219. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2220. if previous_task is not None and not previous_task.done():
  2221. previous_task.cancel()
  2222. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2223. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2224. name=f"kill-switch-notification-{printer_id}",
  2225. )
  2226. else:
  2227. status_logger.warning(
  2228. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2229. printer_id,
  2230. state.state,
  2231. )
  2232. except Exception as e:
  2233. status_logger.warning(
  2234. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2235. )
  2236. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2237. try:
  2238. printer_info = printer_manager.get_printer(printer_id)
  2239. if printer_info:
  2240. await mqtt_relay.on_printer_status(
  2241. printer_id,
  2242. state,
  2243. printer_info.name,
  2244. printer_info.serial_number,
  2245. printer_manager.is_awaiting_plate_clear(printer_id),
  2246. )
  2247. except Exception:
  2248. pass # Don't fail status callback if MQTT fails
  2249. if _last_status_broadcast.get(printer_id) == status_key:
  2250. return # No change, skip WebSocket broadcast
  2251. _last_status_broadcast[printer_id] = status_key
  2252. # Check for progress milestone notifications (25%, 50%, 75%)
  2253. progress = state.progress or 0
  2254. is_printing = state.state in ("RUNNING", "PRINTING")
  2255. if is_printing and progress > 0:
  2256. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2257. if current_milestone is not None:
  2258. try:
  2259. from backend.app.models.printer import Printer
  2260. # Read the printer in a short session and release the connection
  2261. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2262. # pinned a pooled connection per milestone, per printer (issue #2572).
  2263. async with async_session() as db:
  2264. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2265. printer = result.scalar_one_or_none()
  2266. printer_name = printer.name if printer else f"Printer {printer_id}"
  2267. filename = state.subtask_name or state.gcode_file or "Unknown"
  2268. # remaining_time is in minutes, convert to seconds for notification
  2269. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2270. # Capture camera snapshot for notification image attachment (no DB held).
  2271. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2272. # Notification send needs a session (provider/template lookups).
  2273. async with async_session() as db:
  2274. await notification_service.on_print_progress(
  2275. printer_id,
  2276. printer_name,
  2277. filename,
  2278. current_milestone,
  2279. db,
  2280. remaining_time_seconds,
  2281. image_data=image_data,
  2282. )
  2283. except Exception as e:
  2284. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2285. elif progress < 5:
  2286. # Reset milestone tracking when print restarts or new print begins
  2287. _last_progress_milestone[printer_id] = 0
  2288. _first_layer_notified[printer_id] = False
  2289. # HMS error codes that should not trigger notifications even though they
  2290. # have known descriptions (e.g. user-initiated actions, not real errors).
  2291. _HMS_NOTIFICATION_SUPPRESS = {
  2292. "0500_400E", # Printing was cancelled (user action, not an error)
  2293. }
  2294. # Check for new HMS errors and send notifications
  2295. current_hms_errors = getattr(state, "hms_errors", []) or []
  2296. if current_hms_errors:
  2297. new_errors = await _take_new_hms_faults_and_save(printer_id, current_hms_errors, state.state)
  2298. if new_errors:
  2299. try:
  2300. from backend.app.models.printer import Printer
  2301. # Read the printer in a short session and release the connection
  2302. # BEFORE the ~15s camera snapshot below (issue #2572).
  2303. async with async_session() as db:
  2304. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2305. printer = result.scalar_one_or_none()
  2306. printer_name = printer.name if printer else f"Printer {printer_id}"
  2307. # Capture camera snapshot once for all error notifications (no DB held).
  2308. error_image_data = await _capture_snapshot_for_notification(
  2309. printer_id, printer, logging.getLogger(__name__)
  2310. )
  2311. # Notification sends need a session (provider/template lookups).
  2312. async with async_session() as db:
  2313. sent_count = 0
  2314. for error in new_errors:
  2315. # Build short code like "0700_8010"
  2316. # Mask to 16 bits to handle printers that send larger values
  2317. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2318. error_code_masked = error_code_int & 0xFFFF
  2319. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2320. # Only notify for errors Bambu publishes text for — printers
  2321. # send undocumented codes that aren't real errors, and Bambu
  2322. # lists some with empty text. Resolved at parse time (#2926);
  2323. # short_code is still needed for the suppression set below.
  2324. description = error.description
  2325. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2326. continue
  2327. error_type = _hms_error_title(error.module)
  2328. error_detail = description
  2329. await notification_service.on_printer_error(
  2330. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2331. )
  2332. sent_count += 1
  2333. if sent_count:
  2334. logging.getLogger(__name__).info(
  2335. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2336. )
  2337. # Also publish to MQTT relay (no DB): every new fault that
  2338. # counts, with or without text, the same set the UI counts.
  2339. printer_info = printer_manager.get_printer(printer_id)
  2340. if printer_info:
  2341. errors_data = [
  2342. {
  2343. "code": e.code,
  2344. "attr": e.attr,
  2345. "module": e.module,
  2346. "severity": e.severity,
  2347. }
  2348. for e in new_errors
  2349. ]
  2350. await mqtt_relay.on_printer_error(
  2351. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2352. )
  2353. except Exception as e:
  2354. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2355. else:
  2356. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2357. # across a print state change) are forgotten. Some codes, e.g. chamber
  2358. # temperature regulation during PETG prints, toggle every few seconds.
  2359. await _take_new_hms_faults_and_save(printer_id, [], state.state)
  2360. await ws_manager.send_printer_status(
  2361. printer_id,
  2362. printer_state_to_dict(
  2363. state,
  2364. printer_id,
  2365. printer_manager.get_model(printer_id),
  2366. printer_manager.get_drying_targets(printer_id),
  2367. ),
  2368. )
  2369. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2370. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2371. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2372. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2373. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2374. K-profiles are per-nozzle and the printer's calibration table is numbered
  2375. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2376. switch's other inlet therefore silently invalidates every configured slot in
  2377. it: the index stays put and now resolves against the other nozzle's table.
  2378. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2379. and 0.020 on the right kept the left profile after the move, and a manual
  2380. RFID re-read only re-asserted the same wrong one.
  2381. Configuring a slot is a deliberate preparation step, so this re-selects
  2382. rather than re-configures: only the calibration binding moves, and only for
  2383. slots whose spool already has a stored profile for the new nozzle. A slot
  2384. Bambuddy knows nothing about is left exactly as the operator left it.
  2385. """
  2386. logger = logging.getLogger(__name__)
  2387. target_extruder = extruder_for_inlet(inlet)
  2388. if target_extruder is None:
  2389. return
  2390. client = printer_manager.get_client(printer_id)
  2391. state = printer_manager.get_status(printer_id)
  2392. if not client or not state or not state.raw_data:
  2393. return
  2394. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2395. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2396. # the nozzle width, which changes both the K profile to select and the
  2397. # preset the slot should carry.
  2398. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2399. ams_raw = state.raw_data.get("ams")
  2400. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2401. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2402. if not unit:
  2403. return
  2404. try:
  2405. async with async_session() as db:
  2406. for tray in unit.get("tray", []):
  2407. tray_id = int(tray.get("id", -1))
  2408. if tray_id < 0 or not tray.get("tray_type"):
  2409. continue
  2410. current_idx = tray.get("cali_idx")
  2411. profile = await find_slot_kprofile_for_extruder(
  2412. db,
  2413. printer_id,
  2414. ams_id,
  2415. tray_id,
  2416. target_extruder,
  2417. nozzle_diameter,
  2418. printer_manager.get_model(printer_id),
  2419. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2420. )
  2421. if profile is None or profile.cali_idx is None:
  2422. continue
  2423. if current_idx == profile.cali_idx:
  2424. continue # Already on the right one.
  2425. logger.info(
  2426. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2427. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2428. printer_id,
  2429. ams_id,
  2430. tray_id,
  2431. inlet,
  2432. target_extruder,
  2433. profile.name,
  2434. current_idx,
  2435. profile.cali_idx,
  2436. profile.k_value,
  2437. )
  2438. client.extrusion_cali_sel(
  2439. ams_id=ams_id,
  2440. tray_id=tray_id,
  2441. cali_idx=profile.cali_idx,
  2442. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2443. nozzle_diameter=nozzle_diameter,
  2444. )
  2445. except Exception as e:
  2446. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2447. def _slot_feeds_print(printer_id: int, ams_id: int, tray_id: int) -> bool:
  2448. """Is this slot the one feeding the printer right now?
  2449. ``tray_now`` names one slot for the whole printer, so on a dual-nozzle
  2450. machine each extruder's own fed slot is asked as well. Only meaningful
  2451. while a print runs; the caller checks that.
  2452. """
  2453. status = printer_manager.get_status(printer_id)
  2454. if status is None:
  2455. return False
  2456. global_id = printer_tray_layout(printer_id, printer_manager).tray_from_slot_key(ams_id, tray_id)
  2457. if getattr(status, "tray_now", None) == global_id:
  2458. return True
  2459. slots = getattr(status, "extruder_slots", None) or {}
  2460. return any(slot.has_filament and slot.holds(ams_id, tray_id) for slot in slots.values())
  2461. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2462. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2463. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2464. from the delayed re-check -- which is why it takes the AMS data and print
  2465. state as arguments instead of reading them from the push (#3186).
  2466. """
  2467. logger = logging.getLogger(__name__)
  2468. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2469. # Auto-unlink spool assignments with stale fingerprints. Under the
  2470. # per-printer assignment lock since #3186: the held-removal re-check runs
  2471. # this outside any MQTT push, so it can now overlap one.
  2472. try:
  2473. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2474. from sqlalchemy.orm import selectinload
  2475. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2476. from backend.app.models.spool import Spool as _Spool
  2477. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2478. from backend.app.services.ams_slot_presence import spool_present
  2479. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2480. # Built-in assignments only. Since #2812 they survive a switch to
  2481. # Spoolman mode rather than being deleted by it, and this pass ends
  2482. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2483. # time as the AMS contents changed under the other mode, undoing the
  2484. # preservation more slowly but just as completely.
  2485. assignments = []
  2486. if not await spoolman_owns_assignments(db):
  2487. result = await db.execute(
  2488. select(SA)
  2489. .where(SA.printer_id == printer_id)
  2490. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2491. )
  2492. assignments = result.scalars().all()
  2493. # ``printing_now`` (top of this function) keeps a runout from
  2494. # unlinking the spool that fed the print — the next idle-time pass
  2495. # unlinks it if the user really did take it out.
  2496. stale = []
  2497. # Removals this pass is holding rather than unlinking (#3186).
  2498. held: set[tuple] = set()
  2499. for assignment in assignments:
  2500. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2501. if assignment.ams_id == 255:
  2502. ps = printer_manager.get_status(printer_id)
  2503. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2504. ext_id = external_tray_id(assignment.tray_id) # 0→254, 1→255, rack 2-8→247-253
  2505. current_tray = None
  2506. for vt in vt_tray_raw:
  2507. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2508. current_tray = vt
  2509. break
  2510. if not current_tray:
  2511. # vt_tray data may not have arrived yet — keep assignment
  2512. continue
  2513. else:
  2514. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2515. if not current_tray:
  2516. if printing_now:
  2517. logger.info(
  2518. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2519. assignment.spool_id,
  2520. assignment.ams_id,
  2521. assignment.tray_id,
  2522. )
  2523. continue
  2524. # A whole AMS unit can drop out of one push and come back in
  2525. # the next; only a slot that stays gone is a removal (#3186).
  2526. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2527. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2528. held.add(hold_key)
  2529. logger.info(
  2530. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2531. "unlinking if it is still gone in %ds",
  2532. assignment.spool_id,
  2533. assignment.ams_id,
  2534. assignment.tray_id,
  2535. int(slot_unlink_grace.GRACE_SECONDS),
  2536. )
  2537. continue
  2538. logger.info(
  2539. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2540. assignment.spool_id,
  2541. assignment.ams_id,
  2542. assignment.tray_id,
  2543. )
  2544. stale.append(assignment) # Slot empty
  2545. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2546. # A Bambu Lab spool is in this slot — check if it's the same spool
  2547. # that's currently assigned. If yes, keep the assignment (avoids
  2548. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2549. # the printer's filament preset on every startup).
  2550. tray_uuid = current_tray.get("tray_uuid", "")
  2551. tag_uid = current_tray.get("tag_uid", "")
  2552. spool = assignment.spool
  2553. spool_matches = False
  2554. if spool:
  2555. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2556. spool.tag_uid
  2557. and tag_uid
  2558. and tag_uid != "0000000000000000"
  2559. and spool.tag_uid.upper() == tag_uid.upper()
  2560. ):
  2561. spool_matches = True
  2562. if spool_matches:
  2563. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2564. cur_color = current_tray.get("tray_color", "")
  2565. cur_type = current_tray.get("tray_type", "")
  2566. fp_color = assignment.fingerprint_color or ""
  2567. fp_type = assignment.fingerprint_type or ""
  2568. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2569. assignment.fingerprint_color = cur_color
  2570. assignment.fingerprint_type = cur_type
  2571. logger.debug(
  2572. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2573. assignment.spool_id,
  2574. assignment.ams_id,
  2575. assignment.tray_id,
  2576. )
  2577. continue
  2578. # Different BL spool or unrecognized — unlink so auto-assign can match
  2579. logger.info(
  2580. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2581. assignment.spool_id,
  2582. assignment.ams_id,
  2583. assignment.tray_id,
  2584. tray_uuid,
  2585. )
  2586. stale.append(assignment)
  2587. else:
  2588. cur_color = current_tray.get("tray_color", "")
  2589. cur_type = current_tray.get("tray_type", "")
  2590. cur_state = current_tray.get("state")
  2591. fp_color = assignment.fingerprint_color or ""
  2592. fp_type = assignment.fingerprint_type or ""
  2593. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2594. # the slot was empty when the user pre-assigned via SpoolBuddy
  2595. # (the firmware drops ams_filament_setting on empty slots, so
  2596. # MQTT was deferred). The moment any filament gets inserted
  2597. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2598. # reconfigured spool — fire the deferred configuration.
  2599. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2600. # extruder" code) OR, on firmwares that don't use the state
  2601. # enum meaningfully, a non-empty tray_type when state is
  2602. # NOT one of the firmware's explicit empty signals (9, 10).
  2603. # state-only was wrong for firmwares that never set 11 — A1
  2604. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2605. # always report state=3 — so the replay never fired for them
  2606. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2607. # explicit "empty" signals authoritative over any stale
  2608. # tray_type that might survive the relay's auto-clearing.
  2609. #
  2610. # tray_exist_bits comes first because that guard cannot tell
  2611. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2612. # writes state=9 when the bit is 0 and leaves it there when the
  2613. # bit returns. A non-RFID spool inserted into a pre-assigned
  2614. # slot brings no tray_type with it, so the stale 9 made this
  2615. # expression false forever and the deferred config never fired
  2616. # — the deadlock #1322 removed from the assign path, still in
  2617. # place here (#3084, #3100).
  2618. loaded = spool_present(current_tray) is True or (
  2619. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2620. )
  2621. # Not into the slot feeding a running print: the printer refuses
  2622. # the setting for it (``ams_filament_setting refused``), and a
  2623. # spool swapped in after a runout sat through one refused send
  2624. # per AMS change. Held, it fires on the first change once the
  2625. # print is over (#3434).
  2626. if (
  2627. not fp_type.strip()
  2628. and loaded
  2629. and assignment.spool
  2630. and printing_now
  2631. and _slot_feeds_print(printer_id, assignment.ams_id, assignment.tray_id)
  2632. ):
  2633. logger.debug(
  2634. "Pre-config held for spool %d AMS%d-T%d: the slot is feeding the print",
  2635. assignment.spool_id,
  2636. assignment.ams_id,
  2637. assignment.tray_id,
  2638. )
  2639. continue
  2640. if not fp_type.strip() and loaded and assignment.spool:
  2641. # The fingerprint ends this replay. Not recorded when nothing
  2642. # could be sent (no MQTT client while the printer reconnects),
  2643. # so the next AMS change tries again. An attempt that raised is
  2644. # recorded as before: it may have sent part of the commands and
  2645. # would raise again on every change, remain% steps included.
  2646. configured: bool | None = False
  2647. try:
  2648. from backend.app.api.routes.inventory import (
  2649. apply_spool_to_slot_via_mqtt,
  2650. )
  2651. configured = await apply_spool_to_slot_via_mqtt(
  2652. db=db,
  2653. current_user=None,
  2654. spool=assignment.spool,
  2655. printer_id=printer_id,
  2656. ams_id=assignment.ams_id,
  2657. tray_id=assignment.tray_id,
  2658. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2659. current_tray_type=cur_type,
  2660. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2661. )
  2662. except Exception:
  2663. logger.exception(
  2664. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2665. assignment.spool_id,
  2666. printer_id,
  2667. assignment.ams_id,
  2668. assignment.tray_id,
  2669. )
  2670. configured = None
  2671. if configured is False:
  2672. logger.warning(
  2673. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2674. "retrying on the next AMS change",
  2675. assignment.spool_id,
  2676. printer_id,
  2677. assignment.ams_id,
  2678. assignment.tray_id,
  2679. )
  2680. else:
  2681. if configured:
  2682. logger.info(
  2683. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2684. assignment.spool_id,
  2685. printer_id,
  2686. assignment.ams_id,
  2687. assignment.tray_id,
  2688. )
  2689. assignment.fingerprint_color = cur_color
  2690. assignment.fingerprint_type = cur_type
  2691. continue
  2692. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2693. # Blank tray data mid-print is a runout, not a swap: the
  2694. # firmware clears colour and type when it unloads a spool
  2695. # it just emptied. Unlinking here would erase the record
  2696. # of which spool fed the print so far.
  2697. if printing_now and not cur_color.strip() and not cur_type.strip():
  2698. logger.info(
  2699. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2700. "(runout?)",
  2701. assignment.spool_id,
  2702. assignment.ams_id,
  2703. assignment.tray_id,
  2704. )
  2705. continue
  2706. # Same reasoning off the print, on firmware's own say-so:
  2707. # a blank tray report from a slot whose tray_exist_bits
  2708. # bit is set describes a spool the AMS cannot identify —
  2709. # a non-RFID one, or one whose slot was reset — not a
  2710. # spool that was taken out. Deleting the assignment there
  2711. # threw away the identity the user had supplied, which is
  2712. # the only place it existed (#3100). A slot the bit calls
  2713. # empty, or one that carries no bit at all, still unlinks.
  2714. #
  2715. # Unless the slot was reported empty first: a removal
  2716. # already held means a spool came out and another went
  2717. # in, so the blank report keeps the hold running below
  2718. # rather than cancelling it (#3186).
  2719. if (
  2720. spool_present(current_tray) is True
  2721. and not cur_color.strip()
  2722. and not cur_type.strip()
  2723. and not slot_unlink_grace.is_held(
  2724. printer_id,
  2725. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2726. )
  2727. ):
  2728. logger.info(
  2729. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2730. "tray reports no filament data yet",
  2731. assignment.spool_id,
  2732. assignment.ams_id,
  2733. assignment.tray_id,
  2734. )
  2735. continue
  2736. # A blank report the presence bit does not vouch for is
  2737. # still only one push. An idle X1C cleared a whole AMS
  2738. # unit's bits, colour and type for a moment and lost
  2739. # four saved assignments that way (#3186); unlink only
  2740. # if the slot is still blank after the grace period.
  2741. if not cur_color.strip() and not cur_type.strip():
  2742. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2743. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2744. held.add(hold_key)
  2745. logger.info(
  2746. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2747. "unlinking if it is still blank in %ds",
  2748. assignment.spool_id,
  2749. assignment.ams_id,
  2750. assignment.tray_id,
  2751. int(slot_unlink_grace.GRACE_SECONDS),
  2752. )
  2753. continue
  2754. # Fingerprint mismatch — but check if tray now matches the
  2755. # assigned spool (e.g. auto-configure changed the tray).
  2756. # Both sides are reduced to the type the slot can carry
  2757. # before comparing: the assign path writes that rather
  2758. # than the spool's raw material (#2902), so a spool whose
  2759. # material is a product line — "PLA+", "HTPLA" — reports
  2760. # back as "PLA" and would otherwise fail this check and
  2761. # be auto-unlinked from the slot it was just assigned to.
  2762. # Reducing the printer's side too keeps slots configured
  2763. # by an older Bambuddy, still reporting "PLA+", matching.
  2764. spool = assignment.spool
  2765. if spool:
  2766. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2767. # Two ways the assign path can have arrived at the
  2768. # slot's type, so both count as "we wrote this".
  2769. # The material column is one; the spool's preset is
  2770. # the other, and it outranks the material when the
  2771. # spool has one -- a spool whose material says PLA
  2772. # and whose preset is "Bambu PLA Aero" puts
  2773. # PLA-AERO in the slot (#2902). Read from the stored
  2774. # preset name rather than resolving the preset,
  2775. # because this runs on every AMS push and a cloud
  2776. # lookup here would be both slow and unavailable on
  2777. # the unauthenticated replay path.
  2778. spool_types = {printer_filament_type(spool.material).upper()}
  2779. if spool.slicer_filament_name:
  2780. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2781. # An imported local preset stores its type outright,
  2782. # which is what the assign path used -- and the name
  2783. # above may be unset. One keyed read, and only on a
  2784. # mismatch, which is rare.
  2785. #
  2786. # slicer_filament is free text up to fifty characters,
  2787. # so the digits have to be checked against the range
  2788. # of the integer primary key they are about to be
  2789. # compared with. Postgres raises on an out-of-range
  2790. # integer rather than simply not matching, and that
  2791. # would poison this session and abandon the rest of
  2792. # the cleanup pass.
  2793. lp_ref = (spool.slicer_filament or "").strip()
  2794. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2795. from backend.app.models.local_preset import LocalPreset as _LP
  2796. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2797. if lp_type:
  2798. spool_types.add(printer_filament_type(lp_type).upper())
  2799. if (
  2800. _colors_similar(cur_color, spool_color)
  2801. and printer_filament_type(cur_type).upper() in spool_types
  2802. ):
  2803. logger.info(
  2804. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2805. assignment.spool_id,
  2806. assignment.ams_id,
  2807. assignment.tray_id,
  2808. )
  2809. assignment.fingerprint_color = cur_color
  2810. assignment.fingerprint_type = cur_type
  2811. continue
  2812. logger.info(
  2813. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2814. assignment.spool_id,
  2815. assignment.ams_id,
  2816. assignment.tray_id,
  2817. cur_color,
  2818. cur_type,
  2819. fp_color,
  2820. fp_type,
  2821. spool.rgba if spool else "?",
  2822. spool.material if spool else "?",
  2823. )
  2824. stale.append(assignment) # Spool changed
  2825. slot_unlink_grace.settle(printer_id, "inventory", held)
  2826. # Snapshot slots before delete — ORM attribute access after the
  2827. # commit would refresh against a deleted row.
  2828. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2829. for a in stale:
  2830. await db.delete(a)
  2831. if stale:
  2832. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2833. # Commit any changes (stale deletions and/or fingerprint updates)
  2834. await db.commit()
  2835. # Tell open browsers the assignment is gone (#2575). Only the manual
  2836. # REST assign/unassign endpoints broadcast this event; without it the
  2837. # frontend's spool-assignments cache keeps rendering the unlinked
  2838. # spool on the slot until an unrelated refetch — which reads exactly
  2839. # like "the fix didn't work" (reporter verified: a browser refresh
  2840. # after the swap showed the correct state all along).
  2841. for ams_id, tray_id in unlinked_slots:
  2842. await ws_manager.broadcast(
  2843. {
  2844. "type": "spool_assignment_changed",
  2845. "printer_id": printer_id,
  2846. "ams_id": ams_id,
  2847. "tray_id": tray_id,
  2848. }
  2849. )
  2850. except Exception as e:
  2851. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2852. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2853. """Delete Spoolman slot rows whose held removal has run its grace period.
  2854. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2855. talks to Spoolman for every tray; this only needs the local rows, so it
  2856. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2857. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2858. not in a slot the presence bit calls occupied -- and nothing else.
  2859. """
  2860. logger = logging.getLogger(__name__)
  2861. try:
  2862. async with async_session() as db:
  2863. from backend.app.api.routes.settings import get_setting
  2864. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2865. from backend.app.services.ams_slot_presence import spool_present
  2866. enabled = await get_setting(db, "spoolman_enabled")
  2867. if not enabled or enabled.lower() != "true":
  2868. return
  2869. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2870. if sync_mode and sync_mode != "auto":
  2871. return
  2872. trays: dict[tuple[int, int], dict] = {}
  2873. for ams_unit in ams_data or []:
  2874. if not isinstance(ams_unit, dict):
  2875. continue
  2876. for tray in ams_unit.get("tray", []):
  2877. if isinstance(tray, dict):
  2878. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2879. rows = (
  2880. (
  2881. await db.execute(
  2882. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2883. )
  2884. )
  2885. .scalars()
  2886. .all()
  2887. )
  2888. held: set[tuple] = set()
  2889. expired: list[tuple[int, int]] = []
  2890. for row in rows:
  2891. tray = trays.get((row.ams_id, row.tray_id))
  2892. if tray is None or printing_now:
  2893. continue
  2894. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2895. continue
  2896. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2897. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2898. continue
  2899. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2900. expired.append((row.ams_id, row.tray_id))
  2901. else:
  2902. held.add(hold_key)
  2903. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2904. if not expired:
  2905. return
  2906. # A statement rather than ORM deletes, like the sync pass: the two
  2907. # can overlap, and a row the other already removed must not fail
  2908. # this commit.
  2909. for ams_id, tray_id in expired:
  2910. await db.execute(
  2911. delete(SpoolmanSlotAssignment).where(
  2912. SpoolmanSlotAssignment.printer_id == printer_id,
  2913. SpoolmanSlotAssignment.ams_id == ams_id,
  2914. SpoolmanSlotAssignment.tray_id == tray_id,
  2915. )
  2916. )
  2917. await db.commit()
  2918. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2919. for ams_id, tray_id in expired:
  2920. await ws_manager.broadcast(
  2921. {
  2922. "type": "spool_assignment_changed",
  2923. "printer_id": printer_id,
  2924. "ams_id": ams_id,
  2925. "tray_id": tray_id,
  2926. }
  2927. )
  2928. except Exception as e:
  2929. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2930. async def _recheck_held_unlinks(printer_id: int) -> None:
  2931. """Re-run just the slot cleanup against the printer's current AMS state.
  2932. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2933. passes otherwise run only when the AMS hash changes, and a slot that went
  2934. empty and stayed empty may never change it again.
  2935. """
  2936. status = printer_manager.get_status(printer_id)
  2937. # A disconnected printer's state is its last report, not a new one: acting
  2938. # on it would "confirm" a removal nobody has seen for the whole grace
  2939. # period. Leave the holds; the first push after reconnecting decides.
  2940. if status is None or not status.connected:
  2941. return
  2942. ams_raw = status.raw_data.get("ams")
  2943. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2944. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2945. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2946. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2947. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2948. async def on_ams_change(printer_id: int, ams_data: list):
  2949. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2950. logger = logging.getLogger(__name__)
  2951. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2952. # still being charged, skip weight sync later. on_print_complete may pop
  2953. # _active_sessions during our awaits (#880).
  2954. from backend.app.services.usage_tracker import printer_is_charging
  2955. _print_active = printer_is_charging(printer_id)
  2956. # A slot that reports empty while a print is running is a filament runout,
  2957. # not a spool swap: the spool is still physically in the AMS, just
  2958. # consumed. Dropping either inventory backend's slot link there loses the
  2959. # only record of which spool fed the print, so the completion path can't
  2960. # charge the runout segment to anything. Both cleanup passes below consult
  2961. # this; computed once, up front, so neither depends on the other having run.
  2962. _unlink_state = printer_manager.get_status(printer_id)
  2963. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2964. # The session alone is not enough: a restart that finds a stale persisted
  2965. # session registers none for the print that is running.
  2966. _print_active = _print_active or printing_now
  2967. # MQTT relay - publish AMS change
  2968. try:
  2969. printer_info = printer_manager.get_printer(printer_id)
  2970. if printer_info:
  2971. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2972. except Exception:
  2973. pass # Don't fail AMS callback if MQTT fails
  2974. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2975. # This ensures frontend gets immediate updates when AMS slots are configured
  2976. try:
  2977. state = printer_manager.get_status(printer_id)
  2978. if state:
  2979. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2980. await ws_manager.send_printer_status(
  2981. printer_id,
  2982. printer_state_to_dict(
  2983. state,
  2984. printer_id,
  2985. printer_manager.get_model(printer_id),
  2986. printer_manager.get_drying_targets(printer_id),
  2987. ),
  2988. )
  2989. except Exception as e:
  2990. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2991. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2992. # Spools whose tag this pass assigned to a slot; their other slots are
  2993. # released below, once this printer's lock is let go (#3427).
  2994. rfid_assigned: list[tuple[int, tuple[int, int, int]]] = []
  2995. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2996. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2997. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2998. # "no existing assignment" for the same (printer, ams, tray) and race to
  2999. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  3000. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  3001. # bug stayed latent there. See services/ams_assignment_lock for details.
  3002. try:
  3003. async with get_ams_assignment_lock(printer_id), async_session() as db:
  3004. from sqlalchemy.orm import selectinload
  3005. from backend.app.api.routes.settings import get_setting
  3006. from backend.app.models.spool import Spool
  3007. from backend.app.models.spool_assignment import SpoolAssignment as SA
  3008. from backend.app.services.spool_tag_matcher import (
  3009. auto_assign_spool,
  3010. create_spool_from_tray,
  3011. find_matching_untagged_spool,
  3012. get_spool_by_tag,
  3013. is_bambu_tag,
  3014. is_valid_tag,
  3015. link_tag_to_inventory_spool,
  3016. tag_belongs_to_archived_spool,
  3017. )
  3018. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3019. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  3020. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  3021. if not _spoolman_on or _spoolman_on.lower() != "true":
  3022. for ams_unit in ams_data:
  3023. if not isinstance(ams_unit, dict):
  3024. continue
  3025. ams_id = int(ams_unit.get("id", 0))
  3026. for tray in ams_unit.get("tray", []):
  3027. if not isinstance(tray, dict):
  3028. continue
  3029. tray_id = int(tray.get("id", 0))
  3030. tag_uid = tray.get("tag_uid", "")
  3031. tray_uuid = tray.get("tray_uuid", "")
  3032. tray_info_idx = tray.get("tray_info_idx", "")
  3033. if not tray.get("tray_type"):
  3034. # Slot reported empty — drop any cached unknown-tag
  3035. # broadcast so reinserting the same spool re-prompts.
  3036. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3037. continue # Empty slot
  3038. # Check if assignment already exists for this slot
  3039. existing = await db.execute(
  3040. select(SA)
  3041. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3042. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  3043. )
  3044. existing_assignment = existing.scalar_one_or_none()
  3045. if existing_assignment:
  3046. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  3047. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  3048. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  3049. # Skip during active prints: the usage tracker handles deduction
  3050. # precisely via 3MF data on print completion. Without this guard the
  3051. # AMS remain% SET and the usage tracker ADD both fire from the same
  3052. # MQTT message, doubling the deduction (#880).
  3053. if _print_active:
  3054. continue
  3055. remain_raw = tray.get("remain")
  3056. if (
  3057. remain_raw is not None
  3058. and existing_assignment.spool
  3059. and not existing_assignment.spool.weight_locked
  3060. ):
  3061. try:
  3062. remain_val = int(remain_raw)
  3063. except (TypeError, ValueError):
  3064. remain_val = -1
  3065. if 1 <= remain_val <= 100:
  3066. lw = existing_assignment.spool.label_weight or 1000
  3067. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  3068. current_used = existing_assignment.spool.weight_used or 0
  3069. if new_used > current_used + 1:
  3070. # Rechecked in the statement: the spool was loaded
  3071. # before this, and a weight set by hand (or weighed)
  3072. # and locked since then must stay (WL-6).
  3073. result = cast(
  3074. CursorResult,
  3075. await db.execute(
  3076. update(Spool)
  3077. .where(
  3078. Spool.id == existing_assignment.spool_id,
  3079. Spool.weight_locked.is_not(True),
  3080. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3081. )
  3082. .values(weight_used=new_used)
  3083. ),
  3084. )
  3085. await db.commit()
  3086. if result.rowcount:
  3087. logger.info(
  3088. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3089. existing_assignment.spool_id,
  3090. current_used,
  3091. new_used,
  3092. remain_val,
  3093. )
  3094. await ws_manager.broadcast({"type": "inventory_changed"})
  3095. # A K-profile the slot lost (the default K after a reset or
  3096. # power cycle) is put back by kprofile_drift on the next idle
  3097. # push; a different real profile was picked on purpose and
  3098. # stays (#3219, item 44).
  3099. continue
  3100. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3101. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3102. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3103. # Only a spool already known by this tag is proven to be
  3104. # here; a material/colour match or a new spool is not
  3105. # grounds to take it out of other slots (#3427).
  3106. known_by_tag = spool is not None
  3107. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3108. # An archived spool still in the AMS: the slot
  3109. # stays free rather than adopting its tag.
  3110. continue
  3111. if not spool:
  3112. # Try matching an untagged inventory spool (same material/color)
  3113. spool = await find_matching_untagged_spool(db, tray)
  3114. if spool:
  3115. await link_tag_to_inventory_spool(db, spool, tray)
  3116. elif _auto_add_unknown:
  3117. spool = await create_spool_from_tray(db, tray)
  3118. else:
  3119. # Auto-add disabled: surface the slot so the
  3120. # user can add it manually via the UI.
  3121. await _broadcast_unknown_tag(
  3122. printer_id=printer_id,
  3123. ams_id=ams_id,
  3124. tray_id=tray_id,
  3125. tag_uid=tag_uid,
  3126. tray_uuid=tray_uuid,
  3127. tray_type=tray.get("tray_type"),
  3128. tray_color=tray.get("tray_color"),
  3129. tray_sub_brands=tray.get("tray_sub_brands"),
  3130. tray_count=len(ams_unit.get("tray", [])),
  3131. )
  3132. continue
  3133. # Slot matched (existing tag, untagged inventory
  3134. # match, or freshly auto-created spool) — drop any
  3135. # stale dedup so a future tag swap re-prompts.
  3136. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3137. await auto_assign_spool(
  3138. printer_id,
  3139. ams_id,
  3140. tray_id,
  3141. spool,
  3142. printer_manager,
  3143. db,
  3144. tray_info_idx=tray_info_idx,
  3145. )
  3146. await db.commit()
  3147. if known_by_tag:
  3148. rfid_assigned.append((spool.id, (printer_id, ams_id, tray_id)))
  3149. await ws_manager.broadcast(
  3150. {
  3151. "type": "spool_auto_assigned",
  3152. "printer_id": printer_id,
  3153. "ams_id": ams_id,
  3154. "tray_id": tray_id,
  3155. "spool_id": spool.id,
  3156. }
  3157. )
  3158. logger.info(
  3159. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3160. spool.id,
  3161. printer_id,
  3162. ams_id,
  3163. tray_id,
  3164. )
  3165. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3166. db, tag_uid, tray_uuid
  3167. ):
  3168. # Non-BL spool with some tag — let user choose (not
  3169. # an archived one's, whose slot stays free)
  3170. await _broadcast_unknown_tag(
  3171. printer_id=printer_id,
  3172. ams_id=ams_id,
  3173. tray_id=tray_id,
  3174. tag_uid=tag_uid,
  3175. tray_uuid=tray_uuid,
  3176. tray_type=tray.get("tray_type"),
  3177. tray_color=tray.get("tray_color"),
  3178. tray_sub_brands=tray.get("tray_sub_brands"),
  3179. tray_count=len(ams_unit.get("tray", [])),
  3180. )
  3181. # No-tag slots (generic non-RFID filament) are left alone:
  3182. # nothing to identify, prompting "+ Add" would just create
  3183. # ghost spools with empty tags on every confirm.
  3184. except Exception as e:
  3185. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3186. if rfid_assigned:
  3187. from backend.app.services.spool_relocation import INTERNAL, release_other_slots
  3188. for spool_id, slot in rfid_assigned:
  3189. try:
  3190. await release_other_slots(INTERNAL, spool_id, slot)
  3191. except Exception as e:
  3192. logger.warning("Releasing spool %s from its other slots failed: %s", spool_id, e, exc_info=True)
  3193. try:
  3194. async with async_session() as db:
  3195. from backend.app.api.routes.settings import get_setting
  3196. from backend.app.models.printer import Printer
  3197. # Check if Spoolman is enabled
  3198. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3199. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3200. return
  3201. # Check sync mode
  3202. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3203. if sync_mode and sync_mode != "auto":
  3204. return # Only sync on auto mode
  3205. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3206. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3207. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3208. # always owned by per-print tracking, never by AMS auto-sync. The
  3209. # setting is still read by the settings UI for backwards compat but
  3210. # has no effect on the sync path here.
  3211. # Get Spoolman URL
  3212. spoolman_url = await get_setting(db, "spoolman_url")
  3213. if not spoolman_url:
  3214. return
  3215. # Get or create Spoolman client
  3216. client = await get_spoolman_client()
  3217. if not client:
  3218. try:
  3219. client = await init_spoolman_client(spoolman_url)
  3220. except ValueError as exc:
  3221. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3222. return
  3223. # Check if Spoolman is reachable
  3224. if not await client.health_check():
  3225. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3226. return
  3227. # Get printer name for location
  3228. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3229. printer = result.scalar_one_or_none()
  3230. printer_name = printer.name if printer else f"Printer {printer_id}"
  3231. # OPTIMIZATION: Fetch all spools once before processing trays
  3232. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3233. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3234. try:
  3235. cached_spools = await client.get_spools()
  3236. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3237. except Exception as e:
  3238. logger.error(
  3239. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3240. printer_id,
  3241. e,
  3242. )
  3243. return
  3244. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3245. from sqlalchemy.orm import selectinload
  3246. from backend.app.models.spool_assignment import SpoolAssignment
  3247. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3248. from backend.app.services.ams_slot_presence import spool_present
  3249. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3250. # Built-in remaining weight, used by sync_ams_tray only when the
  3251. # firmware reports an unusable remain%/tray_weight for a slot.
  3252. #
  3253. # Left empty since #2812. This block runs in Spoolman mode only,
  3254. # and until then the built-in table was emptied on the switch, so
  3255. # there was never anything here to read and the fallback was inert.
  3256. # Preserving those rows makes it live again, and it is keyed by slot
  3257. # rather than by spool: after a mode switch the tray may well hold
  3258. # different filament, and ``create_spool`` writes ``remaining_weight``
  3259. # unconditionally, so a stale figure would be seeded into a brand new
  3260. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3261. # intent survives for whoever revisits the cross-mode fallback.
  3262. inventory_weights: dict[tuple[int, int], float] = {}
  3263. if not await spoolman_owns_assignments(db):
  3264. try:
  3265. assign_result = await db.execute(
  3266. select(SpoolAssignment)
  3267. .options(selectinload(SpoolAssignment.spool))
  3268. .where(SpoolAssignment.printer_id == printer_id)
  3269. )
  3270. for assignment in assign_result.scalars().all():
  3271. spool = assignment.spool
  3272. if spool and spool.label_weight > 0:
  3273. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3274. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3275. except Exception as e:
  3276. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3277. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3278. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3279. slot_map_read = False
  3280. try:
  3281. slot_result = await db.execute(
  3282. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3283. )
  3284. for slot in slot_result.scalars().all():
  3285. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3286. slot_map_read = True
  3287. except Exception as e:
  3288. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3289. # Sync each AMS tray and collect slot changes for DB persistence
  3290. synced = 0
  3291. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3292. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3293. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3294. for ams_unit in ams_data:
  3295. if not isinstance(ams_unit, dict):
  3296. continue
  3297. ams_id = int(ams_unit.get("id", 0))
  3298. trays = ams_unit.get("tray", [])
  3299. for tray_data in trays:
  3300. if not isinstance(tray_data, dict):
  3301. continue
  3302. tray_id_raw = int(tray_data.get("id", 0))
  3303. tray = client.parse_ams_tray(ams_id, tray_data)
  3304. if not tray:
  3305. # Empty tray slot — record for local assignment cleanup
  3306. # and drop any cached unknown-tag broadcast so a
  3307. # reinserted spool re-prompts.
  3308. #
  3309. # Not during a running print: a slot that empties there
  3310. # is a filament runout, and the spool is still in the
  3311. # AMS. `spoolman_slot_assignments` is how a tag-less
  3312. # spool assigned through the Bambuddy UI is resolved at
  3313. # completion (#1459), so deleting the row mid-print
  3314. # loses the runout segment's usage — the same failure
  3315. # the internal inventory's auto-unlink had.
  3316. #
  3317. # Nor when firmware's presence bit says the slot is
  3318. # occupied. parse_ams_tray calls a tray with no type or
  3319. # no colour empty, and a spool the AMS cannot read has
  3320. # neither until something configures it — so a tag-less
  3321. # spool assigned through the UI had its row deleted by
  3322. # the first idle push after it was inserted. Same
  3323. # deletion as the internal inventory's in #3100, same
  3324. # answer, so the two modes stay in step.
  3325. #
  3326. # And only once the slot has stayed empty for the grace
  3327. # period -- the internal inventory's #3186 answer, for
  3328. # the same one-push blank.
  3329. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3330. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3331. if not printing_now and (
  3332. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3333. ):
  3334. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3335. empty_slots.append((ams_id, tray_id_raw))
  3336. else:
  3337. spoolman_held.add(hold_key)
  3338. logger.info(
  3339. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3340. "unlinking if it is still empty in %ds",
  3341. ams_id,
  3342. tray_id_raw,
  3343. linked_spool,
  3344. int(slot_unlink_grace.GRACE_SECONDS),
  3345. )
  3346. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3347. continue
  3348. spool_tag = (
  3349. tray.tray_uuid
  3350. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3351. else tray.tag_uid
  3352. )
  3353. # Provide the hint only when no RFID is available
  3354. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3355. try:
  3356. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3357. result = await client.sync_ams_tray(
  3358. tray,
  3359. printer_name,
  3360. db,
  3361. # Per-print tracking is the only weight writer (#1119).
  3362. # AMS auto-sync still maintains spool metadata / slot
  3363. # assignments but no longer touches remaining_weight.
  3364. disable_weight_sync=True,
  3365. cached_spools=cached_spools,
  3366. inventory_remaining=inv_remaining,
  3367. spoolman_spool_id_hint=hint,
  3368. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3369. )
  3370. if result is None and spool_tag and not auto_add_unknown_rfid:
  3371. # Spoolman skipped auto-create per user setting — surface
  3372. # the slot so the UI can offer "+ Add to inventory".
  3373. await _broadcast_unknown_tag(
  3374. printer_id=printer_id,
  3375. ams_id=ams_id,
  3376. tray_id=tray.tray_id,
  3377. tag_uid=tray.tag_uid or "",
  3378. tray_uuid=tray.tray_uuid or "",
  3379. tray_type=tray.tray_type,
  3380. tray_color=tray.tray_color,
  3381. tray_sub_brands=tray.tray_sub_brands,
  3382. tray_count=len(trays),
  3383. )
  3384. elif result:
  3385. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3386. if result:
  3387. synced += 1
  3388. if result.get("id"):
  3389. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3390. # If a new spool was created, add it to the cache
  3391. # so subsequent trays can find it if they reference the same tag
  3392. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3393. if not spool_exists:
  3394. cached_spools.append(result)
  3395. logger.debug(
  3396. "[Printer %s] Added newly created spool %s to cache",
  3397. printer_id,
  3398. result["id"],
  3399. )
  3400. # Reconcile slot_preset_mappings (the same row internal
  3401. # mode keeps in sync via inventory + spool_tag_matcher).
  3402. # Without this the slot card surfaces the previous spool's
  3403. # preset name — same bug shape, different inventory mode.
  3404. from backend.app.services.slot_preset_writer import (
  3405. upsert_slot_preset_for_spoolman_spool,
  3406. )
  3407. await upsert_slot_preset_for_spoolman_spool(
  3408. db=db,
  3409. spoolman_spool=result,
  3410. tray_info_idx=tray.tray_info_idx or "",
  3411. tray_sub_brands=tray.tray_sub_brands or "",
  3412. tray_type=tray.tray_type or "",
  3413. printer_id=printer_id,
  3414. ams_id=ams_id,
  3415. tray_id=tray.tray_id,
  3416. )
  3417. except Exception as e:
  3418. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3419. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3420. if synced > 0:
  3421. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3422. # Persist slot assignment changes to the local table: only slots
  3423. # whose spool this pass changed, and only while they still hold what
  3424. # it read before awaiting Spoolman, so a spool assigned by hand in
  3425. # between stays (SSA-3). The changed slots are announced: the slot
  3426. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3427. # tray, so with no event it kept the previous spool's preset name.
  3428. if slot_changes or empty_slots:
  3429. from backend.app.services.spoolman_slot_sync import write_slot_results
  3430. try:
  3431. await write_slot_results(
  3432. db,
  3433. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3434. if slot_map_read
  3435. else None,
  3436. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3437. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3438. )
  3439. except Exception as e:
  3440. await db.rollback()
  3441. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3442. except Exception as e:
  3443. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3444. # Largest finish photo attached to a notification; a bigger one is still linked.
  3445. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3446. async def _finish_photo_for_notification(
  3447. db, archive, archive_id: int, filename: str
  3448. ) -> tuple[str | None, bytes | None]:
  3449. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3450. With authentication off the link is the archive's own photo route, as it
  3451. always was: it opens without a login and doesn't expire. With
  3452. authentication on that route needs a media token, which nothing tapping a
  3453. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3454. link only ever answered 401. The photo is then saved as a notification
  3455. photo as well (utils/notification_photos.py) and the link points there: an
  3456. unguessable name that opens this one photo and nothing else, for 3 days.
  3457. The link is relative when no External URL is set. Bytes over
  3458. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3459. ``(None, None)`` when the photo can't be found.
  3460. """
  3461. from backend.app.api.routes.settings import get_setting
  3462. from backend.app.core.auth import is_auth_enabled
  3463. from backend.app.utils.archive_paths import find_archive_photo
  3464. from backend.app.utils.notification_photos import save_notification_photo
  3465. log = logging.getLogger(__name__)
  3466. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3467. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3468. photo_bytes: bytes | None = None
  3469. try:
  3470. photo_path = find_archive_photo(archive, filename)
  3471. if photo_path is not None:
  3472. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3473. except Exception as e:
  3474. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3475. try:
  3476. auth_on = await is_auth_enabled(db)
  3477. except Exception:
  3478. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3479. if auth_on:
  3480. url = None
  3481. if photo_bytes:
  3482. try:
  3483. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3484. url = f"{base}/api/v1/notifications/photos/{name}"
  3485. except Exception as e:
  3486. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3487. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3488. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3489. return url, None
  3490. if photo_bytes:
  3491. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3492. return url, photo_bytes
  3493. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3494. """Capture a camera snapshot for notification image attachment.
  3495. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3496. Uses: external camera > buffered frame > fresh capture.
  3497. Turns the chamber light on for the picture when the printer asks for it
  3498. (#1655). ``light=False`` is for callers that capture all through a print,
  3499. where the light would flash with every frame.
  3500. """
  3501. if not printer:
  3502. return None
  3503. async with camera_light(printer if light else None):
  3504. return await _capture_snapshot_frame(printer_id, printer, logger)
  3505. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3506. """The capture behind ``_capture_snapshot_for_notification``."""
  3507. try:
  3508. from backend.app.api.routes.settings import get_setting
  3509. async with async_session() as db:
  3510. capture_enabled = await get_setting(db, "capture_finish_photo")
  3511. if capture_enabled is not None and capture_enabled.lower() != "true":
  3512. return None
  3513. # Try external camera first
  3514. if printer.external_camera_enabled and printer.external_camera_url:
  3515. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3516. from backend.app.api.routes.camera import live_frame_for_capture
  3517. from backend.app.services.external_camera import capture_frame
  3518. # An external camera allows one reader, so capturing while a viewer
  3519. # is attached fails (#2707). A None here falls through to the paths
  3520. # below exactly as a failed capture did.
  3521. defer, buffered = live_frame_for_capture(printer_id)
  3522. if defer:
  3523. frame_data = buffered
  3524. else:
  3525. frame_data = await capture_frame(
  3526. printer.external_camera_url,
  3527. printer.external_camera_type or "mjpeg",
  3528. snapshot_url=printer.external_camera_snapshot_url,
  3529. )
  3530. if frame_data and len(frame_data) <= 2_500_000:
  3531. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3532. return _apply_camera_rotation(frame_data, printer, logger)
  3533. # Try buffered frame from active stream
  3534. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3535. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3536. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3537. buffered_frame = get_buffered_frame(printer_id)
  3538. if (active_for_printer or active_chamber) and buffered_frame:
  3539. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3540. if len(buffered_frame) <= 2_500_000:
  3541. return _apply_camera_rotation(buffered_frame, printer, logger)
  3542. # Fresh capture from printer camera
  3543. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3544. from backend.app.services.camera import capture_camera_frame_bytes
  3545. frame_data = await capture_camera_frame_bytes(
  3546. printer.ip_address, printer.access_code, printer.model, timeout=15
  3547. )
  3548. if frame_data and len(frame_data) <= 2_500_000:
  3549. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3550. return _apply_camera_rotation(frame_data, printer, logger)
  3551. except Exception as e:
  3552. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3553. return None
  3554. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3555. """#1867: bank a recent in-print camera frame for the finish photo.
  3556. Called on every layer change and (#2547) on every print-progress advance.
  3557. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3558. path has a pre-End-G-code image for prints that end with a plate swap.
  3559. Both drivers are print telemetry that stops the instant printing ends: no
  3560. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3561. plate swap) executes. So the last banked frame is always the finished print,
  3562. never the swapped plate — that property is what the #1867 path relies on and
  3563. it must survive any change to the throttle below.
  3564. Layer changes alone were not enough: they stop when the *final* layer
  3565. begins, which on a three-minute last layer left the bank stale by the whole
  3566. length of that layer (#2547). Progress keeps ticking through it.
  3567. Best-effort: any failure just leaves the previous banked frame.
  3568. """
  3569. logger = logging.getLogger(__name__)
  3570. client = printer_manager.get_client(printer_id)
  3571. state = client.state if client else None
  3572. if not state or state.state != "RUNNING":
  3573. return
  3574. # Only during actual extrusion — firmware ticks layer_num during the
  3575. # pre-print calibration sequence, whose sub-stages are non-zero.
  3576. if state.mc_print_sub_stage not in (None, 0):
  3577. return
  3578. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3579. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3580. # now that progress advances also drive banking, that exemption would fire a
  3581. # camera grab on every percent tick of the last layer. Bambu printers accept
  3582. # one RTSP client at a time, so each grab contends with the live view.
  3583. now = time.monotonic()
  3584. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3585. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3586. return
  3587. total = state.total_layers or 0
  3588. try:
  3589. async with async_session() as db:
  3590. from backend.app.models.printer import Printer
  3591. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3592. printer = result.scalar_one_or_none()
  3593. if not printer:
  3594. return
  3595. # Reuses the notification snapshot path, which honours the
  3596. # `capture_finish_photo` setting (returns None when disabled) so we
  3597. # don't bank frames the user never asked for. Without the chamber light
  3598. # (#1655): this runs every 25 seconds for the whole print.
  3599. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3600. if frame:
  3601. _inprint_frame_bank[printer_id] = frame
  3602. _inprint_frame_bank_ts[printer_id] = now
  3603. logger.debug(
  3604. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3605. printer_id,
  3606. layer_num,
  3607. total,
  3608. len(frame),
  3609. )
  3610. except Exception as e:
  3611. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3612. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3613. """Apply camera rotation to snapshot image if configured."""
  3614. from backend.app.services.camera import apply_camera_rotation
  3615. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3616. async def _send_print_start_notification(
  3617. printer_id: int,
  3618. data: dict,
  3619. archive_data: dict | None = None,
  3620. logger=None,
  3621. ):
  3622. """Helper to send print start notification with optional archive data."""
  3623. if logger is None:
  3624. logger = logging.getLogger(__name__)
  3625. try:
  3626. async with async_session() as db:
  3627. from backend.app.models.printer import Printer
  3628. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3629. printer = result.scalar_one_or_none()
  3630. printer_name = printer.name if printer else f"Printer {printer_id}"
  3631. # Capture camera snapshot for notification image attachment
  3632. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3633. if image_data:
  3634. if archive_data is None:
  3635. archive_data = {}
  3636. archive_data["image_data"] = image_data
  3637. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3638. # Send user-specific email notification for print start
  3639. if archive_data and archive_data.get("created_by_id"):
  3640. await notification_service.send_user_print_email(
  3641. event_type="user_print_start",
  3642. created_by_id=archive_data["created_by_id"],
  3643. printer_name=printer_name,
  3644. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3645. db=db,
  3646. )
  3647. except Exception as e:
  3648. logger.warning("Notification on_print_start failed: %s", e)
  3649. async def _dispatch_user_print_email(
  3650. status: str,
  3651. created_by_id: int | None,
  3652. printer_name: str,
  3653. filename: str,
  3654. db,
  3655. image_data: bytes | None = None,
  3656. finish_photo_url: str | None = None,
  3657. ) -> None:
  3658. """Send a user-specific print-completion email based on print status.
  3659. Maps the normalised print status to the correct event type and delegates
  3660. to :meth:`NotificationService.send_user_print_email`. A single helper
  3661. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3662. "stopped"`` dispatch block at every call site.
  3663. Does nothing if *created_by_id* is ``None``.
  3664. """
  3665. if created_by_id is None:
  3666. return
  3667. if status == "completed":
  3668. event_type = "user_print_complete"
  3669. elif status == "failed":
  3670. event_type = "user_print_failed"
  3671. elif status in ("stopped", "aborted", "cancelled"):
  3672. event_type = "user_print_stopped"
  3673. else:
  3674. return
  3675. await notification_service.send_user_print_email(
  3676. event_type=event_type,
  3677. created_by_id=created_by_id,
  3678. printer_name=printer_name,
  3679. filename=filename,
  3680. db=db,
  3681. image_data=image_data,
  3682. finish_photo_url=finish_photo_url,
  3683. )
  3684. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3685. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3686. try:
  3687. from backend.app.services.archive import extract_printable_objects_from_archive
  3688. client = printer_manager.get_client(printer_id)
  3689. if not client:
  3690. return
  3691. # Extract with positions for UI overlay, scoped to the plate that
  3692. # is printing — resolve_plate_id is the same resolver /cover uses,
  3693. # so the object list can't disagree with the thumbnail it is drawn
  3694. # over (#2522).
  3695. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3696. app_settings.base_dir / archive.file_path,
  3697. plate_number=resolve_plate_id(client.state),
  3698. )
  3699. if printable_objects:
  3700. client.state.printable_objects = printable_objects
  3701. client.state.printable_objects_bbox_all = bbox_all
  3702. client.state.skipped_objects = []
  3703. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3704. except Exception as e:
  3705. logger.debug("Failed to extract printable objects from archive: %s", e)
  3706. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3707. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3708. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3709. handler must not wait for it. Kept only while the printer is still on
  3710. the print they were read for: a new print replaces the list.
  3711. ``warned_layers``: pauses this print was already warned about, kept on its
  3712. archive, so a restart does not send the heads-up again.
  3713. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3714. is on. Its pauses up to there are behind it, though the printer's layer
  3715. reads 0 until it reports the next one.
  3716. """
  3717. client = printer_manager.get_client(printer_id)
  3718. if not client:
  3719. return
  3720. state = client.state
  3721. read_for = state.pause_points
  3722. try:
  3723. plate_id = resolve_plate_id(state)
  3724. except Exception:
  3725. # Never at the cost of the print-start handler this runs inside.
  3726. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3727. return
  3728. async def _load() -> None:
  3729. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3730. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3731. if state.pause_points is not read_for:
  3732. return
  3733. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3734. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3735. if points:
  3736. logging.getLogger(__name__).info(
  3737. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3738. len(points),
  3739. printer_id,
  3740. [p.layer for p in points],
  3741. )
  3742. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3743. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3744. """Pauses for a print start taken as the resumption of a running print.
  3745. A restart while the print was paused makes its resume look like a new
  3746. print (#2984): the pauses warned about and passed are kept from before.
  3747. """
  3748. client = printer_manager.get_client(printer_id)
  3749. state = client.state if client else None
  3750. _load_pauses_from_3mf(
  3751. app_settings.base_dir / archive.file_path,
  3752. printer_id,
  3753. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3754. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3755. )
  3756. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3757. """Put the skip-objects list back after a restart mid-print.
  3758. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3759. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3760. which the #1304 guard suppresses on the first RUNNING push after startup.
  3761. Everything else this hook restores (the archive, the usage-tracking session,
  3762. the timelapse baseline) was already handled; the object list was not, so a
  3763. restart mid-print took skip-objects away for the rest of that print.
  3764. Nothing recovered it either: the printer card gates its Skip button on the
  3765. object count, and the one endpoint that can rebuild the list is reachable
  3766. only from the modal that button opens.
  3767. The archive is the running print's as ``running_print_archive`` finds it:
  3768. by subtask_id, or for a print that reports none by the archive bound to it
  3769. (#3327), never by name: a leftover ``status="printing"`` row from a
  3770. completion we never saw must not hand this print someone else's objects.
  3771. After a restart that binding exists only for Bambuddy's own prints, so a
  3772. print that reports no subtask_id loads nothing rather than a guess; the
  3773. reload path on ``GET /print/objects`` covers that case on demand.
  3774. """
  3775. client = printer_manager.get_client(printer_id)
  3776. if client is None or (client.state.printable_objects and client.state.pause_points):
  3777. return
  3778. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3779. if archive is not None and archive.file_path:
  3780. if not client.state.printable_objects:
  3781. _load_objects_from_archive(archive, printer_id, logger)
  3782. # The slicer's pauses are in-memory only as well (#2984).
  3783. if not client.state.pause_points:
  3784. _load_pauses_from_3mf(
  3785. app_settings.base_dir / archive.file_path,
  3786. printer_id,
  3787. warned_layers=pause_eta.warned_layers_of(archive, state),
  3788. )
  3789. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3790. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3791. # past it; the second covers a handshake that failed again on the way back and
  3792. # armed a fresh one. Module-level so tests can shrink them.
  3793. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3794. # Retry ladder for the other temporary give-up: the file service answered and
  3795. # the transfer still did not finish, which at print start is usually the printer
  3796. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3797. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3798. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3799. # two cover a printer that stays busy well into the print.
  3800. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3801. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3802. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3803. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3804. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3805. # by view, so two views race), the cool-off retry task, and print completion.
  3806. # Without this they each read file_path == "" and each run a full copy, so the row
  3807. # ends up pointing at one timestamped directory while the others sit orphaned.
  3808. #
  3809. # Keyed by printer rather than archive because a printer runs one print at a time,
  3810. # which makes the two equally strong here — and it bounds the dict by printer
  3811. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3812. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3813. # resuming, so "no waiters" is not a question this API can answer.
  3814. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3815. # How many of a printer's newest archives a touchscreen reprint is compared
  3816. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3817. # print start from reading a long history's extra_data.
  3818. _REPEAT_LOOKBACK = 200
  3819. async def _archived_3mf_for_repeat(
  3820. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3821. ):
  3822. """The newest archive of the job this printer is running again, with its 3MF.
  3823. A "Print again" on the printer's screen never names the file on the card:
  3824. it reports its own history copy under a generic name
  3825. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3826. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3827. not the card file's name, so every lookup built from it misses (#3307).
  3828. An earlier run that was archived recorded that same title and plate in its
  3829. ``_print_data``, and holds the 3MF.
  3830. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3831. known on both sides must agree: the same title and plate re-sliced is
  3832. another job. None when nothing matches.
  3833. """
  3834. from backend.app.models.archive import PrintArchive
  3835. if not subtask_name or not gcode_file:
  3836. return None
  3837. rows = (
  3838. (
  3839. await db.execute(
  3840. select(PrintArchive)
  3841. .where(
  3842. PrintArchive.printer_id == printer_id,
  3843. PrintArchive.deleted_at.is_(None),
  3844. PrintArchive.file_path.isnot(None),
  3845. PrintArchive.file_path != "",
  3846. )
  3847. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3848. .limit(_REPEAT_LOOKBACK)
  3849. )
  3850. )
  3851. .scalars()
  3852. .all()
  3853. )
  3854. for archive in rows:
  3855. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3856. run = extra.get("_print_data")
  3857. if not isinstance(run, dict):
  3858. continue
  3859. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3860. continue
  3861. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3862. continue
  3863. if not (app_settings.base_dir / archive.file_path).is_file():
  3864. continue
  3865. return archive
  3866. return None
  3867. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3868. """Fill in a no-3MF archive from a 3MF that turned up later.
  3869. Returns True when the row was upgraded. Safe to call speculatively: it
  3870. verifies the archive still exists, is still a fallback, and that the file
  3871. is a readable 3MF before touching anything.
  3872. Serialised per printer — see ``_fallback_recovery_locks``.
  3873. """
  3874. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3875. async with lock:
  3876. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3877. async def _recover_fallback_archive_locked(
  3878. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3879. ) -> bool:
  3880. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3881. ``price`` is False when the print's end is being handled: the archive
  3882. still reads "printing" then, and its end prices it.
  3883. """
  3884. import zipfile
  3885. from backend.app.models.archive import PrintArchive
  3886. from backend.app.services.archive import ArchiveService
  3887. logger = logging.getLogger(__name__)
  3888. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3889. return False
  3890. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3891. # A truncated or half-written download is worse than no download: it
  3892. # would replace an honest empty archive with wrong metadata.
  3893. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3894. return False
  3895. async with async_session() as db:
  3896. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3897. if archive is None or archive.deleted_at is not None:
  3898. return False
  3899. if archive.file_path:
  3900. # Already recovered, or never was a fallback. Either way there is a
  3901. # real 3MF attached and overwriting it is not this function's job.
  3902. return False
  3903. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3904. service = ArchiveService(db)
  3905. recovered = await service.archive_print(
  3906. printer_id=printer_id,
  3907. source_file=source_3mf,
  3908. print_data={**print_data, "status": archive.status or "printing"},
  3909. subtask_id=archive.subtask_id,
  3910. update_archive_id=archive.id,
  3911. )
  3912. if recovered is None:
  3913. return False
  3914. logger.info(
  3915. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3916. archive_id,
  3917. source_3mf,
  3918. recovered.file_size,
  3919. )
  3920. # Spoolman's tracking stored no 3MF usage at print start and would
  3921. # charge the AMS remain% change; the built-in tracker reads the archive
  3922. # at completion and needs nothing. Also at the print's end (``price``
  3923. # False): that recovery runs inside the close-out, before the charge.
  3924. try:
  3925. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3926. from backend.app.services.usage_tracker import is_completing
  3927. await attach_recovered_3mf(
  3928. printer_id,
  3929. recovered.id,
  3930. recovered.file_path,
  3931. db,
  3932. printer_manager,
  3933. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3934. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3935. )
  3936. except Exception:
  3937. logger.warning(
  3938. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3939. )
  3940. if price and recovered.status == "printing" and recovered.file_path:
  3941. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3942. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3943. if price and recovered.status == "printing":
  3944. # Print start priced it from the default rate, having no 3MF to
  3945. # estimate from; now it has one. An ended print is left alone: its
  3946. # end prices it. A print Bambuddy didn't dispatch has no start
  3947. # plate; the one the archive just read from the 3MF stands in.
  3948. _schedule_archive_cost_estimate(
  3949. printer_id,
  3950. recovered.id,
  3951. printer_manager,
  3952. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3953. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3954. session_factory=async_session,
  3955. )
  3956. # `archive_updated`, not `archive_created` — the row was already on the
  3957. # Archives page as an empty card and is now filled in, not new.
  3958. await ws_manager.send_archive_updated(
  3959. {
  3960. "id": recovered.id,
  3961. "printer_id": recovered.printer_id,
  3962. "filename": recovered.filename,
  3963. "print_name": recovered.print_name,
  3964. "status": recovered.status,
  3965. }
  3966. )
  3967. return True
  3968. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3969. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3970. Called from the paths that pull a 3MF for a print that is already under way
  3971. — chiefly the cover endpoint, which downloads the very file the archive flow
  3972. could not get and, before #2957, used it for a thumbnail and nothing else.
  3973. The bytes are already local, so this costs a parse and a row update.
  3974. No-op when the running print has a real archive, which is the common case.
  3975. """
  3976. from backend.app.models.archive import PrintArchive
  3977. logger = logging.getLogger(__name__)
  3978. # `_active_prints` is keyed on the raw names seen at print start — the
  3979. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3980. # Callers here arrive with whichever variant their own path produced, so
  3981. # match on the same normalization the download cache uses rather than on an
  3982. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3983. # endpoint find an archive registered under "Desktop_Goose".
  3984. wanted = normalize_3mf_name(name)
  3985. archive_id = None
  3986. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3987. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3988. archive_id = value
  3989. break
  3990. if archive_id is None:
  3991. return False
  3992. async with async_session() as db:
  3993. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3994. # Cheap pre-check so the common case (a normal archive) does no work.
  3995. if archive is None or archive.file_path or archive.deleted_at is not None:
  3996. return False
  3997. try:
  3998. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3999. except Exception as e:
  4000. # Recovery is opportunistic. A failure here must never take down the
  4001. # caller, which is usually just trying to render a thumbnail.
  4002. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  4003. return False
  4004. def _schedule_fallback_3mf_retry(
  4005. printer_id: int,
  4006. archive_id: int,
  4007. filenames: list[str],
  4008. delays: tuple[float, ...] | None = None,
  4009. reason: str = REASON_FTPS_COOLOFF,
  4010. ) -> None:
  4011. """Re-attempt the 3MF download after a temporary give-up.
  4012. ``reason`` says which give-up this is, and picks the default ladder: an
  4013. FTPS cool-off has to be waited out, while a transfer that timed out under
  4014. contention is worth asking about again straight away (#3063). It is only
  4015. read for the ladder and the log line -- the retry itself is identical, since
  4016. in both cases the file is on the printer and the last attempt at it failed
  4017. for a reason that does not last.
  4018. """
  4019. logger = logging.getLogger(__name__)
  4020. if delays is None:
  4021. delays = (
  4022. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  4023. if reason == REASON_FTP_TRANSFER_FAILED
  4024. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  4025. )
  4026. async def _retry() -> None:
  4027. from backend.app.models.archive import PrintArchive
  4028. from backend.app.models.printer import Printer
  4029. for delay in delays:
  4030. await asyncio.sleep(delay)
  4031. async with async_session() as db:
  4032. archive = (
  4033. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4034. ).scalar_one_or_none()
  4035. if archive is None or archive.deleted_at is not None or archive.file_path:
  4036. return
  4037. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  4038. if printer is None:
  4039. return
  4040. # Read the fields while the session is open rather than touching
  4041. # a detached instance minutes later, mid-download.
  4042. printer_ip = printer.ip_address
  4043. printer_code = printer.access_code
  4044. printer_model = printer.model
  4045. # Someone else may have fetched it in the meantime — the cover
  4046. # endpoint routinely does, and its copy is the same bytes.
  4047. for name in filenames:
  4048. cached = get_cached_3mf(printer_id, name)
  4049. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  4050. return
  4051. if ftps_handshake_blocked(printer_ip):
  4052. logger.info(
  4053. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  4054. printer_id,
  4055. archive_id,
  4056. )
  4057. continue
  4058. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  4059. for candidate in filenames:
  4060. # Bare name only. These come from the print-start flow, which
  4061. # already strips the path, but the local temp write must not
  4062. # depend on that holding for every future caller — a name that
  4063. # is absolute or contains ".." would otherwise escape the data
  4064. # volume via the `/` operator.
  4065. name = Path(candidate).name
  4066. if not name or name in (".", ".."):
  4067. continue
  4068. if not name.endswith(".3mf"):
  4069. name = f"{name}.3mf"
  4070. temp_path = app_settings.archive_dir / "temp" / name
  4071. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4072. try:
  4073. hit = await download_file_try_paths_async(
  4074. printer_ip,
  4075. printer_code,
  4076. ftp_probe_paths(name),
  4077. temp_path,
  4078. socket_timeout=ftp_timeout,
  4079. printer_model=printer_model,
  4080. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  4081. )
  4082. except Exception as e:
  4083. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  4084. continue
  4085. if not hit:
  4086. continue
  4087. cache_3mf_download(printer_id, name, temp_path)
  4088. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  4089. return
  4090. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  4091. async def _guarded() -> None:
  4092. try:
  4093. await _retry()
  4094. except asyncio.CancelledError:
  4095. raise
  4096. except Exception as e:
  4097. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4098. finally:
  4099. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4100. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4101. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4102. if existing and not existing.done():
  4103. existing.cancel()
  4104. task = asyncio.create_task(_guarded())
  4105. _fallback_3mf_retry_tasks[printer_id] = task
  4106. logger.info(
  4107. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4108. archive_id,
  4109. reason,
  4110. printer_id,
  4111. ", ".join(f"{d:g}s" for d in delays),
  4112. )
  4113. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4114. """Whether an archive created here should ask for the print's outcome (#1898).
  4115. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4116. branches below: a queued job already has its archive and takes the
  4117. expected-print branch, where the queue item's own ``confirm_outcome``
  4118. decides. The queue is still consulted, because a restart mid-print empties
  4119. ``_expected_prints`` — without the check the setting could override a queue
  4120. item that deliberately has the flag off. Any failure answers "don't ask":
  4121. an unwanted prompt is worse than a missing one, and this must never be the
  4122. reason a print goes unarchived.
  4123. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4124. leaves one behind when a completion cannot be matched to it
  4125. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4126. only takes it back once the printer has sat connected and terminal for
  4127. minutes. Until then every screen-started print on that printer would
  4128. silently lose its prompt, so the row is held against ``observed_name`` by
  4129. the same comparison a completion uses: a positive disagreement means the row
  4130. is about some other run and this print is external after all.
  4131. """
  4132. logger = logging.getLogger(__name__)
  4133. try:
  4134. # A savepoint rather than a rollback of the caller's transaction on
  4135. # failure: a failed statement leaves the transaction unusable, but a
  4136. # full rollback also expires every object the caller has loaded (the
  4137. # printer, the archive it just created), and on an async session the
  4138. # next attribute read then raises instead of reloading. Everything here
  4139. # is a read, so undoing the savepoint loses nothing.
  4140. async with db.begin_nested():
  4141. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4142. except Exception as e:
  4143. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4144. return False
  4145. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4146. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4147. from backend.app.api.routes.settings import get_setting, setting_is_true
  4148. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4149. return False
  4150. from backend.app.models.print_queue import PrintQueueItem
  4151. dispatched_here = await db.scalar(
  4152. select(PrintQueueItem)
  4153. .where(
  4154. PrintQueueItem.printer_id == printer_id,
  4155. PrintQueueItem.status == "printing",
  4156. )
  4157. .limit(1)
  4158. )
  4159. if dispatched_here is None:
  4160. return True
  4161. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4162. observed = (observed_name or "").strip()
  4163. if not expected or not observed or _dispatched_name_matches_echo(expected, observed):
  4164. logger.info(
  4165. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4166. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4167. printer_id,
  4168. dispatched_here.id,
  4169. )
  4170. return False
  4171. logger.info(
  4172. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4173. "%r; treating this as an externally started print.",
  4174. dispatched_here.id,
  4175. printer_id,
  4176. expected,
  4177. observed,
  4178. )
  4179. return True
  4180. async def _dispatch_outcome_confirmation_safely(
  4181. db,
  4182. printer_id: int,
  4183. printer_name: str,
  4184. data: dict,
  4185. archive_id: int,
  4186. archive_data: dict | None = None,
  4187. run_id: int | None = None,
  4188. ) -> None:
  4189. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4190. The completion task sends the per-user print email on the same session
  4191. right after the prompt. A failed statement in the prompt leaves that
  4192. session needing a rollback, and without one the email step fails with
  4193. PendingRollbackError; the prompt is the optional part, so it must not be
  4194. the reason the email never goes out.
  4195. """
  4196. try:
  4197. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4198. except Exception as e:
  4199. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4200. try:
  4201. await db.rollback()
  4202. except Exception:
  4203. pass
  4204. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4205. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4206. who may change everyone's archives. None (everyone on the printer) with auth
  4207. off, or for a print nobody owns."""
  4208. from sqlalchemy.orm import selectinload
  4209. from backend.app.core.auth import is_auth_enabled
  4210. from backend.app.core.permissions import Permission
  4211. from backend.app.models.user import User
  4212. if owner_id is None or not await is_auth_enabled(db):
  4213. return None
  4214. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4215. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4216. async def dispatch_outcome_confirmation(
  4217. db,
  4218. printer_id: int,
  4219. printer_name: str,
  4220. data: dict,
  4221. archive_id: int,
  4222. archive_data: dict | None = None,
  4223. *,
  4224. run_id: int | None = None,
  4225. ) -> bool:
  4226. """Emit the post-print outcome prompt for a completed print (#1898).
  4227. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4228. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4229. for a print Bambuddy did not start, copied onto the run at its start) and
  4230. ``user_verdict`` being unset is what makes the question still open. Mints
  4231. the run's capability token the one-tap verdict links carry: plates of one
  4232. archive each have their own question. Without a run, the archive's, as
  4233. before runs.
  4234. Lives here rather than inline in ``on_print_complete``'s notification task
  4235. because that task swallows every exception: extracted, the gate and the two
  4236. emissions can be driven by a test, which is the only thing standing between
  4237. a regression here and a farm that quietly stops asking.
  4238. Returns whether a prompt was sent.
  4239. """
  4240. logger = logging.getLogger(__name__)
  4241. from backend.app.models.archive import PrintArchive
  4242. from backend.app.models.print_log import PrintLogEntry
  4243. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4244. if confirm_archive is None:
  4245. return False
  4246. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4247. if run is not None and run.archive_id != archive_id:
  4248. run = None
  4249. # The run carries the opt-in from its start; one logged before it did
  4250. # (None) asks as its archive does.
  4251. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4252. holder = run if run is not None else confirm_archive
  4253. if not (asks.confirm_requested and holder.user_verdict is None):
  4254. return False
  4255. import secrets as _secrets
  4256. # A spent token stays on the row so the one-tap route can recognise it, so
  4257. # "has a token" no longer means "answerable". A prompt going out now needs a
  4258. # live one: mint a new token whenever the stored one is already spent, or
  4259. # every button in the new message would land on the already-answered page.
  4260. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4261. holder.confirm_token = _secrets.token_urlsafe(32)
  4262. holder.confirm_token_used_at = None
  4263. await db.commit()
  4264. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4265. base = await get_external_base_url(db)
  4266. if not await get_setting(db, "external_url"):
  4267. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4268. # absolute URL, so an unconfigured install used to get a message body
  4269. # with two unusable relative paths and no buttons at all. The shared
  4270. # fallback at least produces tappable links; say which setting makes
  4271. # them resolve from a phone.
  4272. logger.warning(
  4273. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4274. "Set Settings → External URL so they resolve away from this host.",
  4275. base,
  4276. )
  4277. token = holder.confirm_token
  4278. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4279. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4280. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4281. await ws_manager.send_print_confirm_request(
  4282. printer_id,
  4283. {
  4284. "archive_id": archive_id,
  4285. "run_id": run.id if run is not None else None,
  4286. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4287. },
  4288. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4289. )
  4290. await notification_service.on_print_confirm_request(
  4291. printer_id,
  4292. printer_name,
  4293. data,
  4294. db,
  4295. archive_data=archive_data,
  4296. good_url=good_url,
  4297. reject_url=reject_url,
  4298. confirm_url=confirm_url,
  4299. archive_id=archive_id,
  4300. run_id=run.id if run is not None else None,
  4301. )
  4302. return True
  4303. async def _printer_gone(db, printer_id: int) -> bool:
  4304. """Whether the printer was deleted. A column read: the session's loaded
  4305. Printer would otherwise answer for the database."""
  4306. from backend.app.models.printer import Printer
  4307. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4308. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4309. """Remove the archive just written if its printer was deleted meanwhile.
  4310. The delete route sweeps the printer's archives before it commits, so a row
  4311. committed after that sweep (the check before writing passed while the
  4312. delete was still uncommitted) is left for a printer that will never report
  4313. the print's end. A row the sweep reached is the route's: deleted with the
  4314. printer's archives, or detached (printer_id NULL) when the user kept them,
  4315. and then left as it is. Either way nothing is registered for it. Run after
  4316. the archive's commit, before anything is registered for it.
  4317. """
  4318. from backend.app.models.archive import PrintArchive
  4319. if not await _printer_gone(db, printer_id):
  4320. return False
  4321. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4322. if owner == printer_id:
  4323. logging.getLogger(__name__).info(
  4324. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4325. )
  4326. await ArchiveService(db).delete_archive(archive_id)
  4327. await forget_printer(printer_id)
  4328. return True
  4329. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4330. """After an IntegrityError on a print start's archive write: whether it was
  4331. the printer being deleted, forgotten then (the caller returns).
  4332. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4333. commit, so an archive written or adopted for it meanwhile (one that sets
  4334. printer_id) waits and the printer's foreign key then refuses it. That is
  4335. the printer being deleted, not an error; anything else is re-raised by the
  4336. caller.
  4337. """
  4338. await db.rollback()
  4339. if not await _printer_gone(db, printer_id):
  4340. return False
  4341. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4342. await forget_printer(printer_id)
  4343. return True
  4344. async def _forget_if_printer_gone(printer_id: int) -> None:
  4345. """At the end of a print start: the slow steps after the last check (smart
  4346. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4347. printer's delete and its forget_printer, and then wrote state back.
  4348. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4349. SQLite; PostgreSQL refuses it.)
  4350. Its own session: those steps can leave the handler's needing a rollback (a
  4351. write to the archive the delete removed). Never raises: it runs inside the
  4352. fallback branch's try, whose except reports the archive as failed.
  4353. """
  4354. try:
  4355. async with async_session() as db:
  4356. gone = await _printer_gone(db, printer_id)
  4357. if gone:
  4358. await forget_printer(printer_id)
  4359. except Exception:
  4360. logging.getLogger(__name__).warning(
  4361. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4362. )
  4363. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4364. """Tell the UI a plate check could not run. It does not block the print,
  4365. but an unchecked plate is not an empty one."""
  4366. try:
  4367. await ws_manager.broadcast(
  4368. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4369. )
  4370. except Exception as e:
  4371. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4372. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4373. """The ``_expected_prints`` keys a print start may be registered under."""
  4374. keys: list[tuple[int, str]] = []
  4375. if subtask_name:
  4376. keys.append((printer_id, subtask_name))
  4377. keys.append((printer_id, f"{subtask_name}.3mf"))
  4378. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4379. if filename:
  4380. fname = filename.split("/")[-1] if "/" in filename else filename
  4381. keys.append((printer_id, fname))
  4382. # Strip extensions to match
  4383. base = fname.replace(".gcode", "").replace(".3mf", "")
  4384. keys.append((printer_id, base))
  4385. keys.append((printer_id, f"{base}.3mf"))
  4386. return keys
  4387. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4388. """Whether this print start is one Bambuddy sent to the printer."""
  4389. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4390. return True
  4391. from backend.app.models.archive import PrintArchive
  4392. from backend.app.models.print_queue import PrintQueueItem
  4393. # The queue row the scheduler sets to printing before it sends -- but only
  4394. # when it was sent as this print: a row left printing by a run whose end
  4395. # was missed names another file.
  4396. dispatched_names = (
  4397. await db.execute(
  4398. select(PrintArchive.filename)
  4399. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4400. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4401. )
  4402. ).scalars()
  4403. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4404. return any(
  4405. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4406. for dispatched in dispatched_names
  4407. if dispatched
  4408. for seen in observed
  4409. )
  4410. async def on_print_start(printer_id: int, data: dict):
  4411. """Handle print start - archive the 3MF file immediately."""
  4412. logger = logging.getLogger(__name__)
  4413. # The print's start, before the 3MF download that the archive waits for
  4414. # (#3327): a minute of it would otherwise be missing from the print time.
  4415. detected_at = datetime.now(timezone.utc)
  4416. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4417. octoeverywhere_detection_service.reset_printer(printer_id)
  4418. try:
  4419. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4420. except Exception:
  4421. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4422. # Clear any stale user-stopped flag from previous print cycles
  4423. _user_stopped_printers.discard(printer_id)
  4424. _kill_switch_stopped.discard(printer_id)
  4425. # A new print starts its milestones from zero (#3211). The status path only
  4426. # resets on progress below 5 while not printing, which a printer that goes
  4427. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4428. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4429. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4430. _last_progress_milestone[printer_id] = 0
  4431. _kill_switch_notification_tasks.pop(printer_id, None)
  4432. # #1721: drop any leftover pre-captured finish frame from a prior print
  4433. # so a never-consumed cache entry can't bleed into the new print's photo.
  4434. _stage22_finish_frames.pop(printer_id, None)
  4435. # #1867: same for the in-print frame bank — a queued print must not reuse
  4436. # the previous job's banked frame.
  4437. _inprint_frame_bank.pop(printer_id, None)
  4438. _inprint_frame_bank_ts.pop(printer_id, None)
  4439. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4440. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4441. # print's flag instead of inheriting it.
  4442. print_dispatch_context.adopt(printer_id)
  4443. # Cancel any active bed cooldown waiter for this printer
  4444. if _bed_cool_waiters.pop(printer_id, None):
  4445. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4446. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4447. from backend.app.api.routes.printers import clear_cover_cache
  4448. clear_cover_cache(printer_id)
  4449. await ws_manager.send_print_start(printer_id, data)
  4450. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4451. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4452. # MQTT relay - publish print start
  4453. try:
  4454. printer_info = printer_manager.get_printer(printer_id)
  4455. if printer_info:
  4456. await mqtt_relay.on_print_start(
  4457. printer_id,
  4458. printer_info.name,
  4459. printer_info.serial_number,
  4460. data.get("filename", ""),
  4461. data.get("subtask_name", ""),
  4462. )
  4463. except Exception:
  4464. pass # Don't fail print start callback if MQTT fails
  4465. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4466. # and mapping, and the seeded tray-change log.
  4467. #
  4468. # Unconditional, for both inventory backends. This only *captures* — the
  4469. # writing is still split, with the internal tracker skipped at completion
  4470. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4471. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4472. # tray-change log, and that log is the only record of which spool fed
  4473. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4474. # it on one side only would leave Spoolman users with the mid-print
  4475. # restart bug this fixes for everyone else.
  4476. try:
  4477. async with async_session() as db:
  4478. from backend.app.api.routes.settings import get_setting
  4479. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4480. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4481. await usage_on_print_start(
  4482. printer_id,
  4483. data,
  4484. printer_manager,
  4485. db=db,
  4486. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4487. )
  4488. except Exception as e:
  4489. logger.warning("Usage tracker on_print_start failed: %s", e)
  4490. # Track if notification was sent (to avoid sending twice)
  4491. notification_sent = False
  4492. # Smart plug automation: turn on plug when print starts
  4493. try:
  4494. async with async_session() as db:
  4495. await smart_plug_manager.on_print_start(printer_id, db)
  4496. except Exception as e:
  4497. logger.warning("Smart plug on_print_start failed: %s", e)
  4498. async with async_session() as db:
  4499. from backend.app.models.printer import Printer
  4500. from backend.app.services.bambu_ftp import list_files_async
  4501. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4502. printer = result.scalar_one_or_none()
  4503. # Plate detection check - pause if objects detected on build plate
  4504. logger.info(
  4505. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4506. )
  4507. if printer and printer.plate_detection_enabled:
  4508. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4509. # Release the pooled DB connection before the plate-detection camera
  4510. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4511. # printer SELECT has run so far — nothing to persist — so this commit
  4512. # is a data-noop that ends the read transaction and returns the
  4513. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4514. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4515. # archive lookups below re-acquire a fresh connection on next execute.
  4516. await db.commit()
  4517. try:
  4518. from backend.app.services.plate_detection import check_plate_empty
  4519. # Build ROI tuple from printer settings if available
  4520. roi = None
  4521. if all(
  4522. [
  4523. printer.plate_detection_roi_x is not None,
  4524. printer.plate_detection_roi_y is not None,
  4525. printer.plate_detection_roi_w is not None,
  4526. printer.plate_detection_roi_h is not None,
  4527. ]
  4528. ):
  4529. roi = (
  4530. printer.plate_detection_roi_x,
  4531. printer.plate_detection_roi_y,
  4532. printer.plate_detection_roi_w,
  4533. printer.plate_detection_roi_h,
  4534. )
  4535. # The light is held, not switched, so a live view opened
  4536. # meanwhile keeps it when the check lets go (SP-C11). Every
  4537. # printer, whatever the camera light mode: detection needs it.
  4538. plate_photo_data = None
  4539. objects_detected = False
  4540. check_failure: str | None = None
  4541. async with camera_light(printer, any_mode=True, settle=2.5):
  4542. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4543. plate_result = await check_plate_empty(
  4544. printer_id=printer_id,
  4545. ip_address=printer.ip_address,
  4546. access_code=printer.access_code,
  4547. model=printer.model,
  4548. include_debug_image=False,
  4549. external_camera_url=printer.external_camera_url,
  4550. external_camera_type=printer.external_camera_type,
  4551. use_external=printer.external_camera_enabled,
  4552. roi=roi,
  4553. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4554. )
  4555. # No reference to compare against is a check that did not
  4556. # run either: say so rather than call the plate empty.
  4557. check_failure = getattr(plate_result, "failure_reason", None) or (
  4558. "not_calibrated" if plate_result.needs_calibration else None
  4559. )
  4560. objects_detected = not check_failure and not plate_result.is_empty
  4561. if objects_detected:
  4562. # Objects detected - pause the print!
  4563. logger.warning(
  4564. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4565. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4566. )
  4567. pause_client = printer_manager.get_client(printer_id)
  4568. if pause_client:
  4569. pause_client.pause_print()
  4570. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4571. # Snapshot while the light's still on — restoring it first
  4572. # would leave the notification with a dark photo.
  4573. try:
  4574. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4575. except Exception as snap_err:
  4576. logger.warning(
  4577. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4578. )
  4579. if objects_detected:
  4580. # Send notification about plate not empty
  4581. await ws_manager.broadcast(
  4582. {
  4583. "type": "plate_not_empty",
  4584. "printer_id": printer_id,
  4585. "printer_name": printer.name,
  4586. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4587. }
  4588. )
  4589. # Also send push notification
  4590. try:
  4591. await notification_service.on_plate_not_empty(
  4592. printer_id=printer_id,
  4593. printer_name=printer.name,
  4594. db=db,
  4595. difference_percent=plate_result.difference_percent,
  4596. image_data=plate_photo_data,
  4597. )
  4598. except Exception as notif_err:
  4599. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4600. elif check_failure:
  4601. logger.warning(
  4602. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4603. printer_id,
  4604. check_failure,
  4605. plate_result.message,
  4606. )
  4607. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4608. else:
  4609. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4610. except Exception as plate_err:
  4611. # Don't block print on plate detection errors
  4612. logger.warning(
  4613. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4614. printer_id,
  4615. plate_err,
  4616. )
  4617. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4618. if not printer:
  4619. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4620. if not notification_sent:
  4621. await _send_print_start_notification(printer_id, data, logger=logger)
  4622. return
  4623. # Skip the printer's own jobs — a calibration run is not a user's print.
  4624. # See is_internal_printer_job for what counts and why both fields are
  4625. # tested; the pressure-advance line reports as a subtask name with no
  4626. # /usr/ path, which the old prefix-only test here missed entirely.
  4627. #
  4628. # No notification either. The event describes the printer calibrating
  4629. # itself, so "Print started" is as wrong as the archive was, and the
  4630. # matching completion is suppressed in on_print_complete for the same
  4631. # reason. Checked before the auto-archive switches, whose "off" path
  4632. # still notifies.
  4633. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4634. # print Bambuddy dispatched is never one, whatever it is called.
  4635. # Dispatched = an expected print, or, after a restart that lost those,
  4636. # a queue job printing on the printer.
  4637. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4638. (data.get("filename") or "").startswith("/usr/")
  4639. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4640. ):
  4641. logger.info(
  4642. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4643. data.get("filename", ""),
  4644. data.get("subtask_name", ""),
  4645. )
  4646. return
  4647. # The global switch is the master: off, no printer archives prints
  4648. # started outside Bambuddy; on, each printer's own switch decides.
  4649. from backend.app.api.routes.settings import get_setting
  4650. _global_auto_archive = await get_setting(db, "auto_archive")
  4651. _global_archives = _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4652. archives_prints = printer.auto_archive and _global_archives
  4653. if not archives_prints:
  4654. # auto-archive disabled — check if there's an expected print (dispatched
  4655. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4656. # If so, fall through to the expected-print handling below so the archive
  4657. # is tracked in _active_prints and usage tracking works at completion.
  4658. _fn = data.get("filename", "")
  4659. _sn = data.get("subtask_name", "")
  4660. _check_keys: list[tuple[int, str]] = []
  4661. if _sn:
  4662. _check_keys += [
  4663. (printer_id, _sn),
  4664. (printer_id, f"{_sn}.3mf"),
  4665. (printer_id, f"{_sn}.gcode.3mf"),
  4666. ]
  4667. if _fn:
  4668. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4669. _check_keys.append((printer_id, _base_fn))
  4670. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4671. _check_keys += [
  4672. (printer_id, _no_archive_base),
  4673. (printer_id, f"{_no_archive_base}.3mf"),
  4674. ]
  4675. _has_expected = any(k in _expected_prints for k in _check_keys)
  4676. if not _has_expected:
  4677. # No expected print — truly external print (started from slicer/touchscreen).
  4678. # Say which switch it was: before 1.3.0 the global one was saved
  4679. # and never read, so an install upgraded with it off stopped
  4680. # archiving with nothing to point at it (#3477).
  4681. if not _global_archives:
  4682. logger.info(
  4683. "[CALLBACK] Skipping archive: the global 'Auto-archive prints' switch "
  4684. "(Settings > General > Archive Settings) is off, and Bambuddy did not start this print"
  4685. )
  4686. else:
  4687. logger.info(
  4688. "[CALLBACK] Skipping archive: auto-archive is off for printer %s, "
  4689. "and Bambuddy did not start this print",
  4690. printer_id,
  4691. )
  4692. if not notification_sent:
  4693. _no_archive_creator: int | None = None
  4694. for _key in _check_keys:
  4695. _expected_prints.pop(_key, None)
  4696. _expected_print_registered_at.pop(_key, None)
  4697. popped_creator = _expected_print_creators.pop(_key, None)
  4698. if _no_archive_creator is None:
  4699. _no_archive_creator = popped_creator
  4700. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4701. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4702. return
  4703. else:
  4704. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4705. # Get the filename and subtask_name
  4706. filename = data.get("filename", "")
  4707. subtask_name = data.get("subtask_name", "")
  4708. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4709. # present, it lets us match an archive across a backend restart (#972):
  4710. # same id → same print → resume the existing row instead of cancelling
  4711. # it and recreating from scratch (which loses started_at). Treat "0"
  4712. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4713. raw_mqtt = data.get("raw_data") or {}
  4714. subtask_id = raw_mqtt.get("subtask_id")
  4715. if subtask_id is not None:
  4716. subtask_id = str(subtask_id).strip()
  4717. if subtask_id in ("", "0"):
  4718. subtask_id = None
  4719. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4720. if not filename and not subtask_name:
  4721. # Send notification without archive data (no filename)
  4722. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4723. if not notification_sent:
  4724. await _send_print_start_notification(printer_id, data, logger=logger)
  4725. return
  4726. # Check if this is an expected print from reprint/scheduled
  4727. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4728. expected_archive_id = None
  4729. # Who queued it, taken with the entries it was registered beside: left
  4730. # behind once those are gone (the archive deleted mid-dispatch, or the
  4731. # start notification already sent), the expiry never saw it, and an
  4732. # unrelated later print of that name was attributed to that user (EP-2).
  4733. fallback_creator = None
  4734. for key in expected_keys:
  4735. expected_archive_id = _expected_prints.pop(key, None)
  4736. _expected_print_registered_at.pop(key, None)
  4737. if expected_archive_id:
  4738. # Clean up other possible keys for this print
  4739. for other_key in expected_keys:
  4740. _expected_prints.pop(other_key, None)
  4741. _expected_print_registered_at.pop(other_key, None)
  4742. creator = _expected_print_creators.pop(other_key, None)
  4743. if fallback_creator is None:
  4744. fallback_creator = creator
  4745. break
  4746. if expected_archive_id:
  4747. # This is a reprint/scheduled print - use existing archive, don't create new one
  4748. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4749. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4750. # Bambuddy's once the expected entry is consumed here.
  4751. _owned_print_archive_ids.add(expected_archive_id)
  4752. from backend.app.models.archive import PrintArchive
  4753. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4754. archive = result.scalar_one_or_none()
  4755. # Deleted after this handler loaded it (the plate check waits
  4756. # seconds) but before the route forgot the expected print: the
  4757. # archive the route kept or deleted is left as the route left it.
  4758. if archive and await _printer_gone(db, printer_id):
  4759. logger.info(
  4760. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4761. )
  4762. await forget_printer(printer_id)
  4763. return
  4764. if archive:
  4765. # As it was before this adoption: put back if the printer turns
  4766. # out to have been deleted while it was adopted (below).
  4767. before_adoption = {
  4768. attr.columns[0].name: getattr(archive, attr.key)
  4769. for attr in sa_inspect(PrintArchive).column_attrs
  4770. if attr.key != "id"
  4771. }
  4772. # Update archive status to printing
  4773. archive.status = "printing"
  4774. archive.started_at = datetime.now(timezone.utc)
  4775. # The previous run's outcome is not this one's: a reprint that
  4776. # completes must not keep showing why the last one failed.
  4777. archive.failure_reason = None
  4778. archive.completed_at = None
  4779. # The previous run's answer is still on this row and the
  4780. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4781. # so without a reset the second run inherits the first run's
  4782. # verdict: no prompt at all, and a green "good" badge on a run
  4783. # nobody ever judged.
  4784. if archive.confirm_requested:
  4785. archive.user_verdict = None
  4786. archive.user_verdict_source = None
  4787. archive.user_verdict_at = None
  4788. archive.confirm_token = None
  4789. archive.confirm_token_used_at = None
  4790. # Reprint of an archive reuses the source row. Without resetting
  4791. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4792. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4793. # extracts the *original* print's last frame, which then ships in
  4794. # the completion notification (#1707). Clear the path so the
  4795. # scanner runs fresh; also unlink the old video file so reprints
  4796. # don't accumulate orphans in the archive directory. Photos list
  4797. # is left alone — accumulating one finish photo per run is fine.
  4798. # The print-start baseline (#2704) is stale for the same reason:
  4799. # it describes the printer before the previous run. The capture
  4800. # below overwrites it, but clear it here too so an early failure
  4801. # can't leave the scan diffing against the wrong snapshot.
  4802. #
  4803. # Unlinked only when it is the same plate printing again. Every
  4804. # plate of a Send All shares this archive, and the video on it
  4805. # can be the only copy of another plate's run -- the printer's
  4806. # was deleted once it attached (#3275). That one is left in the
  4807. # archive directory, which goes with the archive. A video whose
  4808. # plate is not on record (attached by hand, or before the
  4809. # column existed) is kept too where the 3MF has other plates,
  4810. # or cannot be read: nothing tells it apart from another plate's,
  4811. # and keeping costs one file where deleting can cost the only
  4812. # copy. On an archive with exactly one plate it is that plate's.
  4813. archive.timelapse_baseline = None
  4814. stale_timelapse_relpath = archive.timelapse_path
  4815. stale_timelapse_plate_id = archive.timelapse_plate_id
  4816. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4817. if stale_timelapse_relpath:
  4818. archive.timelapse_path = None
  4819. archive.timelapse_plate_id = None
  4820. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4821. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4822. from backend.app.services.archive import plate_indexes_in_3mf
  4823. plates = await asyncio.to_thread(
  4824. plate_indexes_in_3mf,
  4825. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4826. )
  4827. stale_is_this_plates = len(plates) == 1
  4828. if stale_timelapse_relpath and not stale_is_this_plates:
  4829. logger.info(
  4830. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4831. stale_timelapse_relpath,
  4832. stale_timelapse_plate_id,
  4833. expected_archive_id,
  4834. starting_plate_id,
  4835. )
  4836. # The video is deleted once the adoption stands (below).
  4837. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4838. # Persist a restart-stable id so a later restart resumes this
  4839. # archive by subtask_id instead of name-matching + duplicating
  4840. # it (#1485). The printer often hasn't echoed subtask_id back
  4841. # this soon after dispatch, so fall back to the id Bambuddy
  4842. # minted when it sent the print command. Scoped to this
  4843. # expected-print branch on purpose: an expected match means
  4844. # Bambuddy dispatched this exact print in this process, so the
  4845. # client's last-dispatch id genuinely belongs to it — using it
  4846. # for an externally-started print could mis-tag the archive.
  4847. effective_subtask_id = subtask_id
  4848. if not effective_subtask_id:
  4849. _client = printer_manager.get_client(printer_id)
  4850. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4851. if _dispatched:
  4852. effective_subtask_id = str(_dispatched).strip() or None
  4853. # Update on first-set OR on reprint (the queue dispatcher mints
  4854. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4855. # the rewrite for reprints leaves the archive holding the FIRST
  4856. # run's id; if MQTT then reconnects mid-print, the reconciler
  4857. # (#1542) compares the stale stored id against the printer's
  4858. # live id, sees a mismatch, and synthesises a bogus PRINT
  4859. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4860. # in #1807. Inequality check preserves the noop-on-stable-push
  4861. # behaviour the earlier `not archive.subtask_id` guard provided.
  4862. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4863. archive.subtask_id = effective_subtask_id
  4864. # #1403 follow-up: VP-queue archives are created with
  4865. # printer_id=None at queue-add time (we don't know which
  4866. # printer will run the job yet). When the print actually
  4867. # starts on a specific printer the expected-archive lookup
  4868. # used to skip this assignment, leaving printer_id=None
  4869. # forever — which then disables the "Scan for timelapse"
  4870. # button in ArchivesPage (gated on !archive.printer_id).
  4871. if archive.printer_id != printer_id:
  4872. archive.printer_id = printer_id
  4873. adopting_id = archive.id # a rollback expires the object
  4874. try:
  4875. await db.commit()
  4876. except (IntegrityError, StaleDataError):
  4877. # The archive stays unchanged, or is gone: "delete archives"
  4878. # removed the row under the adoption, which then matched no
  4879. # row (StaleDataError) rather than being refused.
  4880. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4881. return
  4882. raise
  4883. # The printer can be deleted between the check above and this
  4884. # commit (the route's transaction lasts seconds), and the commit
  4885. # then adopted the archive anyway: status, verdict and timelapse
  4886. # changed, and the deleted printer's id written on a row the
  4887. # route had detached or never touched. Undo the adoption.
  4888. if await _printer_gone(db, printer_id):
  4889. logger.info(
  4890. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4891. printer_id,
  4892. archive.id,
  4893. )
  4894. # Everything as before this adoption. The printer it had
  4895. # then stays, unless it was the deleted one: the route
  4896. # detached that row (kept) or deleted it (no row matches).
  4897. previous_printer = before_adoption["printer_id"]
  4898. await db.execute(
  4899. update(PrintArchive)
  4900. .where(PrintArchive.id == archive.id)
  4901. .values(
  4902. {
  4903. **before_adoption,
  4904. "printer_id": None if previous_printer == printer_id else previous_printer,
  4905. }
  4906. )
  4907. )
  4908. await db.commit()
  4909. await forget_printer(printer_id)
  4910. return
  4911. await _drop_replaced_plate_videos(
  4912. db,
  4913. archive.id,
  4914. starting_plate_id,
  4915. stale_timelapse_relpath if delete_stale_video else None,
  4916. logger,
  4917. )
  4918. # Track as active print
  4919. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4920. await _open_run_for(archive.id, printer_id, subtask_id)
  4921. # Start timelapse session if external camera is enabled (#1353).
  4922. # Queue / VP-dispatched prints land here in the expected-archive
  4923. # branch and used to skip start_session entirely — frames were
  4924. # never captured and the post-print stitch silently returned None.
  4925. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4926. # Inject ams_mapping into usage tracker session — the session was created
  4927. # before expected-print promotion, so it may have ams_mapping=None when
  4928. # the MQTT request topic subscription failed (common on P1S/A1).
  4929. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4930. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4931. if _stored_map or _stored_plate_id is not None:
  4932. try:
  4933. from backend.app.services.usage_tracker import _active_sessions
  4934. _ut_session = _active_sessions.get(printer_id)
  4935. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4936. _ut_session.ams_mapping = _stored_map
  4937. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4938. # plate_id injection covers direct-Print of plate N of a multi-plate
  4939. # 3MF — queue prints already capture it via the on_print_start queue
  4940. # lookup, but direct-Print never goes through the queue (#1697).
  4941. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4942. _ut_session.plate_id = _stored_plate_id
  4943. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4944. except Exception:
  4945. pass
  4946. # Set up energy tracking (#941: persist start on archive row)
  4947. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4948. await ws_manager.send_archive_updated(
  4949. {
  4950. "id": archive.id,
  4951. "status": "printing",
  4952. }
  4953. )
  4954. # Send notification with archive data (reprint/scheduled)
  4955. if not notification_sent:
  4956. # Use archive's created_by_id; fall back to the creator registered via
  4957. # register_expected_print (handles library-file-based queue items where
  4958. # the freshly-created archive has no created_by_id yet), taken above.
  4959. archive_data = {
  4960. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4961. "created_by_id": archive.created_by_id or fallback_creator,
  4962. }
  4963. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4964. # Extract printable objects from the archived 3MF file
  4965. _load_objects_from_archive(archive, printer_id, logger)
  4966. if archive.file_path:
  4967. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4968. # Store Spoolman tracking data for per-filament usage reporting
  4969. try:
  4970. await _store_spoolman_print_data(
  4971. printer_id,
  4972. archive.id,
  4973. archive.file_path,
  4974. db,
  4975. printer_manager,
  4976. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4977. plate_id=_get_start_plate_id(printer_id, archive.id),
  4978. )
  4979. except Exception as e:
  4980. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4981. # Price the print from its spools now rather than only at completion (#3261)
  4982. _schedule_archive_cost_estimate(
  4983. printer_id,
  4984. archive.id,
  4985. printer_manager,
  4986. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4987. plate_id=_get_start_plate_id(printer_id, archive.id),
  4988. session_factory=async_session,
  4989. )
  4990. # Capture timelapse file baseline for snapshot-diff on completion
  4991. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4992. # hit this branch — without the baseline the completion-time scan
  4993. # falls into its "take baseline now" fallback, which snapshots
  4994. # AFTER the new MP4 already exists and never matches a diff
  4995. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4996. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4997. await _forget_if_printer_gone(printer_id)
  4998. return # Skip creating a new archive
  4999. # The archive was deleted after the job was queued.
  5000. if not archives_prints:
  5001. # Only the expected print brought a printer that does not
  5002. # archive this far; with it gone, nothing is archived.
  5003. return
  5004. # Otherwise archive the print anew rather than drop it, so it still
  5005. # gets its notification, usage tracking and history.
  5006. logger.warning(
  5007. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  5008. expected_archive_id,
  5009. printer_id,
  5010. )
  5011. # Check if there's already a "printing" archive for this printer/file
  5012. # This prevents duplicates when backend restarts during an active print
  5013. from backend.app.models.archive import PrintArchive
  5014. existing_archive: PrintArchive | None = None
  5015. resumed_by_run = False
  5016. # Best match: this job's run, open on the printer since the print
  5017. # started. The archive row is shared by every plate of it, and its
  5018. # printer, job id and status are the latest start's, which may be
  5019. # another printer's.
  5020. if subtask_id:
  5021. from backend.app.services.print_log import open_run_on_printer
  5022. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  5023. if run is not None and run.archive_id is not None:
  5024. existing_archive = await db.scalar(
  5025. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  5026. )
  5027. resumed_by_run = existing_archive is not None
  5028. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  5029. # across a backend restart for the same print, so this is the most
  5030. # reliable way to reattach. Only a row still printing: a cancelled one
  5031. # has been through completion (usage, history, notifications) already,
  5032. # and reopening it would count the print twice.
  5033. if subtask_id and existing_archive is None:
  5034. by_id = await db.execute(
  5035. select(PrintArchive)
  5036. .where(PrintArchive.printer_id == printer_id)
  5037. .where(PrintArchive.subtask_id == subtask_id)
  5038. .where(PrintArchive.status == "printing")
  5039. .order_by(PrintArchive.created_at.desc())
  5040. .limit(1)
  5041. )
  5042. existing_archive = by_id.scalar_one_or_none()
  5043. # Fallback match: name-based lookup. Kept as-is for prints whose
  5044. # subtask_id is missing ("0" / local / non-cloud prints).
  5045. if existing_archive is None:
  5046. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  5047. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  5048. # A print started from the printer's screen names its file in full,
  5049. # so the forms above double its extension. The file itself is the
  5050. # one exact match, and nothing looser is added (#3009).
  5051. if _subtask_is_the_file(subtask_name, filename):
  5052. archive_filenames.append(subtask_name)
  5053. existing = await db.execute(
  5054. select(PrintArchive)
  5055. .where(PrintArchive.printer_id == printer_id)
  5056. .where(PrintArchive.status == "printing")
  5057. .where(
  5058. or_(
  5059. PrintArchive.print_name == check_name,
  5060. PrintArchive.filename.in_(archive_filenames),
  5061. )
  5062. )
  5063. .order_by(PrintArchive.created_at.desc())
  5064. .limit(1)
  5065. )
  5066. existing_archive = existing.scalar_one_or_none()
  5067. if existing_archive:
  5068. # subtask_id match → always resume, regardless of age. Same print,
  5069. # just a backend restart.
  5070. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  5071. if subtask_match:
  5072. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  5073. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5074. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5075. _mark_owned_if_dispatched(existing_archive)
  5076. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5077. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  5078. if not notification_sent:
  5079. archive_data = {
  5080. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5081. "created_by_id": existing_archive.created_by_id,
  5082. }
  5083. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5084. _load_objects_from_archive(existing_archive, printer_id, logger)
  5085. if existing_archive.file_path:
  5086. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5087. return
  5088. # Name-match only (no subtask_id to anchor on): decide resume vs.
  5089. # stale from the printer's *current* progress, not wall-clock age.
  5090. # A genuinely long print used to trip a blind 4h cutoff and have its
  5091. # live archive cancelled + duplicated on every backend restart
  5092. # (#1485). If the printer reports real progress, this name-matched
  5093. # 'printing' archive IS that ongoing print — resume it whatever its
  5094. # age. Only treat it as a stale leftover when the printer clearly
  5095. # shows a different, freshly-started print: near-0% progress on an
  5096. # archive far too old to still be at 0%. Unknown progress (printer
  5097. # not connected) never cancels — resuming is the safe default.
  5098. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  5099. live_status = printer_manager.get_status(printer_id)
  5100. live_progress = getattr(live_status, "progress", None) if live_status else None
  5101. looks_stale = (
  5102. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  5103. )
  5104. # Two subtask ids are two prints, however young the archive: one
  5105. # whose completion was missed must not swallow the next print of
  5106. # the same file. Except Bambuddy's own reprint, which reuses the
  5107. # row and mints a fresh id (#1807): the id it last sent says so,
  5108. # and after a restart, which forgets it, this printer's queue job
  5109. # running the archive.
  5110. if (
  5111. not looks_stale
  5112. and subtask_id
  5113. and existing_archive.subtask_id
  5114. and existing_archive.subtask_id != subtask_id
  5115. ):
  5116. _client = printer_manager.get_client(printer_id)
  5117. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5118. if _dispatched:
  5119. looks_stale = _dispatched != subtask_id
  5120. else:
  5121. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5122. queue_run = await db.scalar(
  5123. select(_PQI.id)
  5124. .where(_PQI.archive_id == existing_archive.id)
  5125. .where(_PQI.printer_id == printer_id)
  5126. .where(_PQI.status == "printing")
  5127. .limit(1)
  5128. )
  5129. looks_stale = queue_run is None
  5130. if looks_stale:
  5131. logger.warning(
  5132. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5133. " — marking cancelled and creating new archive",
  5134. existing_archive.id,
  5135. archive_age,
  5136. live_progress,
  5137. existing_archive.subtask_id,
  5138. subtask_id,
  5139. )
  5140. existing_archive.status = "cancelled"
  5141. # Canonical key, not a sentence (issue #2974). "No status update
  5142. # received" is what both stale paths actually observed; which of
  5143. # the two it was is already carried by ``status`` -- cancelled
  5144. # here, the reconciled outcome at the reconnect site -- so one
  5145. # key loses no information and gives the Statistics breakdown a
  5146. # single bucket instead of two untranslatable prose strings.
  5147. existing_archive.failure_reason = "noStatusUpdate"
  5148. # And its run, as before runs were opened at the start: a new
  5149. # print starts on the printer, so whatever is open there ended
  5150. # unseen. Left open, the next reconnect would close it again.
  5151. from backend.app.services.print_log import discard_open_runs
  5152. discarded = await discard_open_runs(db, printer_id)
  5153. await db.commit()
  5154. await _announce_discarded_runs(discarded, printer_id)
  5155. # Its print keys go with it; the new archive registers its own.
  5156. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5157. del _active_prints[_key]
  5158. # Fall through to create new archive (don't return)
  5159. else:
  5160. logger.info(
  5161. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5162. )
  5163. # Track this as the active print
  5164. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5165. _mark_owned_if_dispatched(existing_archive)
  5166. # Attach subtask_id retroactively so future restarts can resume.
  5167. # Compare for inequality (not "is empty") to also pick up reprint
  5168. # dispatches that mint a fresh id — see #1807 for the bogus
  5169. # "Print Stopped" the strict-empty guard caused on reconnect.
  5170. if subtask_id and existing_archive.subtask_id != subtask_id:
  5171. existing_archive.subtask_id = subtask_id
  5172. await db.commit()
  5173. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5174. # Also set up energy tracking if not already tracked (#941: persisted column)
  5175. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5176. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5177. # Send notification with archive data (existing archive)
  5178. if not notification_sent:
  5179. archive_data = {
  5180. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5181. "created_by_id": existing_archive.created_by_id,
  5182. }
  5183. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5184. # Extract printable objects from the archived 3MF file
  5185. _load_objects_from_archive(existing_archive, printer_id, logger)
  5186. if existing_archive.file_path:
  5187. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5188. return
  5189. # Build list of possible 3MF filenames to try
  5190. possible_names = []
  5191. # Bambu printers typically store files as "Name.gcode.3mf"
  5192. # The subtask_name is usually the best source for the filename
  5193. if subtask_name:
  5194. if _subtask_is_the_file(subtask_name, filename):
  5195. # A print started from the printer's own screen reports the
  5196. # file's full name, extension included. That is the file, so
  5197. # no extension is appended to it (#3009).
  5198. possible_names.append(subtask_name)
  5199. else:
  5200. # Try common Bambu naming patterns
  5201. possible_names.append(f"{subtask_name}.gcode.3mf")
  5202. possible_names.append(f"{subtask_name}.3mf")
  5203. # Try original filename with .3mf extension
  5204. if filename:
  5205. # Extract just the filename part, not the full path
  5206. fname = filename.split("/")[-1] if "/" in filename else filename
  5207. if fname.endswith(".3mf"):
  5208. possible_names.append(fname)
  5209. elif fname.endswith(".gcode"):
  5210. base = fname.rsplit(".", 1)[0]
  5211. possible_names.append(f"{base}.gcode.3mf")
  5212. possible_names.append(f"{base}.3mf")
  5213. else:
  5214. possible_names.append(f"{fname}.gcode.3mf")
  5215. possible_names.append(f"{fname}.3mf")
  5216. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5217. space_variants = []
  5218. for name in possible_names:
  5219. if " " in name:
  5220. space_variants.append(name.replace(" ", "_"))
  5221. possible_names.extend(space_variants)
  5222. # Remove duplicates while preserving order
  5223. seen = set()
  5224. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5225. logger.info("Trying filenames: %s", possible_names)
  5226. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5227. # here means none of the expected-/existing-archive write branches ran
  5228. # (they all return earlier) — only SELECTs have executed on this path, so
  5229. # this commit persists nothing; it ends the read transaction so the
  5230. # connection returns to the pool during the download. That download tries
  5231. # up to five remote paths per candidate filename with retry/backoff and
  5232. # can run for minutes under FTP contention; holding the session across it
  5233. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5234. # work runs during the download — the new-archive writes below re-acquire
  5235. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5236. await db.commit()
  5237. # Try to find and download the 3MF file
  5238. temp_path = None
  5239. downloaded_filename = None
  5240. # Cache check: cover endpoint may have already pulled this 3MF during
  5241. # the print (frontend opens the card and shows the thumbnail) — reuse
  5242. # that file instead of re-downloading 36MB over the same FTP link that
  5243. # just served it (#972). The cache keys on a normalized filename so
  5244. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5245. for try_filename in possible_names:
  5246. if not try_filename.endswith(".3mf"):
  5247. continue
  5248. cached = get_cached_3mf(printer_id, try_filename)
  5249. if cached:
  5250. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5251. temp_path = cached
  5252. downloaded_filename = try_filename
  5253. break
  5254. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5255. # H2-series and P2S the answer is routinely no — the file stays on
  5256. # internal eMMC and port 990 only ever serves external storage — and
  5257. # then the whole sweep below (six filenames x five directories x four
  5258. # retries, then the directory walk) is ~110 connections that cannot
  5259. # succeed. Skip it and say why (#2780).
  5260. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5261. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5262. # running rather than because the file is somewhere unreachable. The
  5263. # distinction is the whole of #2957: one is permanent, the other clears
  5264. # in minutes with the file still sitting on the printer.
  5265. blocked_by_ftps_cooloff = False
  5266. # Set when a probe reached the printer and still came back without the
  5267. # file -- a timeout mid-transfer, a refused connection, anything that is
  5268. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5269. # caught by name below, so a file that genuinely is not on the card
  5270. # leaves this False and schedules nothing. Anything else means the
  5271. # transfer, not the file, is what failed, and that does not last (#3063).
  5272. ftp_transfer_failed = False
  5273. # The narrower case of the above: the directory walk *listed* a file
  5274. # for this print and could not fetch it, so the file is on the card
  5275. # under a name that matches. The only failure that rules out an
  5276. # earlier run's 3MF standing in for it (#3307).
  5277. walk_transfer_failed = False
  5278. # Paths the sweep reached and could not transfer -- a timeout, not a
  5279. # 550. The directory walk lists the same folders and would download
  5280. # the same file again: on a slow A1 that was a second 300 s on the
  5281. # printer's one FTPS slot, at print start, for a file the recovery
  5282. # retry fetches with a deadline twice as long (#3308).
  5283. sweep_failed_paths: set[str] = set()
  5284. # The print's name, for a fallback archive whose `subtask_name` the
  5285. # plate guard below had to disown. Display only, and deliberately kept
  5286. # apart from `subtask_name`: that variable is what every file lookup
  5287. # here is built from, and once a name has been shown to fetch another
  5288. # plate's 3MF it must not key `_active_prints` either, or the cover
  5289. # endpoint hands the same contradicted file to
  5290. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5291. display_name_after_plate_reject: str | None = None
  5292. # Get FTP retry settings
  5293. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5294. # ...but "the printer put it on eMMC" is where it went, not whether we
  5295. # can read it. An H2D with a card in mirrors the job to /cache and
  5296. # serves it happily, and skipping on the URL alone cost that reporter
  5297. # every archive for two days (#2856). So ask the printer instead of
  5298. # guessing: the dispatch named the exact file, which is one connection
  5299. # walking five paths rather than the sweep's ~110. Only when the probe
  5300. # comes back empty does the verdict's reason stand.
  5301. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5302. if ftps_handshake_blocked(printer.ip_address):
  5303. # Deliberately NOT recorded as a cool-off give-up. This branch
  5304. # only runs on an unreachable verdict, and that verdict is the
  5305. # honest, permanent reason the archive is empty — the probe was
  5306. # a long shot on top of it. Blaming the cool-off here would
  5307. # schedule a retry for a file sitting on internal eMMC, which is
  5308. # the sweep #2780 removed (#2957).
  5309. logger.debug(
  5310. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5311. storage.probe_filename,
  5312. printer_id,
  5313. )
  5314. else:
  5315. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5316. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5317. try:
  5318. probe_hit = await download_file_try_paths_async(
  5319. printer.ip_address,
  5320. printer.access_code,
  5321. ftp_probe_paths(storage.probe_filename),
  5322. probe_path,
  5323. socket_timeout=ftp_timeout,
  5324. printer_model=printer.model,
  5325. )
  5326. except Exception as e:
  5327. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5328. probe_hit = False
  5329. if probe_hit:
  5330. downloaded_filename = storage.probe_filename
  5331. temp_path = probe_path
  5332. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5333. # Naming the path, not just the file: a printer that keeps
  5334. # uploads around for weeks can serve a same-named copy of an
  5335. # earlier slice, and without the directory in the log that
  5336. # mismatch is invisible rather than merely rare (#1820).
  5337. logger.info(
  5338. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5339. downloaded_filename,
  5340. probe_hit,
  5341. printer_id,
  5342. storage.reason,
  5343. )
  5344. if not storage.reachable and not downloaded_filename:
  5345. # Same opening words whether or not a probe ran, because that is
  5346. # the phrase support asks people to grep for — only the tail says
  5347. # which of the two happened.
  5348. logger.info(
  5349. "Skipping the 3MF lookup for printer %s: %s — %s",
  5350. printer_id,
  5351. storage.reason,
  5352. "no copy of it on external storage either"
  5353. if storage.probe_filename
  5354. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5355. )
  5356. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5357. if not try_filename.endswith(".3mf"):
  5358. continue
  5359. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5360. # printers, so try it first — deferring it to last cost #972's reporter
  5361. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5362. # landing on the path that actually had the file.
  5363. remote_paths = [
  5364. f"/{try_filename}",
  5365. f"/cache/{try_filename}",
  5366. f"/model/{try_filename}",
  5367. f"/data/{try_filename}",
  5368. f"/data/Metadata/{try_filename}",
  5369. ]
  5370. temp_path = app_settings.archive_dir / "temp" / try_filename
  5371. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5372. for remote_path in remote_paths:
  5373. if ftps_handshake_blocked(printer.ip_address):
  5374. # The printer's FTPS service is not completing a TLS
  5375. # handshake, so it has no path we could reach — walking the
  5376. # remaining candidates only re-runs the same failure
  5377. # (#2780). Fall through to the no-3MF archive now.
  5378. #
  5379. # Remember *why*, though. This is the one give-up that is
  5380. # temporary: the cool-off clears in minutes and the file was
  5381. # on the printer the whole time. The fallback archive is
  5382. # stamped with it so a retry can be scheduled, and so the
  5383. # Archives banner stops blaming storage (#2957).
  5384. blocked_by_ftps_cooloff = True
  5385. logger.warning(
  5386. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5387. printer_id,
  5388. )
  5389. break
  5390. logger.debug("Trying FTP download: %s", remote_path)
  5391. try:
  5392. if ftp_retry_enabled:
  5393. downloaded = await with_ftp_retry(
  5394. download_file_async,
  5395. printer.ip_address,
  5396. printer.access_code,
  5397. remote_path,
  5398. temp_path,
  5399. timeout=ftp_timeout,
  5400. socket_timeout=ftp_timeout,
  5401. printer_model=printer.model,
  5402. max_retries=ftp_retry_count,
  5403. retry_delay=ftp_retry_delay,
  5404. operation_name=f"Download 3MF from {remote_path}",
  5405. cooloff_ip=printer.ip_address,
  5406. non_retry_exceptions=(FileNotOnPrinterError,),
  5407. )
  5408. else:
  5409. downloaded = await download_file_async(
  5410. printer.ip_address,
  5411. printer.access_code,
  5412. remote_path,
  5413. temp_path,
  5414. timeout=ftp_timeout,
  5415. socket_timeout=ftp_timeout,
  5416. printer_model=printer.model,
  5417. )
  5418. if downloaded:
  5419. downloaded_filename = try_filename
  5420. logger.info("Downloaded: %s", remote_path)
  5421. # Populate shared cache so the cover endpoint (if it
  5422. # runs next) doesn't refetch the same 36MB over FTP.
  5423. cache_3mf_download(printer_id, try_filename, temp_path)
  5424. break
  5425. # with_ftp_retry returns None once it has spent its budget,
  5426. # and download_file_async returns False on a timeout, so an
  5427. # exhausted transfer arrives here rather than as an
  5428. # exception (#3063).
  5429. ftp_transfer_failed = True
  5430. sweep_failed_paths.add(remote_path)
  5431. except FileNotOnPrinterError:
  5432. # 550 — file isn't at this path. Advance to next candidate
  5433. # without burning the retry budget.
  5434. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5435. except Exception as e:
  5436. ftp_transfer_failed = True
  5437. sweep_failed_paths.add(remote_path)
  5438. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5439. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5440. break
  5441. # If still not found, try listing directories to find matching file
  5442. # Different printer models use different directory structures. Skipped
  5443. # when the printer's FTPS handshake is failing — the directory walk is
  5444. # five more connections that cannot get further than the download did.
  5445. if (
  5446. not downloaded_filename
  5447. and storage.reachable
  5448. and (filename or subtask_name)
  5449. and not ftps_handshake_blocked(printer.ip_address)
  5450. ):
  5451. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5452. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5453. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5454. # Every folder is listed before one file is picked, so a file named
  5455. # for the print in a later folder wins over one that merely
  5456. # contains the name in an earlier folder.
  5457. listed_paths: list[str] = []
  5458. for search_dir in search_dirs:
  5459. try:
  5460. dir_files = await list_files_async(
  5461. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5462. )
  5463. except Exception as e:
  5464. logger.debug("Failed to list %s: %s", search_dir, e)
  5465. continue
  5466. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5467. if threemf_files:
  5468. logger.info(
  5469. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5470. )
  5471. listed_paths += [
  5472. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5473. ]
  5474. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5475. if remote_full_path in sweep_failed_paths:
  5476. # Listed for this print, and its transfer already failed:
  5477. # the same as a failed walk download, without spending a
  5478. # second deadline on it. Skipping it cannot hand the walk a
  5479. # look-alike: while a file of the print's own name is
  5480. # listed, files that merely contain the name are not.
  5481. logger.info(
  5482. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5483. remote_full_path,
  5484. )
  5485. walk_transfer_failed = True
  5486. continue
  5487. fname = posixpath.basename(remote_full_path)
  5488. logger.info("Found matching file: %s", remote_full_path)
  5489. temp_path = app_settings.archive_dir / "temp" / fname
  5490. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5491. try:
  5492. if ftp_retry_enabled:
  5493. downloaded = await with_ftp_retry(
  5494. download_file_async,
  5495. printer.ip_address,
  5496. printer.access_code,
  5497. remote_full_path,
  5498. temp_path,
  5499. timeout=ftp_timeout,
  5500. socket_timeout=ftp_timeout,
  5501. printer_model=printer.model,
  5502. max_retries=ftp_retry_count,
  5503. retry_delay=ftp_retry_delay,
  5504. operation_name=f"Download 3MF from {remote_full_path}",
  5505. cooloff_ip=printer.ip_address,
  5506. )
  5507. else:
  5508. downloaded = await download_file_async(
  5509. printer.ip_address,
  5510. printer.access_code,
  5511. remote_full_path,
  5512. temp_path,
  5513. timeout=ftp_timeout,
  5514. socket_timeout=ftp_timeout,
  5515. printer_model=printer.model,
  5516. )
  5517. except Exception as e:
  5518. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5519. continue
  5520. if downloaded:
  5521. downloaded_filename = fname
  5522. logger.info("Found and downloaded: %s", remote_full_path)
  5523. cache_3mf_download(printer_id, fname, temp_path)
  5524. break
  5525. # The listing named the file, so it is on the card;
  5526. # only the transfer failed (#3063).
  5527. ftp_transfer_failed = True
  5528. walk_transfer_failed = True
  5529. # A "Print again" on the printer's screen names no file Bambuddy can
  5530. # find: only its history copy under a generic name, and the 3MF's
  5531. # internal title (#3307). When an earlier run of the same job was
  5532. # archived, its 3MF is the one being printed again. Not when the
  5533. # directory walk listed a file for this print and only its transfer
  5534. # failed: that file is on the card, and the retry fetches it. A
  5535. # cool-off or a failed sweep path is no such evidence -- the retry
  5536. # tries the same names, which this print's file never had.
  5537. reused_3mf_from: int | None = None
  5538. if not downloaded_filename and not walk_transfer_failed:
  5539. reported_layers = raw_mqtt.get("total_layer_num")
  5540. earlier = await _archived_3mf_for_repeat(
  5541. db,
  5542. printer_id,
  5543. subtask_name,
  5544. filename,
  5545. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5546. )
  5547. if earlier is not None:
  5548. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5549. # Per printer: two printers reprinting the same job at once
  5550. # must not write one temp file (archive_print names the
  5551. # archive after original_filename, not this path).
  5552. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5553. try:
  5554. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5555. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5556. except OSError as e:
  5557. # A copy that fails leaves the print the fallback archive
  5558. # it would have had, not no archive at all.
  5559. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5560. else:
  5561. temp_path = reuse_path
  5562. downloaded_filename = reuse_name
  5563. reused_3mf_from = earlier.id
  5564. cache_3mf_download(printer_id, reuse_name, temp_path)
  5565. logger.info(
  5566. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5567. printer_id,
  5568. subtask_name,
  5569. filename,
  5570. earlier.id,
  5571. )
  5572. # Validate the downloaded 3MF actually matches the plate that's running
  5573. # (#1204): subtask_name lags across consecutive plates of the same model,
  5574. # so the first FTP candidate (built from subtask_name) can land on the
  5575. # previous plate's still-resident upload. Cross-check the slice_info
  5576. # plate index against the plate parsed from gcode_file (always fresh —
  5577. # it's the field whose change triggered this callback).
  5578. if downloaded_filename and temp_path:
  5579. expected_plate = parse_plate_id(filename)
  5580. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5581. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5582. logger.warning(
  5583. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5584. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5585. downloaded_filename,
  5586. actual_plate,
  5587. expected_plate,
  5588. subtask_name,
  5589. )
  5590. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5591. retry_succeeded = False
  5592. if corrected_subtask and corrected_subtask != subtask_name:
  5593. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5594. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5595. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5596. for remote_path in (
  5597. f"/{try_filename}",
  5598. f"/cache/{try_filename}",
  5599. f"/model/{try_filename}",
  5600. f"/data/{try_filename}",
  5601. f"/data/Metadata/{try_filename}",
  5602. ):
  5603. try:
  5604. if ftp_retry_enabled:
  5605. downloaded = await with_ftp_retry(
  5606. download_file_async,
  5607. printer.ip_address,
  5608. printer.access_code,
  5609. remote_path,
  5610. retry_temp_path,
  5611. timeout=ftp_timeout,
  5612. socket_timeout=ftp_timeout,
  5613. printer_model=printer.model,
  5614. max_retries=ftp_retry_count,
  5615. retry_delay=ftp_retry_delay,
  5616. operation_name=f"Re-download 3MF from {remote_path}",
  5617. cooloff_ip=printer.ip_address,
  5618. non_retry_exceptions=(FileNotOnPrinterError,),
  5619. )
  5620. else:
  5621. downloaded = await download_file_async(
  5622. printer.ip_address,
  5623. printer.access_code,
  5624. remote_path,
  5625. retry_temp_path,
  5626. timeout=ftp_timeout,
  5627. socket_timeout=ftp_timeout,
  5628. printer_model=printer.model,
  5629. )
  5630. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5631. logger.info(
  5632. "[CALLBACK] Re-download succeeded with corrected name %s "
  5633. "(plate %s) — replacing wrong file",
  5634. try_filename,
  5635. expected_plate,
  5636. )
  5637. try:
  5638. temp_path.unlink(missing_ok=True)
  5639. except OSError:
  5640. pass
  5641. temp_path = retry_temp_path
  5642. downloaded_filename = try_filename
  5643. subtask_name = corrected_subtask
  5644. cache_3mf_download(printer_id, try_filename, temp_path)
  5645. retry_succeeded = True
  5646. break
  5647. elif downloaded:
  5648. # Wrong plate again — discard and keep trying
  5649. try:
  5650. retry_temp_path.unlink(missing_ok=True)
  5651. except OSError:
  5652. pass
  5653. except FileNotOnPrinterError:
  5654. continue
  5655. except Exception as e:
  5656. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5657. if retry_succeeded:
  5658. break
  5659. # If the retry didn't find a matching file, drop the wrong 3MF
  5660. # so the no-3MF fallback below creates an archive whose name
  5661. # at least reflects the right plate.
  5662. if not retry_succeeded:
  5663. logger.warning(
  5664. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5665. expected_plate,
  5666. )
  5667. try:
  5668. temp_path.unlink(missing_ok=True)
  5669. except OSError:
  5670. pass
  5671. temp_path = None
  5672. downloaded_filename = None
  5673. # Whatever the sweep's transport did earlier, it is not why
  5674. # this archive ends up empty: a 3MF downloaded fine, it was
  5675. # just the wrong plate. Retrying would re-fetch that same
  5676. # contradicted file under the same stale names and hand it
  5677. # to _recover_fallback_archive, which checks that a
  5678. # candidate is a readable 3MF but not which plate it is --
  5679. # so the row would be filled in with another plate's
  5680. # filament and cost, the exact swap #2957 removed (#3063).
  5681. ftp_transfer_failed = False
  5682. # Disown the name for *lookups*: it has just been shown to
  5683. # fetch another plate's 3MF, and it keys `_active_prints`
  5684. # below, where the cover endpoint's own download of that
  5685. # same name would find this archive and fill it in with the
  5686. # file we are discarding here.
  5687. #
  5688. # Keep it for the *title*, which is a separate question.
  5689. # ``swap_plate_suffix`` returns None both for a name that
  5690. # carries no "- Plate N" / "_plate_N" suffix and for no
  5691. # name at all, and those are not the same situation: a name
  5692. # without a suffix holds no stale plate number to be wrong
  5693. # about. Blanking both uses at once dropped the project
  5694. # name too, and the row fell through to the gcode_file path
  5695. # titled "plate_1" though the real name was in hand.
  5696. # #1204's own premise is consecutive plates *of the same
  5697. # model*, so the project part is right either way (#3126).
  5698. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5699. subtask_name = corrected_subtask or ""
  5700. # Deleted while the 3MF was being fetched (that can take minutes): no
  5701. # archive, timelapse or tracking for a printer that will never report
  5702. # the print's end. forget_printer again: the download registered its
  5703. # 3MF cache entry after the delete cleared the id. (A delete committing
  5704. # while the archive is written is caught after its commit.)
  5705. if await _printer_gone(db, printer_id):
  5706. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5707. await forget_printer(printer_id)
  5708. return
  5709. if not downloaded_filename or not temp_path:
  5710. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5711. # Create a fallback archive without 3MF data so the print is still tracked
  5712. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5713. try:
  5714. from backend.app.models.archive import PrintArchive
  5715. # Why the card is empty. The two temporary causes outrank the
  5716. # storage verdict because they say the sweep never got a fair
  5717. # answer: a cool-off skipped it at the transport, and a failed
  5718. # transfer reached the printer but never finished. Either way
  5719. # the file is still on the card, so reporting where the printer
  5720. # files its jobs would describe a setting that is not the
  5721. # problem (#2957, #3063).
  5722. if blocked_by_ftps_cooloff:
  5723. no_3mf_reason = REASON_FTPS_COOLOFF
  5724. elif storage.reachable and ftp_transfer_failed:
  5725. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5726. else:
  5727. no_3mf_reason = storage.reason
  5728. # Derive print name from subtask_name or filename. The
  5729. # plate guard's disowned name comes second: it is a real name
  5730. # for a real print, and only the gcode_file path is left
  5731. # otherwise -- which titles the row "plate_1" (#3126).
  5732. print_name = subtask_name or display_name_after_plate_reject or filename
  5733. if print_name:
  5734. # Clean up the name (remove extensions, path parts)
  5735. print_name = print_name.split("/")[-1]
  5736. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5737. else:
  5738. print_name = "Unknown Print"
  5739. # Recover estimated print time from MQTT (best-effort for notifications)
  5740. fallback_print_time = None
  5741. mqtt_remaining = data.get("remaining_time")
  5742. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5743. fallback_print_time = int(mqtt_remaining)
  5744. if fallback_print_time is None:
  5745. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5746. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5747. fallback_print_time = int(mc_remaining * 60)
  5748. # Best-effort filament metadata from MQTT — see
  5749. # _extract_filament_data_from_mqtt. Without this the fallback
  5750. # archive's filament fields stayed NULL even though the AMS
  5751. # state at print start was sitting right there in `data`.
  5752. # The slicer's ams_mapping (when present) narrows the result
  5753. # to slots actually used by the print (#1533).
  5754. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5755. data, _get_start_ams_mapping(data, printer_id, None)
  5756. )
  5757. # Create minimal archive entry
  5758. fallback_archive = PrintArchive(
  5759. printer_id=printer_id,
  5760. filename=filename or f"{print_name}.3mf",
  5761. file_path="", # Empty - no 3MF file available
  5762. file_size=0,
  5763. print_name=print_name,
  5764. print_time_seconds=fallback_print_time,
  5765. status="printing",
  5766. started_at=detected_at,
  5767. subtask_id=subtask_id,
  5768. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5769. filament_type=mqtt_filament_meta.get("filament_type"),
  5770. filament_color=mqtt_filament_meta.get("filament_color"),
  5771. extra_data={
  5772. "no_3mf_available": True,
  5773. # Why the card is empty, when we know -- see above. The
  5774. # banner reads this to stop telling H2/P2 owners to
  5775. # switch on a setting that is already on and would not
  5776. # have helped (#2780).
  5777. "no_3mf_reason": no_3mf_reason,
  5778. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5779. "_print_data": data,
  5780. },
  5781. )
  5782. db.add(fallback_archive)
  5783. try:
  5784. await db.commit()
  5785. except IntegrityError:
  5786. # Not "Failed to create fallback archive" below, and no
  5787. # start notification for a printer that is gone.
  5788. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5789. return
  5790. raise
  5791. await db.refresh(fallback_archive)
  5792. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5793. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5794. return
  5795. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5796. # Track as active print
  5797. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5798. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5799. # Record starting energy if smart plug available (#941: persisted column)
  5800. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5801. # Send WebSocket notification
  5802. await ws_manager.send_archive_created(
  5803. {
  5804. "id": fallback_archive.id,
  5805. "printer_id": fallback_archive.printer_id,
  5806. "filename": fallback_archive.filename,
  5807. "print_name": fallback_archive.print_name,
  5808. "status": fallback_archive.status,
  5809. }
  5810. )
  5811. # MQTT relay - publish archive created
  5812. try:
  5813. await mqtt_relay.on_archive_created(
  5814. archive_id=fallback_archive.id,
  5815. print_name=fallback_archive.print_name,
  5816. printer_name=printer.name,
  5817. status=fallback_archive.status,
  5818. )
  5819. except Exception:
  5820. pass # Don't fail if MQTT fails
  5821. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5822. try:
  5823. await _store_spoolman_print_data(
  5824. printer_id,
  5825. fallback_archive.id,
  5826. fallback_archive.file_path,
  5827. db,
  5828. printer_manager,
  5829. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5830. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5831. )
  5832. except Exception as e:
  5833. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5834. # Both temporary give-ups are worth coming back for, and for
  5835. # the same reason: the file is on the printer and the last look
  5836. # failed at the transport rather than finding nothing. One waits
  5837. # out the handshake block (#2957), the other waits for the
  5838. # printer to stop being busy (#3063). Deliberately not scheduled
  5839. # for a storage verdict: a file on internal eMMC will not appear
  5840. # at any FTPS path however long we wait, and retrying it is
  5841. # exactly the sweep #2780 removed.
  5842. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5843. # `possible_names`, not the raw MQTT strings: it is the exact
  5844. # list this flow just tried, already stripped of any path
  5845. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5846. # some firmware) and deduped.
  5847. _schedule_fallback_3mf_retry(
  5848. printer_id=printer_id,
  5849. archive_id=fallback_archive.id,
  5850. filenames=list(possible_names),
  5851. reason=no_3mf_reason,
  5852. )
  5853. # Send notification without archive data (file not found)
  5854. if not notification_sent:
  5855. await _send_print_start_notification(printer_id, data, logger=logger)
  5856. # The same baseline the other two on_print_start branches take
  5857. # (#2704), and last for the same reason they are: it lists the
  5858. # printer's timelapse directory, so a slow card must not delay
  5859. # the _active_prints registration, the energy reading, the
  5860. # archive-created event or the start notification above it.
  5861. #
  5862. # This branch never took one, so every no-3MF archive reached
  5863. # completion with no baseline in memory and none on the row, and
  5864. # the completion scan fell into its "snapshot now" fallback --
  5865. # which runs after the printer has written the video, so the new
  5866. # file landed inside the baseline and no diff ever matched
  5867. # (#2957 follow-up).
  5868. #
  5869. # Skipped when the FTPS cool-off is what produced this fallback:
  5870. # the listing needs the same connection that just failed, so it
  5871. # could only record that the card was unreadable. The scan
  5872. # handles that case by refusing to choose between candidates.
  5873. if not blocked_by_ftps_cooloff:
  5874. await _capture_timelapse_baseline_at_start(
  5875. printer, printer_id, logger, archive_id=fallback_archive.id
  5876. )
  5877. await _forget_if_printer_gone(printer_id)
  5878. return
  5879. except Exception as e:
  5880. logger.error("Failed to create fallback archive: %s", e)
  5881. # Send notification without archive data (file not found)
  5882. if not notification_sent:
  5883. await _send_print_start_notification(printer_id, data, logger=logger)
  5884. return
  5885. try:
  5886. # Archive the file with status "printing"
  5887. service = ArchiveService(db)
  5888. try:
  5889. archive = await service.archive_print(
  5890. printer_id=printer_id,
  5891. source_file=temp_path,
  5892. print_data={
  5893. **data,
  5894. "status": "printing",
  5895. # Where the 3MF came from when the printer had none to
  5896. # give (#3307), for whoever reads this archive later.
  5897. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5898. },
  5899. subtask_id=subtask_id,
  5900. started_at=detected_at,
  5901. # The reused copy's temp name carries the printer id; a
  5902. # download's is the file's own name, as before.
  5903. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5904. )
  5905. except IntegrityError:
  5906. # archive_print removed the folder it had copied the 3MF into.
  5907. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5908. return
  5909. raise
  5910. if archive:
  5911. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5912. # Set on the row rather than passed to archive_print, which also
  5913. # serves the queue dispatcher — there the queue item decides.
  5914. # Guarded because this branch has no ``except``: an unhandled
  5915. # write error would take the _active_prints registration, the
  5916. # start notification, the energy reading and the timelapse
  5917. # baseline below it with it, and a missing prompt is by far the
  5918. # cheaper failure.
  5919. archive_id = archive.id
  5920. try:
  5921. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5922. archive.confirm_requested = True
  5923. await db.commit()
  5924. except Exception as e:
  5925. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5926. # The rollback expires every loaded object, and on an async
  5927. # session reading one afterwards raises instead of
  5928. # reloading, so the two this branch goes on to use are
  5929. # fetched again. The archive itself was committed by
  5930. # archive_print; only the flag is lost.
  5931. try:
  5932. await db.rollback()
  5933. archive = await db.get(PrintArchive, archive_id)
  5934. printer = await db.get(Printer, printer_id)
  5935. except Exception as reload_error:
  5936. logger.warning(
  5937. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5938. )
  5939. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5940. return
  5941. # Track this active print (use both original filename and downloaded filename)
  5942. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5943. await _open_run_for(archive_id, printer_id, subtask_id)
  5944. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5945. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5946. # Record starting energy from smart plug if available (#941: persisted column)
  5947. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5948. await ws_manager.send_archive_created(
  5949. {
  5950. "id": archive.id,
  5951. "printer_id": archive.printer_id,
  5952. "filename": archive.filename,
  5953. "print_name": archive.print_name,
  5954. "status": archive.status,
  5955. }
  5956. )
  5957. # MQTT relay - publish archive created
  5958. try:
  5959. await mqtt_relay.on_archive_created(
  5960. archive_id=archive.id,
  5961. print_name=archive.print_name,
  5962. printer_name=printer.name,
  5963. status=archive.status,
  5964. )
  5965. except Exception:
  5966. pass # Don't fail if MQTT fails
  5967. # Send notification with archive data (new archive created)
  5968. if not notification_sent:
  5969. archive_data = {
  5970. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5971. "created_by_id": archive.created_by_id,
  5972. }
  5973. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5974. # Extract printable objects for skip object functionality
  5975. try:
  5976. from backend.app.services.archive import extract_printable_objects_from_3mf
  5977. client = printer_manager.get_client(printer_id)
  5978. if client:
  5979. with open(temp_path, "rb") as f:
  5980. threemf_data = f.read()
  5981. # Extract with positions for UI overlay, scoped to the
  5982. # plate that is printing — an all-plates 3MF carries
  5983. # every plate's objects (#2522).
  5984. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5985. threemf_data,
  5986. plate_number=resolve_plate_id(client.state),
  5987. include_positions=True,
  5988. )
  5989. if printable_objects:
  5990. # Store objects in printer state
  5991. client.state.printable_objects = printable_objects
  5992. client.state.printable_objects_bbox_all = bbox_all
  5993. client.state.skipped_objects = [] # Reset skipped objects for new print
  5994. logger.info(
  5995. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5996. )
  5997. except Exception as e:
  5998. logger.debug("Failed to extract printable objects: %s", e)
  5999. # From the archived copy: the downloaded one may be removed
  6000. # below while the pauses are still being read.
  6001. if archive is not None and archive.file_path:
  6002. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  6003. # Store Spoolman tracking data for per-filament usage reporting
  6004. try:
  6005. await _store_spoolman_print_data(
  6006. printer_id,
  6007. archive.id,
  6008. archive.file_path,
  6009. db,
  6010. printer_manager,
  6011. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  6012. plate_id=_get_start_plate_id(printer_id, archive_id),
  6013. )
  6014. except Exception as e:
  6015. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  6016. # Price the print from its spools now rather than only at completion (#3261)
  6017. _schedule_archive_cost_estimate(
  6018. printer_id,
  6019. archive.id,
  6020. printer_manager,
  6021. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  6022. plate_id=_get_start_plate_id(printer_id, archive_id),
  6023. session_factory=async_session,
  6024. )
  6025. # Capture timelapse file baseline for snapshot-diff on completion
  6026. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  6027. await _forget_if_printer_gone(printer_id)
  6028. finally:
  6029. # Keep temp_path around until print completes so the cover endpoint
  6030. # can reuse it (#972). Cache eviction in on_print_complete deletes
  6031. # the file. If the cache entry was evicted early (file vanished),
  6032. # clean up any stragglers here to avoid leaking disk on retries.
  6033. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  6034. if temp_path and temp_path.exists() and cached_now != temp_path:
  6035. temp_path.unlink()
  6036. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  6037. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  6038. # A baseline that could not be read at print start is read again on this
  6039. # schedule while the print runs (#3412). The printer writes the video only once
  6040. # the print has ended, so a reading taken mid-print is as good as one taken at
  6041. # the start. The interval is shorter than the FTPS cool-offs (300 s), which are
  6042. # what usually makes the card unreadable, so the first reading after one ends
  6043. # is not long behind; while a cool-off runs a round costs nothing, as no
  6044. # connection is opened. The cap bounds a print that never reports an end.
  6045. #
  6046. # A round that could not read the card doubles the wait before the next, up to
  6047. # the ceiling, and after that many failed rounds in a row the re-read gives up
  6048. # and leaves the baseline unread for the completion scan to handle (#3474). Each
  6049. # connection to a hung file service can leave a session behind on the printer.
  6050. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  6051. _TIMELAPSE_BASELINE_REREAD_MAX_INTERVAL_SECONDS = 1800.0
  6052. _TIMELAPSE_BASELINE_REREAD_MAX_FAILED_ROUNDS = 5
  6053. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  6054. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  6055. # tests can shrink them without waiting out real delays.
  6056. #
  6057. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  6058. # looking. Across 247 support bundles the attempt that found the video was #1
  6059. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  6060. # decaying one, which is the signature of a budget that expires while files are
  6061. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  6062. # prints make big videos and the printer writes them after the print ends, so
  6063. # the poll now runs for minutes and costs one FTP LIST per round.
  6064. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  6065. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  6066. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  6067. def _timelapse_scan_max_attempts() -> int:
  6068. """Round cap for the poll, derived from the wall-clock budget.
  6069. The deadline alone is not a sufficient bound: it assumes each round really
  6070. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  6071. and an FTP list that fails immediately would otherwise spin against the
  6072. printer at full speed for the whole window. Whichever bound is reached
  6073. first ends the poll.
  6074. """
  6075. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  6076. # A zero interval makes the wall-clock budget meaningless; fall back to
  6077. # the round count the production interval would have given.
  6078. return 32
  6079. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  6080. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  6081. """The video names on *printer*'s card, and whether the card was read.
  6082. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  6083. than raising, so a card behind the FTPS handshake cool-off, or one whose
  6084. listing timed out, is indistinguishable from one holding no videos.
  6085. Everywhere that only wants to know "is there a video yet" the difference
  6086. does not matter -- both mean "not yet, retry".
  6087. It matters where an empty listing is recorded as a *baseline*. Recording
  6088. "the card held nothing" for a card that was never read means every video on
  6089. it counts as new, and the completion scan then attaches a stale video to
  6090. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  6091. card counts as read only when every directory walked answered, with a
  6092. listing or with "no such directory". One that failed may be the one
  6093. holding the videos.
  6094. One walk, one connection per directory. It used to list the card with
  6095. ``_list_timelapse_videos`` first and walk the same directories again when
  6096. that came back empty, which against a hung file service was eight dead
  6097. connections a round instead of one (#3474). A directory that fails does
  6098. not end the walk unless the failure put the printer in a cool-off: a later
  6099. one holding videos still answers the question.
  6100. """
  6101. from backend.app.services.bambu_ftp import ftps_background_blocked, list_files_result_async
  6102. ip_address = getattr(printer, "ip_address", None)
  6103. printer_id = getattr(printer, "id", None)
  6104. if not ip_address:
  6105. return set(), True
  6106. # No card in the slot: nothing to read, and nothing a video could land on.
  6107. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6108. return set(), True
  6109. read = True
  6110. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6111. if ftps_background_blocked(ip_address):
  6112. # Below any path: every remaining one would fail the same way.
  6113. return set(), False
  6114. listing = await list_files_result_async(
  6115. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6116. )
  6117. if not (listing.available or listing.missing):
  6118. read = False
  6119. continue
  6120. videos = [
  6121. f
  6122. for f in listing.files
  6123. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6124. ]
  6125. if videos:
  6126. return {f.get("name", "") for f in videos}, True
  6127. return set(), read
  6128. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6129. """List video files from printer's timelapse directory.
  6130. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6131. Returns (video_files, found_path) where video_files is a list of file dicts
  6132. and found_path is the directory where they were found, or ([], None).
  6133. An empty return does not distinguish "no videos" from "could not read the
  6134. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6135. callers use instead.
  6136. """
  6137. from backend.app.services.bambu_ftp import ftps_background_blocked, list_files_async
  6138. logger = logging.getLogger(__name__)
  6139. # No card in the slot means no /timelapse to walk — four connections that
  6140. # can only fail, on a path whose failures are swallowed and so would go on
  6141. # costing time silently forever (#2780).
  6142. #
  6143. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6144. # inside the loop's own try/except, so a caller that passed something
  6145. # unexpected used to get an empty listing rather than an exception. Keep
  6146. # that, instead of making this gate the first thing that can raise here.
  6147. printer_id = getattr(printer, "id", None)
  6148. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6149. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6150. return [], None
  6151. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6152. if ftps_background_blocked(getattr(printer, "ip_address", None) or ""):
  6153. # The printer's file service is refusing or hung: every remaining
  6154. # path is another connection it may keep a session for (#3474).
  6155. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: its file service is cooling off", printer_id)
  6156. return [], None
  6157. try:
  6158. found_files = await list_files_async(
  6159. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6160. )
  6161. if found_files:
  6162. video_files = [
  6163. f
  6164. for f in found_files
  6165. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6166. ]
  6167. if video_files:
  6168. return video_files, timelapse_path
  6169. except Exception as e:
  6170. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6171. continue
  6172. return [], None
  6173. async def _capture_timelapse_baseline_at_start(
  6174. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6175. ) -> None:
  6176. """Snapshot the printer's timelapse directory at print start so the
  6177. completion-time scan can pick the new file by set-difference.
  6178. Must be called from every on_print_start path that proceeds to a real
  6179. print — both the new-archive branch and the expected-archive branch (which
  6180. queue / VP-dispatched prints take). Without a baseline,
  6181. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6182. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6183. so the new file ends up in the "baseline" set and no diff ever matches.
  6184. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6185. unreliable — the snapshot-diff approach sidesteps that entirely.
  6186. When ``archive_id`` is known the baseline is also written to the archive
  6187. row, so it survives a restart and the manual "Scan for Timelapse" button
  6188. can run the same diff instead of falling back to clock-based matching
  6189. (#2704). Only baselines taken at print start are persisted — one taken at
  6190. completion already contains the new video and would poison a later scan.
  6191. """
  6192. names: set[str] | None = None
  6193. unread = False
  6194. _timelapse_baselines_unread.discard(printer_id)
  6195. try:
  6196. names, read = await _read_timelapse_baseline(printer)
  6197. unread = not read
  6198. _timelapse_baselines[printer_id] = names
  6199. if unread:
  6200. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6201. # off a card we could not read is not evidence, but it is still the
  6202. # right *default*: Bambuddy deletes each video from the printer once
  6203. # it is attached, so the usual card holds exactly one video at
  6204. # completion and an empty baseline resolves it. Persisting NULL
  6205. # instead would send completion to take its own snapshot, by which
  6206. # point this print's video is on the card and would be swallowed by
  6207. # it. The mark keeps the scan from choosing between several videos
  6208. # (#3412), and the card is read again while the print runs.
  6209. _timelapse_baselines_unread.add(printer_id)
  6210. logger.warning(
  6211. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6212. "treating it as empty for now and reading it again during the print",
  6213. printer_id,
  6214. )
  6215. logger.info(
  6216. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6217. len(names),
  6218. printer_id,
  6219. )
  6220. except Exception as e:
  6221. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6222. run_started_at: datetime | None = None
  6223. run_id: int | None = None
  6224. if archive_id is not None:
  6225. try:
  6226. async with async_session() as db:
  6227. from backend.app.models.archive import PrintArchive
  6228. from backend.app.services.print_log import open_run_on_printer
  6229. archive = await db.get(PrintArchive, archive_id)
  6230. if archive is not None:
  6231. # Written even when the listing failed, and then as NULL. A
  6232. # reprint reuses the archive row, so leaving the previous
  6233. # run's baseline in place would have the scan diff this print
  6234. # against the state of the printer before the *last* one —
  6235. # and a stale baseline reads as authoritative, where NULL
  6236. # correctly falls back to a fresh snapshot.
  6237. baseline = sorted(names) if names is not None else None
  6238. archive.timelapse_baseline = baseline
  6239. archive.timelapse_baseline_unread = unread
  6240. run_started_at = archive.started_at
  6241. # And on the run this print opened, whose scan reads it:
  6242. # the archive's is its latest start's, which another plate
  6243. # of it on another printer can take over.
  6244. run = await open_run_on_printer(db, printer_id)
  6245. if run is not None and run.archive_id == archive_id:
  6246. run.timelapse_baseline = baseline
  6247. run.timelapse_baseline_unread = unread
  6248. run_id = run.id
  6249. await db.commit()
  6250. except Exception as e:
  6251. # In-memory baseline still covers the normal completion path.
  6252. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6253. if unread and names is not None:
  6254. spawn_background_task(
  6255. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6256. name=f"reread-timelapse-baseline-{printer_id}",
  6257. )
  6258. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6259. # levelling) counts as much as the print itself.
  6260. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6261. def _schedule_timelapse_scan(
  6262. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6263. ) -> None:
  6264. """Start the completion scan with the print-start baseline: the names, and
  6265. whether they were taken off a card that could not be read. Taking them
  6266. ends any re-read still running for it. ``run_id`` is the print that
  6267. ended, whose video it looks for."""
  6268. unread = printer_id in _timelapse_baselines_unread
  6269. _timelapse_baselines_unread.discard(printer_id)
  6270. baseline = _timelapse_baselines.pop(printer_id, None)
  6271. from backend.app.services import archive_work
  6272. # Held while it looks: it finds its print by the archive's id, which a
  6273. # merge would move away (archive redesign P2).
  6274. spawn_background_task(
  6275. archive_work.held_while(
  6276. archive_id,
  6277. _scan_for_timelapse_with_retries(
  6278. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6279. ),
  6280. ),
  6281. name=f"scan-timelapse-{archive_id}",
  6282. )
  6283. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6284. """Whether to read an unread baseline again now: True to read, None to
  6285. skip this round, False once it is over -- the print it was taken for is
  6286. no longer the one on the printer, has stopped printing, or the baseline
  6287. has been read.
  6288. ``names`` is the very set object recorded at print start: completion pops
  6289. it and the next print records a new one, so identity marks the run. A
  6290. printer that is momentarily disconnected says nothing about its print, so
  6291. that only skips the round.
  6292. So does a print that is not recording a timelapse: completion only looks
  6293. for a video when one was recorded, so reading the card for it is a
  6294. connection for nothing (#3474). Skipped rather than ended, as the flag can
  6295. arrive after the print has started.
  6296. """
  6297. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6298. return False
  6299. state = printer_manager.get_status(printer_id)
  6300. if state is None or not state.connected:
  6301. return None
  6302. if state.state not in _BASELINE_REREAD_STATES:
  6303. return False
  6304. return True if state.timelapse else None
  6305. async def _reread_unread_timelapse_baseline(
  6306. printer_id: int,
  6307. names: set[str],
  6308. archive_id: int | None,
  6309. run_started_at: datetime | None,
  6310. run_id: int | None = None,
  6311. ) -> None:
  6312. """Read again a print-start baseline the card could not give (#3412).
  6313. The printer writes the video only once the print has ended, so the card
  6314. read at any point during the print holds exactly what it held at the
  6315. start. Each round stops once the print is no longer the one the baseline
  6316. was taken for or has stopped printing, and checks that again after the
  6317. listing returns, before anything is recorded.
  6318. A round that cannot read the card doubles the wait before the next one,
  6319. and enough of them in a row end the re-read (#3474): see
  6320. ``_TIMELAPSE_BASELINE_REREAD_MAX_FAILED_ROUNDS``.
  6321. """
  6322. from backend.app.models.archive import PrintArchive
  6323. from backend.app.models.printer import Printer
  6324. from backend.app.services.print_log import run_of
  6325. logger = logging.getLogger(__name__)
  6326. interval = _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS
  6327. failed_rounds = 0
  6328. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6329. await asyncio.sleep(interval)
  6330. now = _unread_baseline_round(printer_id, names)
  6331. if now is False:
  6332. return
  6333. if now is None:
  6334. continue
  6335. try:
  6336. async with async_session() as db:
  6337. printer = await db.get(Printer, printer_id)
  6338. if printer is None:
  6339. return
  6340. fresh, read = await _read_timelapse_baseline(printer)
  6341. except Exception as e:
  6342. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6343. fresh, read = set(), False
  6344. if not read:
  6345. failed_rounds += 1
  6346. if failed_rounds >= _TIMELAPSE_BASELINE_REREAD_MAX_FAILED_ROUNDS:
  6347. logger.warning(
  6348. "[TIMELAPSE] Card of printer %s still unreadable after %s tries; no longer reading "
  6349. "the baseline for this print, it stays unread",
  6350. printer_id,
  6351. failed_rounds,
  6352. )
  6353. return
  6354. interval = min(interval * 2, _TIMELAPSE_BASELINE_REREAD_MAX_INTERVAL_SECONDS)
  6355. continue
  6356. now = _unread_baseline_round(printer_id, names)
  6357. if now is False:
  6358. return
  6359. if now is None:
  6360. # The printer dropped off while the listing was out, so nothing
  6361. # says it did not end meanwhile: keep the reading for a round that
  6362. # can vouch for it.
  6363. continue
  6364. names.update(fresh)
  6365. _timelapse_baselines_unread.discard(printer_id)
  6366. logger.info(
  6367. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6368. printer_id,
  6369. len(fresh),
  6370. )
  6371. if archive_id is None:
  6372. return
  6373. try:
  6374. async with async_session() as db:
  6375. archive = await db.get(PrintArchive, archive_id)
  6376. # Only the run it was taken for: by now the row can belong to a
  6377. # reprint, whose baseline is its own.
  6378. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6379. archive.timelapse_baseline = sorted(names)
  6380. archive.timelapse_baseline_unread = False
  6381. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6382. if run is not None and run.timelapse_baseline_unread:
  6383. run.timelapse_baseline = sorted(names)
  6384. run.timelapse_baseline_unread = False
  6385. await db.commit()
  6386. except Exception as e:
  6387. # The in-memory baseline is read now, which covers completion
  6388. # unless Bambuddy restarts first.
  6389. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6390. return
  6391. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6392. """Whether the print a timelapse is for still has none: its run, by id,
  6393. exists without a video and no later print took over (``superseded``).
  6394. Without a run, the archive is still on that print's start (a newer run's
  6395. video is its own) and has none."""
  6396. from backend.app.services.print_log import run_of, superseded
  6397. if run_id is not None:
  6398. run = await run_of(db, archive.id, run_id)
  6399. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6400. return archive.timelapse_path is None and archive.started_at == run_started_at
  6401. async def _scan_for_timelapse_with_retries(
  6402. archive_id: int,
  6403. baseline_names: set[str] | None = None,
  6404. *,
  6405. plate_id: int | None = None,
  6406. baseline_unread: bool = False,
  6407. run_id: int | None = None,
  6408. ):
  6409. """Poll the printer for this print's timelapse and attach it.
  6410. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6411. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6412. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6413. (#2704). Comparing the current listing against the set of filenames that
  6414. existed when the print started needs no clock at all, because the printer
  6415. writes the video only once the print has ended.
  6416. Baseline precedence: the caller's in-memory set, then the one persisted on
  6417. the archive at print start, then a snapshot taken now. The last of those is
  6418. a poor substitute — by completion the new video may already be on the card,
  6419. in which case it lands in the "baseline" and no diff can ever match — but it
  6420. is all that is available for a print that began before Bambuddy started.
  6421. On success the video is deleted from the printer, which keeps ``/timelapse``
  6422. down to the unclaimed files and makes the next diff unambiguous.
  6423. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6424. could not be read; a stored one carries the same mark on the archive.
  6425. ``run_id`` is the print that ended (archive redesign): the video is that
  6426. run's, the stored baseline is the run's own, and the poll ends once the
  6427. run has a video or is gone. Without it (no run was written), the run is
  6428. whichever the archive is on when the scan starts.
  6429. """
  6430. from backend.app.services.print_log import run_of
  6431. logger = logging.getLogger(__name__)
  6432. # Cleared when the baseline was taken off a card we could not read, so the
  6433. # attach step refuses to choose between several candidates (#2957, #3412).
  6434. baseline_trusted = True
  6435. # --- Phase 1: establish the baseline -------------------------------------
  6436. try:
  6437. async with async_session() as db:
  6438. from backend.app.models.printer import Printer
  6439. service = ArchiveService(db)
  6440. archive = await service.get_archive(archive_id)
  6441. if not archive:
  6442. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6443. return
  6444. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6445. if run_id is not None and run is None:
  6446. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6447. return
  6448. if run.timelapse_path if run is not None else archive.timelapse_path:
  6449. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6450. return
  6451. # The printer the print ran on: plates of one archive can print on
  6452. # two printers, and the archive's is the one that started last.
  6453. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6454. if not scan_printer_id:
  6455. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6456. return
  6457. # The run this scan is for. The archive row passes to a newer run
  6458. # when it prints again (the next plate, a reprint), and that run's
  6459. # video is its own.
  6460. run_started_at = run.started_at if run is not None else archive.started_at
  6461. # The baseline stored for it: the run's own, else the archive's
  6462. # while that is still this run's start's.
  6463. stored_baseline, stored_unread = None, False
  6464. if run is not None and run.timelapse_baseline is not None:
  6465. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6466. elif archive.started_at == run_started_at:
  6467. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6468. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6469. # The card was read at print start, and the in-memory copy is
  6470. # one Bambuddy took after a restart off a card it could not
  6471. # read: the stored one is this run's and is evidence.
  6472. baseline_names = set(stored_baseline)
  6473. logger.info(
  6474. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6475. len(baseline_names),
  6476. archive_id,
  6477. )
  6478. elif baseline_names is not None:
  6479. baseline_trusted = not baseline_unread
  6480. logger.info(
  6481. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6482. len(baseline_names),
  6483. archive_id,
  6484. )
  6485. elif stored_baseline is not None:
  6486. # Persisted at print start — survives a restart mid-print.
  6487. baseline_names = set(stored_baseline)
  6488. baseline_trusted = not stored_unread
  6489. logger.info(
  6490. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6491. len(baseline_names),
  6492. archive_id,
  6493. )
  6494. else:
  6495. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6496. printer = result.scalar_one_or_none()
  6497. if not printer:
  6498. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6499. return
  6500. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6501. if not baseline_trusted:
  6502. # The card is unreadable at the one moment a baseline has to
  6503. # be taken, so the empty listing means "we never looked",
  6504. # not "these are all new". Carry on with it anyway — the
  6505. # usual card holds exactly one video, which resolves
  6506. # correctly — but stop the poll from *choosing* between
  6507. # several, which is how a stale video got attached to this
  6508. # print and then deleted off the printer (#2957 follow-up).
  6509. logger.warning(
  6510. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6511. "read. A single new video still resolves; several will not be guessed between — "
  6512. "use Scan for Timelapse to pick one by hand",
  6513. archive_id,
  6514. scan_printer_id,
  6515. )
  6516. logger.info(
  6517. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6518. len(baseline_names),
  6519. archive_id,
  6520. )
  6521. except Exception as e:
  6522. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6523. return
  6524. # --- Phase 2: poll for a file that was not there when the print began -----
  6525. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6526. max_attempts = _timelapse_scan_max_attempts()
  6527. seen_names: set[str] = set()
  6528. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6529. attempt = 0
  6530. while True:
  6531. await asyncio.sleep(delay)
  6532. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6533. attempt += 1
  6534. try:
  6535. from backend.app.models.printer import Printer
  6536. # Read phase: fetch archive + printer in a short session and release
  6537. # the pooled connection BEFORE the FTP list/download below. Holding it
  6538. # across the FTP round-trips left one connection idle-in-transaction per
  6539. # in-flight scan (issue #2572).
  6540. async with async_session() as db:
  6541. from backend.app.services.print_log import claimed_timelapse_stems
  6542. service = ArchiveService(db)
  6543. archive = await service.get_archive(archive_id)
  6544. if not archive:
  6545. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6546. return
  6547. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6548. logger.info(
  6549. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6550. archive_id,
  6551. )
  6552. return
  6553. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6554. printer = result.scalar_one_or_none()
  6555. if not printer:
  6556. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6557. return
  6558. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6559. # I/O phase (no DB connection held): FTP list + download.
  6560. video_files, found_path = await _list_timelapse_videos(printer)
  6561. # The poll can run for dozens of rounds, so only narrate a round
  6562. # that saw something change. Repeating the whole listing every 30 s
  6563. # would bury the one interesting line in the support bundle.
  6564. names_now = {f.get("name", "") for f in video_files}
  6565. changed = attempt == 1 or names_now != seen_names
  6566. seen_names = names_now
  6567. speak = logger.info if changed else logger.debug
  6568. if video_files:
  6569. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6570. if changed:
  6571. for f in video_files[:5]:
  6572. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6573. attached = await _attach_first_unclaimed_timelapse(
  6574. archive_id,
  6575. printer,
  6576. video_files,
  6577. baseline_names,
  6578. claimed,
  6579. attempt,
  6580. logger,
  6581. quiet=not changed,
  6582. require_unambiguous=not baseline_trusted,
  6583. plate_id=plate_id,
  6584. run_started_at=run_started_at,
  6585. run_id=run_id,
  6586. )
  6587. if attached:
  6588. return
  6589. else:
  6590. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6591. except Exception as e:
  6592. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6593. if attempt >= max_attempts or time.monotonic() >= deadline:
  6594. break
  6595. # No name-match fallback: it compared the print name against the filename,
  6596. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6597. # bundles it fired 159 times and matched zero times, so all it added was a
  6598. # misleading log line before giving up.
  6599. logger.warning(
  6600. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6601. archive_id,
  6602. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6603. )
  6604. async def _attach_layer_timelapse(
  6605. archive_id: int,
  6606. timelapse_path: Path,
  6607. plate_id: int | None,
  6608. run_started_at: datetime | None,
  6609. run_id: int | None = None,
  6610. ) -> None:
  6611. """Attach the external camera's stitched timelapse to the archive.
  6612. The camera's video is the one the user set up in Bambuddy, so it wins
  6613. over the printer's own when both are on: it replaces the printer's video
  6614. (usually there first; stitching takes minutes) and that file is deleted,
  6615. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6616. the run the frames were taken for: when the archive is printing again by
  6617. the time the stitch is done, the video is not the new run's and is
  6618. dropped. The stitched file is a temporary either way.
  6619. ``run_id`` is the print that ended (archive redesign): the video is that
  6620. run's and replaces that run's printer video; the poll by start above is
  6621. for a print without a run.
  6622. """
  6623. from backend.app.services.print_log import run_of, superseded
  6624. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6625. logger = logging.getLogger(__name__)
  6626. try:
  6627. async with async_session() as db:
  6628. service = ArchiveService(db)
  6629. archive = await service.get_archive(archive_id)
  6630. if archive is None:
  6631. return
  6632. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6633. if run_id is not None and run is None:
  6634. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6635. return
  6636. if run is not None and await superseded(db, run):
  6637. logger.info(
  6638. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6639. run_id,
  6640. archive_id,
  6641. )
  6642. return
  6643. if run is None and archive.started_at != run_started_at:
  6644. logger.info(
  6645. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6646. )
  6647. return
  6648. holder = run if run is not None else archive
  6649. replaced = holder.timelapse_path
  6650. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6651. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6652. if not await service.attach_timelapse(
  6653. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6654. ):
  6655. return
  6656. attached = holder.timelapse_path
  6657. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6658. if replaced and replaced != attached:
  6659. try:
  6660. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6661. except PathTraversalError:
  6662. return
  6663. await asyncio.to_thread(old.unlink, missing_ok=True)
  6664. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6665. finally:
  6666. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6667. # ``run_started_at`` not given: attach whichever run the archive is on.
  6668. _ANY_RUN = object()
  6669. async def _attach_first_unclaimed_timelapse(
  6670. archive_id: int,
  6671. printer,
  6672. video_files: list[dict],
  6673. baseline_names: set[str],
  6674. claimed: set[str],
  6675. attempt: int,
  6676. logger: logging.Logger,
  6677. *,
  6678. quiet: bool = False,
  6679. require_unambiguous: bool = False,
  6680. plate_id: int | None = None,
  6681. run_started_at: datetime | None | object = _ANY_RUN,
  6682. run_id: int | None = None,
  6683. ) -> bool:
  6684. """Download and attach the one video that belongs to this print.
  6685. A candidate is any file absent from the print-start baseline. More than one
  6686. can qualify when a previous print's video landed late, after this print's
  6687. baseline was taken — those are filtered out by name, because they are
  6688. already attached to another archive. Sorting the candidates instead would
  6689. mean sorting on mtime or on the filename timestamp, both of which come from
  6690. the printer's unsynced clock.
  6691. Returns True once a video is attached. The printer's copy is deleted only
  6692. after the attach succeeds on bytes whose length matched the listing.
  6693. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6694. already seen this exact listing — the poll runs for many rounds and only the
  6695. rounds where something changed are worth an INFO line.
  6696. """
  6697. from backend.app.services.bambu_ftp import (
  6698. DownloadDeadlineExceeded,
  6699. delete_archived_timelapse,
  6700. download_file_bytes_async,
  6701. remote_file_settled,
  6702. )
  6703. speak = logger.debug if quiet else logger.info
  6704. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6705. if not new_files:
  6706. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6707. return False
  6708. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6709. if not candidates:
  6710. speak(
  6711. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6712. attempt,
  6713. len(new_files),
  6714. )
  6715. return False
  6716. if len(candidates) > 1:
  6717. if require_unambiguous:
  6718. # The baseline is not evidence -- it was taken off a card that could
  6719. # not be read -- so "new since the baseline" does not narrow these
  6720. # down at all. Taking the first would attach an arbitrary video to
  6721. # this print and then delete it from the printer.
  6722. logger.warning(
  6723. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6724. "leaving all of them on the printer for manual selection",
  6725. attempt,
  6726. len(candidates),
  6727. ", ".join(str(f.get("name")) for f in candidates),
  6728. )
  6729. return False
  6730. logger.warning(
  6731. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6732. "the rest stay on the printer for manual selection",
  6733. attempt,
  6734. len(candidates),
  6735. ", ".join(str(f.get("name")) for f in candidates),
  6736. )
  6737. target = candidates[0]
  6738. file_name = str(target.get("name") or "") # every listed entry has one
  6739. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6740. logger.info(
  6741. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6742. attempt,
  6743. file_name,
  6744. archive_id,
  6745. )
  6746. # The listing always carries a size (`list_files` skips entries it can't
  6747. # parse), but read it explicitly: the delete below is destructive and must
  6748. # depend on a size we actually had, not on one we hoped was there.
  6749. expected_size = target.get("size")
  6750. try:
  6751. timelapse_data = await download_file_bytes_async(
  6752. printer.ip_address,
  6753. printer.access_code,
  6754. remote_path,
  6755. printer_model=printer.model,
  6756. expected_size=expected_size,
  6757. )
  6758. except DownloadDeadlineExceeded:
  6759. # Too slow for its size this round; the printer keeps its copy.
  6760. timelapse_data = None
  6761. if not timelapse_data:
  6762. # Short or failed transfer. The printer keeps its copy, so the next
  6763. # round can try again — which is exactly why the delete below is
  6764. # gated on a verified download.
  6765. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6766. return False
  6767. # The length check above proves we got what the listing said, not that the
  6768. # printer had finished writing. A video still being written can be listed
  6769. # short, served short, and pass — so confirm it has stopped growing before
  6770. # committing to it and deleting the original (#2704).
  6771. if not await remote_file_settled(
  6772. printer.ip_address,
  6773. printer.access_code,
  6774. remote_path,
  6775. len(timelapse_data),
  6776. printer_model=printer.model,
  6777. ):
  6778. return False
  6779. # Write phase: attach in a fresh short-lived session. The download took a
  6780. # while: by now the archive may have its video, or be printing again for a
  6781. # newer run, whose video this is not. Then nothing is attached or deleted,
  6782. # and the poll ends (True).
  6783. async with async_session() as db:
  6784. service = ArchiveService(db)
  6785. if run_id is not None or run_started_at is not _ANY_RUN:
  6786. current = await service.get_archive(archive_id)
  6787. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6788. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6789. logger.info(
  6790. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6791. "%s stays on the printer",
  6792. archive_id,
  6793. file_name,
  6794. )
  6795. return True
  6796. success = await service.attach_timelapse(
  6797. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6798. )
  6799. if not success:
  6800. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6801. return False
  6802. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6803. await delete_archived_timelapse(
  6804. printer.ip_address,
  6805. printer.access_code,
  6806. remote_path,
  6807. verified=expected_size is not None,
  6808. printer_model=printer.model,
  6809. printer_name=printer.name,
  6810. )
  6811. return True
  6812. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6813. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6814. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6815. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6816. # How long the *background* upgrade keeps waiting after the notification has
  6817. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6818. # printer can't hold up the print-complete notification; this one exists so the
  6819. # archive still ends up with the better frame afterwards.
  6820. #
  6821. # Measured across 261 attaches in the support bundles, the video lands a median
  6822. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6823. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6824. # was 546s. Every other model was inside 26s. The long budget is therefore
  6825. # almost entirely for P1-series users; on everything else the short wait already
  6826. # wins and this task never runs.
  6827. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6828. async def _capture_finish_photo_from_timelapse(
  6829. archive_id: int,
  6830. archive_dir: Path,
  6831. timeout: float | None = None,
  6832. rotation: int = 0,
  6833. run_id: int | None = None,
  6834. ) -> tuple[str | None, bool]:
  6835. """Wait for the per-print timelapse to land on the archive and extract its
  6836. last frame as the finish photo (#1397).
  6837. Bambu firmware stops timelapse recording after the toolhead parks but
  6838. before the bed-drop end-gcode runs, so the last frame frames the finished
  6839. print correctly. A live camera grab at gcode_state=FINISH captures the
  6840. bed already lowered.
  6841. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6842. ``archive.timelapse_path`` when the file lands. This function polls for
  6843. that field.
  6844. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6845. the wait ran out with no video on the archive yet — i.e. the video may
  6846. still be coming and a later attempt could succeed. It is False when the
  6847. video landed (whether or not extraction worked), because in that case
  6848. waiting longer changes nothing. The caller uses that to decide between
  6849. falling back permanently and scheduling a background upgrade.
  6850. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6851. still (#2708) so this source agrees with every other finish-photo source.
  6852. The archived video itself is the printer's own file and is left alone —
  6853. rotating it would mean re-encoding it.
  6854. ``run_id`` is the print that ended: its own video is the one waited for,
  6855. not the archive's, which can be another plate's.
  6856. """
  6857. import uuid
  6858. from backend.app.models.archive import PrintArchive
  6859. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6860. from backend.app.services.print_log import run_of
  6861. logger = logging.getLogger(__name__)
  6862. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6863. deadline = asyncio.get_event_loop().time() + budget
  6864. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6865. while True:
  6866. async with async_session() as db:
  6867. if run_id is not None:
  6868. run = await run_of(db, archive_id, run_id)
  6869. timelapse_relpath = run.timelapse_path if run else None
  6870. else:
  6871. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6872. archive = result.scalar_one_or_none()
  6873. timelapse_relpath = archive.timelapse_path if archive else None
  6874. if timelapse_relpath:
  6875. video_path = app_settings.base_dir / timelapse_relpath
  6876. if video_path.exists() and video_path.stat().st_size > 0:
  6877. photos_dir = archive_dir / "photos"
  6878. photos_dir.mkdir(parents=True, exist_ok=True)
  6879. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6880. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6881. output_path = photos_dir / filename
  6882. if await extract_video_last_frame(video_path, output_path):
  6883. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6884. logger.info(
  6885. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6886. video_path.name,
  6887. archive_id,
  6888. )
  6889. return filename, False
  6890. logger.warning(
  6891. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6892. video_path.name,
  6893. archive_id,
  6894. )
  6895. return None, False
  6896. if asyncio.get_event_loop().time() >= deadline:
  6897. logger.info(
  6898. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6899. archive_id,
  6900. budget,
  6901. )
  6902. return None, True
  6903. await asyncio.sleep(poll_interval)
  6904. async def _upgrade_finish_photo_from_timelapse(
  6905. archive_id: int,
  6906. archive_dir: Path,
  6907. rotation: int = 0,
  6908. run_id: int | None = None,
  6909. replace: str | None = None,
  6910. ) -> None:
  6911. """Put the timelapse's last frame on an archive after the fact (#2704).
  6912. The print-complete notification waits only ~60s for the video, because
  6913. holding a notification for minutes is worse than sending it with a live
  6914. camera grab. On a P1-series printer the video often lands well after that,
  6915. so the archive used to be stuck with the live grab — which is taken at
  6916. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6917. the worse photo of the two.
  6918. This keeps waiting in the background and, when the video arrives, extracts
  6919. the frame and puts it *first* in the archive's photo list, so opening the
  6920. gallery shows it. ``replace`` is the live grab: the frame is written over
  6921. that file, under its name, rather than added next to it. Two finish photos
  6922. of the same moment is one too many, and the name has to survive: with
  6923. authentication off, the notification that already went out links to
  6924. ``/archives/<id>/photos/<name>``, which now shows the better photo. (With
  6925. it on, the link is to a copy in notification_photos, and attachments are
  6926. bytes, so neither cares.) Without ``replace``, or once that photo has been
  6927. deleted, the frame is added under its own name. ``run_id`` is the print it
  6928. is for, whose list leads with it too.
  6929. """
  6930. from backend.app.services.print_log import add_run_photo, run_of
  6931. logger = logging.getLogger(__name__)
  6932. filename, _ = await _capture_finish_photo_from_timelapse(
  6933. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6934. )
  6935. if not filename:
  6936. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6937. return
  6938. try:
  6939. async with async_session() as db:
  6940. from backend.app.models.archive import PrintArchive
  6941. archive = await db.get(PrintArchive, archive_id)
  6942. if archive is None:
  6943. return
  6944. photos = list(archive.photos or [])
  6945. if filename in photos:
  6946. return
  6947. photos_dir = archive_dir / "photos"
  6948. if replace and replace in photos and (photos_dir / replace).is_file():
  6949. # Atomic, so the gallery never reads half a JPEG.
  6950. await asyncio.to_thread(os.replace, photos_dir / filename, photos_dir / replace)
  6951. filename = replace
  6952. photos.remove(replace)
  6953. # Front of the list: PhotoGalleryModal opens at index 0.
  6954. archive.photos = [filename, *photos]
  6955. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6956. await db.commit()
  6957. except Exception as e:
  6958. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6959. return
  6960. logger.info(
  6961. "[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s%s",
  6962. archive_id,
  6963. filename,
  6964. " (replacing the live grab)" if filename == replace else "",
  6965. )
  6966. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6967. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6968. """Put the filament-attribution context back after a restart mid-print.
  6969. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6970. both die with the process. The print keeps running, so at completion the
  6971. tracker would fall back to whatever the printer reports *now* — and AMS
  6972. filament backup makes "now" the substitute tray, charging the whole print
  6973. to the spool that only finished it.
  6974. The persisted row is only trusted when its print name still matches what
  6975. the printer says it is running: a row left behind by a completion we never
  6976. saw must not attach itself to the next print.
  6977. """
  6978. try:
  6979. from backend.app.api.routes.settings import get_setting
  6980. from backend.app.services.usage_tracker import (
  6981. clear_persisted_session,
  6982. get_persisted_ams_mapping,
  6983. get_persisted_print_name,
  6984. get_persisted_spool_change_log,
  6985. restore_session,
  6986. )
  6987. persisted_name = await get_persisted_print_name(db, printer_id)
  6988. current_name = (state.subtask_name or "").strip()
  6989. if persisted_name and current_name and persisted_name.strip() != current_name:
  6990. logger.info(
  6991. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6992. printer_id,
  6993. persisted_name,
  6994. current_name,
  6995. )
  6996. await clear_persisted_session(db, printer_id)
  6997. # Fall through to seeding: the print on the printer is real, it just
  6998. # isn't the one the row described.
  6999. persisted_log = None
  7000. else:
  7001. # Spoolman users get the tray-change log back but no in-memory
  7002. # session — see ``on_print_start`` on why that dict is load-bearing
  7003. # for the remain%-sync guard.
  7004. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7005. persisted_log = await restore_session(
  7006. db,
  7007. printer_id,
  7008. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  7009. )
  7010. # The slot pills (#1762) read the mapping captured from the print
  7011. # command, which dies with the process as well. One this process
  7012. # has captured since is newer.
  7013. if state.print_ams_mapping is None:
  7014. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  7015. # Spools swapped on a tray before the restart (#3325); anything this
  7016. # process has recorded since goes after them.
  7017. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  7018. if persisted_swaps:
  7019. seen = getattr(state, "spool_change_log", None) or []
  7020. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  7021. if persisted_log:
  7022. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  7023. # Anything this process already observed goes after the persisted
  7024. # history — the log is ordered by layer, and a fresh process can
  7025. # only have seen changes from later in the print.
  7026. for entry in state.tray_change_log or []:
  7027. if tuple(entry) not in restored:
  7028. restored.append(tuple(entry))
  7029. state.tray_change_log = restored
  7030. tray_now = state.tray_now
  7031. if 0 <= tray_now <= 254:
  7032. if not state.tray_change_log:
  7033. # No persisted history — a print that started before this build,
  7034. # or before the row existed. Seed with the tray feeding right
  7035. # now so the remainder of the print is at least attributable to
  7036. # the right spool.
  7037. state.tray_change_log = [(tray_now, state.layer_num)]
  7038. logger.info(
  7039. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  7040. printer_id,
  7041. tray_now,
  7042. state.layer_num,
  7043. )
  7044. # The tray handler updates ``last_loaded_tray`` on every push
  7045. # regardless of whether it logged a change, so re-align it to avoid
  7046. # a duplicate entry on the next push. Only ever with a real tray:
  7047. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  7048. # 255" fallback, and writing 255 into it would defeat that.
  7049. state.last_loaded_tray = tray_now
  7050. except Exception:
  7051. # Never let attribution recovery cost the caller its timelapse
  7052. # baseline — that capture has to happen before the printer uploads
  7053. # the in-flight MP4 and there is no second chance at it.
  7054. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  7055. async def on_print_running_observed(printer_id: int, data: dict):
  7056. """Restart-recovery for a print that started before Bambuddy came up.
  7057. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  7058. after Bambuddy startup (#1304 guard, prevents duplicate archive
  7059. creation). This hook restores the persisted archive into ``_active_prints``
  7060. and captures the timelapse baseline that normally hangs off print start.
  7061. Fires once per session, in lieu of on_print_start when restart-recovery
  7062. kicks in. The printer doesn't upload the timelapse until after PRINT
  7063. COMPLETE, so a baseline captured any time during the print is still
  7064. pre-upload.
  7065. """
  7066. logger = logging.getLogger(__name__)
  7067. async with async_session() as db:
  7068. from backend.app.models.printer import Printer
  7069. state = printer_manager.get_status(printer_id)
  7070. if state is not None:
  7071. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  7072. if authorization is True:
  7073. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  7074. await _restore_usage_tracking_session(printer_id, state, db, logger)
  7075. await _restore_printable_objects(printer_id, state, db, logger)
  7076. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7077. printer = result.scalar_one_or_none()
  7078. if not printer:
  7079. logger.warning(
  7080. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  7081. printer_id,
  7082. )
  7083. return
  7084. # Avoid double-capture: ownership reconciliation above must still run when
  7085. # a baseline already exists, but the camera work itself is one-shot.
  7086. if printer_id in _timelapse_baselines:
  7087. logger.debug(
  7088. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  7089. printer_id,
  7090. )
  7091. return
  7092. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  7093. class _RunOfArchive:
  7094. """An archive as one of its runs printed it: the run's job id, start and
  7095. plate, the rest the archive's. What the reconcile judges and closes."""
  7096. def __init__(self, archive, run):
  7097. self._archive = archive
  7098. self.subtask_id = run.subtask_id
  7099. self.started_at = run.started_at
  7100. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  7101. def __getattr__(self, name):
  7102. return getattr(self._archive, name)
  7103. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  7104. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  7105. against the printer's current MQTT state.
  7106. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  7107. COMPLETE events, typically a print finishing during an MQTT disconnect
  7108. window followed by a smart-plug power cycle):
  7109. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  7110. provably not running anymore — only branch that should fire under
  7111. normal disconnect-then-reconnect timing.
  7112. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  7113. firmware mints a fresh ``subtask_id`` for each print, including the
  7114. ghost replay it runs after a power cycle from a leftover SD file —
  7115. so a mismatch unambiguously means the in-DB archive is no longer
  7116. the print on the printer.
  7117. 3. Printer is running but ``subtask_name`` is empty. The printer
  7118. doesn't know what it's running; the archive's reference to it is
  7119. already broken.
  7120. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  7121. with matching subtask_id+subtask_name is left alone. The cost of a false
  7122. positive is a print closed while it still runs: the reconcile takes its
  7123. ``_active_prints`` entry and the archive is no longer ``printing``, so
  7124. the real PRINT COMPLETE later finds no archive to close (#1679). The
  7125. cost of a false negative is the ghost-print loop in #1542. What the
  7126. archive is closed as is ``_reconciled_outcome``'s call.
  7127. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  7128. MQTT has connected but the first ``push_status`` response hasn't been
  7129. applied yet — ``PrinterState`` is sitting on its construction defaults.
  7130. The reconcile caller in ``on_printer_status_change`` is already gated
  7131. on a real ``state.state``, so in normal operation this branch is
  7132. unreachable; it's kept as belt-and-braces for future callers and for
  7133. the narrow window where a partial state update could arrive
  7134. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  7135. ``not stale`` on degenerate input is strictly conservative: a real
  7136. stale archive will still be caught by the next push_status arriving
  7137. with terminal state.
  7138. """
  7139. current_state = (state.state or "").upper()
  7140. if current_state in ("", "UNKNOWN"):
  7141. # No real push_status yet — PrinterState defaults are not evidence.
  7142. return False, ""
  7143. if current_state in ("IDLE", "FINISH", "FAILED"):
  7144. return True, f"printer state {current_state}"
  7145. # Below here the printer is in a running / pre-running state (RUNNING /
  7146. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  7147. current_subtask_id = (state.subtask_id or "").strip()
  7148. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  7149. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  7150. current_subtask_name = (state.subtask_name or "").strip()
  7151. if not current_subtask_name:
  7152. return True, "printer subtask_name empty"
  7153. return False, ""
  7154. async def prime_kprofile_table(printer_id: int) -> int:
  7155. """Read the printer's calibration table once per connection.
  7156. The AMS slot card shows a K value per slot (#2854). On the printers whose
  7157. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  7158. report ``cali_idx`` and nothing else -- that number can only come from
  7159. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  7160. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  7161. backup, or the printer answering a query BambuStudio made on the report
  7162. topic we share. A Bambuddy that nobody visited showed a card with no K
  7163. values at all.
  7164. Only the diameters actually fitted are asked for, which is one request on a
  7165. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7166. what the backup does, and it is both wasteful and the thing that used to
  7167. blank the table.
  7168. Returns the number of nozzles whose table was read.
  7169. """
  7170. client = printer_manager.get_client(printer_id)
  7171. state = printer_manager.get_status(printer_id)
  7172. if client is None or state is None or not state.connected:
  7173. return 0
  7174. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7175. # ask once, and both entries are empty until the first push_status lands.
  7176. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7177. if not diameters:
  7178. logging.getLogger(__name__).debug(
  7179. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7180. printer_id,
  7181. )
  7182. return 0
  7183. primed = 0
  7184. for diameter in diameters:
  7185. try:
  7186. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7187. except Exception as exc: # noqa: BLE001
  7188. # A printer that won't answer costs the card its K values, nothing
  7189. # more — never the connection this runs on the back of.
  7190. logging.getLogger(__name__).warning(
  7191. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7192. )
  7193. continue
  7194. primed += 1
  7195. logging.getLogger(__name__).info(
  7196. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7197. )
  7198. return primed
  7199. def _sd_files_in_use(state) -> set[str]:
  7200. """Names of the SD-card files the printer may be printing right now (#3009).
  7201. The post-print cleanup works out what to delete from the finished archive,
  7202. not from the printer. When reconciliation closes an old archive because the
  7203. printer has moved on to a new job, and that job is the same file reprinted
  7204. from the printer's screen, the cleanup would delete the file mid-print.
  7205. Empty unless the printer is busy: on an ordinary completion the state is
  7206. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7207. name, a path or a URL depending on firmware, and some report only the
  7208. plate's G-code, so the job name is matched as well, in the same spellings
  7209. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7210. ignores case.
  7211. """
  7212. def _text(value) -> str:
  7213. return value.strip() if isinstance(value, str) else ""
  7214. if state is None:
  7215. return set()
  7216. current_state = _text(getattr(state, "state", None)).upper()
  7217. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7218. return set()
  7219. in_use: set[str] = set()
  7220. gcode_file = _text(getattr(state, "gcode_file", None))
  7221. if gcode_file:
  7222. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7223. # both legal in a file name, and raises on some inputs.
  7224. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7225. if name:
  7226. in_use.add(name.lower())
  7227. subtask_name = _text(getattr(state, "subtask_name", None))
  7228. if subtask_name:
  7229. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7230. for ext in (".3mf", ".gcode"):
  7231. in_use.add(f"{name}{ext}".lower())
  7232. return in_use
  7233. def _reconciled_outcome(archive, state) -> str:
  7234. """What a stale archive is closed as at reconnect (#3310).
  7235. A print that ends while Bambuddy restarts is never seen to end: the new
  7236. MQTT client's first status is already FINISH, which is not a transition.
  7237. The printer keeps reporting the finished job's ``subtask_id`` until the
  7238. next print, so a matching id proves the FINISH or FAILED is this
  7239. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7240. started outside the cloud) or none -- says only that the print is over,
  7241. not how, and stays ``aborted``.
  7242. """
  7243. current_state = (state.state or "").upper()
  7244. if current_state not in ("FINISH", "FAILED"):
  7245. return "aborted"
  7246. archive_id = (archive.subtask_id or "").strip()
  7247. current_id = str(state.subtask_id or "").strip()
  7248. if archive_id in ("", "0") or archive_id != current_id:
  7249. return "aborted"
  7250. return "completed" if current_state == "FINISH" else "failed"
  7251. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7252. """When a print reconciled as completed most likely ended, or None (#3310).
  7253. The printer does not say when it finished, and the reconnect can be hours
  7254. later. Its start plus the slicer's estimate for the plate it printed,
  7255. never later than now, is the best guess; None when either is missing,
  7256. and the run then keeps no duration, as an aborted one does.
  7257. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7258. of another plate reuses the archive without changing ``archive.plate_id``.
  7259. """
  7260. started = archive.started_at
  7261. if not started:
  7262. return None
  7263. if started.tzinfo is None:
  7264. started = started.replace(tzinfo=timezone.utc)
  7265. plate = plate_id if plate_id is not None else archive.plate_id
  7266. estimate = None
  7267. if archive.file_path:
  7268. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7269. full_path = (
  7270. app_settings.base_dir / archive.file_path
  7271. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7272. try:
  7273. estimate = extract_print_time_from_3mf(full_path, plate)
  7274. except Exception as exc: # noqa: BLE001
  7275. logging.getLogger(__name__).debug(
  7276. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7277. )
  7278. if plate is None and estimate != archive.print_time_seconds:
  7279. # Without a plate the first plate's estimate is read. The archive
  7280. # carries the sum over all plates (#1593), so a difference means
  7281. # several plates and no telling which one printed.
  7282. estimate = None
  7283. elif plate is None:
  7284. # Nothing to read the plate from; the archive's own estimate, as for
  7285. # a single-plate file.
  7286. estimate = archive.print_time_seconds
  7287. if not estimate or estimate <= 0:
  7288. return None
  7289. return min(started + timedelta(seconds=int(estimate)), now)
  7290. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7291. """Synthesise ``on_print_complete`` for archives whose print can't be
  7292. running on the printer anymore.
  7293. Called once per MQTT (re)connection (from on_printer_status_change when
  7294. the connected edge flips False → True) and at Bambuddy startup (from
  7295. the FastAPI lifespan). Without this, a print that completes during a
  7296. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7297. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7298. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7299. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7300. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7301. closes the loop by faking the missed PRINT COMPLETE — the existing
  7302. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7303. and notifications.
  7304. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7305. when the printer still reports the archive's own job as finished or
  7306. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7307. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7308. after a restart the printer's FINISH is not one (#3310).
  7309. Returns the number of archives reconciled.
  7310. """
  7311. state = printer_manager.get_status(printer_id)
  7312. if not state:
  7313. return 0
  7314. # Don't reconcile while disconnected — we'd be making a decision against
  7315. # stale cached state. The connected → reconcile edge handles this.
  7316. if not state.connected:
  7317. return 0
  7318. from backend.app.models.archive import PrintArchive
  7319. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7320. reconciled = 0
  7321. async with async_session() as db:
  7322. # The prints on this printer Bambuddy saw start: their runs open here.
  7323. # The archive row is shared by every plate of a file, its printer, job
  7324. # and start the latest start's, so each is judged as its run.
  7325. open_runs = (
  7326. await db.scalars(
  7327. select(PrintLogEntry)
  7328. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7329. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7330. )
  7331. ).all()
  7332. by_run = {
  7333. archive.id: archive
  7334. for archive in (
  7335. await db.scalars(
  7336. select(PrintArchive).where(
  7337. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7338. )
  7339. )
  7340. ).all()
  7341. }
  7342. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7343. # And as before runs were opened at the start: a printing archive of
  7344. # this printer with no run open anywhere (printing since before).
  7345. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7346. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7347. )
  7348. result = await db.execute(
  7349. select(PrintArchive)
  7350. .where(
  7351. PrintArchive.printer_id == printer_id,
  7352. PrintArchive.status == "printing",
  7353. PrintArchive.id.not_in(archives_with_open_runs),
  7354. )
  7355. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7356. )
  7357. active.extend(result.scalars().all())
  7358. if not active:
  7359. return 0
  7360. # The plate each run printed, from its queue job (#3310).
  7361. from backend.app.models.print_queue import PrintQueueItem
  7362. async with async_session() as db:
  7363. plate_rows = await db.execute(
  7364. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7365. PrintQueueItem.printer_id == printer_id,
  7366. PrintQueueItem.status == "printing",
  7367. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7368. )
  7369. )
  7370. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7371. logger = logging.getLogger(__name__)
  7372. for archive in active:
  7373. is_stale, reason = _is_active_archive_stale(archive, state)
  7374. if not is_stale:
  7375. continue
  7376. logger.info(
  7377. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7378. printer_id,
  7379. archive.id,
  7380. archive.filename,
  7381. reason,
  7382. )
  7383. # Synthesised payload: minimal fields the on_print_complete chain
  7384. # needs. `_reconciled` marker lets downstream code distinguish this
  7385. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7386. # metrics / debug logging). raw_data is the live printer state so
  7387. # the usage tracker can compare end-of-print remain% against the
  7388. # captured start values.
  7389. outcome = _reconciled_outcome(archive, state)
  7390. payload = {
  7391. "status": outcome,
  7392. "filename": archive.filename,
  7393. "subtask_name": archive.print_name or "",
  7394. "subtask_id": archive.subtask_id or "",
  7395. "raw_data": state.raw_data or {},
  7396. "_reconciled": True,
  7397. }
  7398. if isinstance(archive, _RunOfArchive):
  7399. # The archive it closes, which its names and printer may not find:
  7400. # another printer's plate of it can have started since.
  7401. payload["_reconciled_archive_id"] = archive.id
  7402. if outcome != "aborted":
  7403. # The printer's progress and layer are this job's, so a partial
  7404. # run is charged what it printed rather than nothing.
  7405. from backend.app.utils.printer_models import usage_progress
  7406. run_progress = usage_progress(
  7407. printer_manager.get_model(printer_id),
  7408. state.progress,
  7409. getattr(state, "layer_num", None),
  7410. getattr(state, "total_layers", None),
  7411. )
  7412. if run_progress:
  7413. payload["last_progress"] = run_progress
  7414. if state.layer_num:
  7415. payload["last_layer_num"] = state.layer_num
  7416. if outcome == "failed":
  7417. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7418. if outcome == "completed":
  7419. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7420. if ended:
  7421. payload["_reconciled_completed_at"] = ended
  7422. try:
  7423. await on_print_complete(printer_id, payload)
  7424. reconciled += 1
  7425. except Exception as e:
  7426. # Catch-all: a reconciliation failure must not block the
  7427. # printer's normal status flow. The archive stays in
  7428. # ``status="printing"`` and the next reconnect retries.
  7429. logger.warning(
  7430. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7431. archive.id,
  7432. e,
  7433. )
  7434. return reconciled
  7435. # #2547: clearance left between the nozzle and the top of the print when the
  7436. # plate is commanded back into camera framing. The nozzle is parked away from
  7437. # the part by then, so this is belt-and-braces against a max_z_height that
  7438. # under-reports (e.g. a slicer that excludes a final Z hop).
  7439. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7440. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7441. # this axis, so it is a proven-safe speed for the full travel.
  7442. _PLATE_RESTORE_FEEDRATE = 600
  7443. # Time allowed for the plate to reach the restored position before the camera
  7444. # grab. Sized for the ~100 mm the stock end G-code drops on X1/P1 at F600
  7445. # (10 mm/s); most H2 and P2 end G-code drops less, or not at all.
  7446. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7447. # How long `_background_finish_photo` waits for this producer. Must cover the
  7448. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7449. # notification path's own photo wait so a slow producer degrades to a
  7450. # photo-less notification rather than a missed one. The chamber light's
  7451. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7452. # camera_light.MAX_DELAY_SECONDS stays below it.
  7453. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7454. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7455. """The ``_active_prints`` keys a finished print may be registered under.
  7456. Matching how they were registered in on_print_start. Shared by
  7457. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7458. to find the same binding.
  7459. """
  7460. possible_keys = []
  7461. # Try subtask_name variations first (most reliable for matching)
  7462. if subtask_name:
  7463. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7464. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7465. possible_keys.append((printer_id, subtask_name))
  7466. # Try filename variations
  7467. if filename:
  7468. # Extract just the filename if it's a path
  7469. fname = filename.split("/")[-1] if "/" in filename else filename
  7470. if fname.endswith(".3mf"):
  7471. possible_keys.append((printer_id, fname))
  7472. elif fname.endswith(".gcode"):
  7473. base_name = fname.rsplit(".", 1)[0]
  7474. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7475. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7476. possible_keys.append((printer_id, fname))
  7477. else:
  7478. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7479. possible_keys.append((printer_id, f"{fname}.3mf"))
  7480. possible_keys.append((printer_id, fname))
  7481. # Also try full path versions
  7482. if filename.endswith(".3mf"):
  7483. possible_keys.append((printer_id, filename))
  7484. elif filename.endswith(".gcode"):
  7485. base_name = filename.rsplit(".", 1)[0]
  7486. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7487. possible_keys.append((printer_id, filename))
  7488. else:
  7489. possible_keys.append((printer_id, f"{filename}.3mf"))
  7490. possible_keys.append((printer_id, filename))
  7491. return possible_keys
  7492. def _archive_name_forms(archive) -> set[str]:
  7493. """The names an archive could be echoed back as, in normalised form (#3240).
  7494. Its print name, and its filename with and without the 3MF extension.
  7495. """
  7496. forms = set()
  7497. if archive.print_name:
  7498. forms.add(_normalise_subtask_name(archive.print_name))
  7499. if archive.filename:
  7500. forms.add(_normalise_subtask_name(archive.filename))
  7501. for suffix in (".gcode.3mf", ".3mf"):
  7502. if archive.filename.lower().endswith(suffix):
  7503. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7504. forms.discard("")
  7505. return forms
  7506. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7507. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7508. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7509. from the plate recorded when the job was dispatched. Neither is touched:
  7510. ``on_print_complete`` pops both, which is why the finish-photo producer
  7511. calls this before its first await, while they are still there.
  7512. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7513. archive, or that it only knows by a name -- and on any error: the producer
  7514. calls this before the ``try`` that always releases the photo consumer, so
  7515. it must not raise.
  7516. """
  7517. try:
  7518. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7519. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7520. if archive_id is None:
  7521. return None, None
  7522. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7523. except Exception:
  7524. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7525. return None, None
  7526. class PlateHeights(NamedTuple):
  7527. """Where the finished print is, and where its end G-code left the plate (#2547)."""
  7528. print_top: float
  7529. """The plate's ``max_z_height``: the Z the toolhead sat at for the last layer."""
  7530. end_z: float
  7531. """The last Z the end G-code moved to: where the plate is now, and where it is parked back to."""
  7532. async def _plate_heights_for_current_print(
  7533. printer_id: int,
  7534. data: dict,
  7535. logger,
  7536. archive_id: int | None,
  7537. plate_id: int | None = None,
  7538. ) -> PlateHeights | None:
  7539. """Heights of the print that just finished on ``printer_id``, or None (#2547).
  7540. These numbers become the targets of real Z moves, so every step here refuses
  7541. rather than guesses. Both have to be known: without the end Z there is no
  7542. position to park the plate back to that the printer's own G-code chose, and
  7543. the firmware won't stop a made-up one at the travel limit (#2579). A height belonging to some *other* print is the one
  7544. failure that could drive the nozzle into the model: 20 mm carried onto a
  7545. 200 mm print would command the plate up through the part.
  7546. Three independent things therefore have to agree before a height is
  7547. returned:
  7548. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7549. when it started (see ``_bound_print``), never one found by name. A name
  7550. is not an identity: every plate of a multi-plate file shares one, and a
  7551. reprint reuses its archive row, so the newest archive with the right
  7552. name can be another plate of the same file. Support bundles show the
  7553. old name lookup doing exactly that (archive 288 for a print bound to
  7554. 169, 313 layers against 125), stopped only by the layer check below.
  7555. No binding, no move.
  7556. 2. **Identity.** The bound archive's name still has to be the finished
  7557. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7558. because the printer echoes spaces as underscores (#3240). Exact: not a
  7559. substring, and not the completion check's tolerance for a truncated
  7560. echo.
  7561. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7562. match the layer count the printer itself reported over MQTT for the print
  7563. that just ended. These come from genuinely different sources, so a
  7564. mismatch means the row is not this print, whatever its name says.
  7565. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7566. plate of a multi-plate file reuses the archive row without updating its
  7567. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7568. ``on_print_complete`` may already have flipped the status by the time we
  7569. run.
  7570. """
  7571. subtask_name = (data.get("subtask_name") or "").strip()
  7572. if not subtask_name:
  7573. # Nothing to identify the print by — refuse rather than fall back to
  7574. # "whatever ran last on this printer".
  7575. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7576. return None
  7577. if archive_id is None:
  7578. logger.info(
  7579. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7580. printer_id,
  7581. subtask_name,
  7582. )
  7583. return None
  7584. try:
  7585. from backend.app.models.archive import PrintArchive
  7586. from backend.app.utils.threemf_tools import extract_end_z_from_3mf, extract_max_z_height_from_3mf
  7587. async with async_session() as db:
  7588. result = await db.execute(
  7589. select(PrintArchive).where(
  7590. PrintArchive.id == archive_id,
  7591. PrintArchive.printer_id == printer_id,
  7592. PrintArchive.status.in_(("printing", "completed")),
  7593. PrintArchive.deleted_at.is_(None),
  7594. )
  7595. )
  7596. archive = result.scalar_one_or_none()
  7597. if archive is None or not archive.file_path:
  7598. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7599. return None
  7600. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7601. logger.warning(
  7602. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7603. printer_id,
  7604. archive_id,
  7605. subtask_name,
  7606. )
  7607. return None
  7608. client = printer_manager.get_client(printer_id)
  7609. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7610. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7611. logger.warning(
  7612. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7613. "— refusing to move the plate on a height that may not be this print's",
  7614. printer_id,
  7615. archive.id,
  7616. archive.total_layers,
  7617. reported_layers,
  7618. )
  7619. return None
  7620. # Stored relative to the data directory, like every other archive path
  7621. # (#3240: this read a `data_dir` setting that does not exist).
  7622. path = app_settings.base_dir / archive.file_path
  7623. plate = plate_id or archive.plate_id or 1
  7624. print_top = await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7625. if print_top is None:
  7626. return None
  7627. end_z = await asyncio.to_thread(extract_end_z_from_3mf, path, plate)
  7628. if end_z is None:
  7629. logger.info(
  7630. "[PLATE-RESTORE] printer %s: archive %s has no end G-code position to park at — skipping",
  7631. printer_id,
  7632. archive_id,
  7633. )
  7634. return None
  7635. return PlateHeights(print_top, end_z)
  7636. except Exception as e:
  7637. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7638. return None
  7639. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7640. """Raise the plate back into camera framing before the finish photo (#2547).
  7641. On X1/P1/A1 Bambu's end G-code drops the plate ~100 mm as the last thing it
  7642. does, so by the time ``gcode_state`` reaches FINISH the finished print sits
  7643. far below the camera's natural framing — the complaint behind #1145, #1397
  7644. and #1565. This commands an absolute ``G1 Z`` back to just above the last
  7645. printed layer. Whether that is needed at all is ``_raise_plate_for_finish_photo``'s
  7646. call: plenty of end G-code (H2C, tall prints anywhere) leaves the plate in
  7647. view already.
  7648. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7649. clearance`` is a height the toolhead was physically at seconds earlier, so
  7650. it is inside the travel limits by construction and leaves the nozzle above
  7651. the part. It is also unambiguous across model families: Z is the
  7652. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7653. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7654. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7655. (#2579).
  7656. Returns True if the move was sent and waited out, False if it was skipped.
  7657. """
  7658. client = printer_manager.get_client(printer_id)
  7659. if client is None:
  7660. return False
  7661. # Re-read state immediately before commanding motion. If the queue has
  7662. # already started the next print, the printer is no longer ours to move.
  7663. state = getattr(client, "state", None)
  7664. if state is None or state.state != "FINISH":
  7665. logger.info(
  7666. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7667. printer_id,
  7668. getattr(state, "state", "unknown"),
  7669. )
  7670. return False
  7671. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7672. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7673. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7674. return False
  7675. logger.info(
  7676. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7677. printer_id,
  7678. target_z,
  7679. max_z_height,
  7680. _PLATE_RESTORE_CLEARANCE_MM,
  7681. _PLATE_RESTORE_SETTLE_SECONDS,
  7682. )
  7683. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7684. return True
  7685. def _park_plate_after_finish_photo(printer_id: int, end_z: float, logger) -> None:
  7686. """Put the plate back where the end G-code left it, after the finish photo (#2547).
  7687. ``end_z`` is the last Z the print's own end G-code moved to, never a height
  7688. worked out here. That is the safety argument: Bambu's templates keep their
  7689. end moves inside each model's travel, and the firmware does not clamp
  7690. G-code sent over MQTT (#2579). Parking at print top + 100 mm instead drove
  7691. the plate of a 238 mm H2C print to the bottom of its travel, a move Bambu's
  7692. own template had declined to make.
  7693. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7694. print homes anyway.
  7695. """
  7696. client = printer_manager.get_client(printer_id)
  7697. state = getattr(client, "state", None) if client else None
  7698. if client is None or state is None or state.state != "FINISH":
  7699. return
  7700. client.send_gcode(f"G90\nG1 Z{end_z:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7701. logger.info("[PLATE-RESTORE] printer %s: plate back to the end G-code's Z%.2f", printer_id, end_z)
  7702. async def _raise_plate_for_finish_photo(
  7703. printer_id: int, data: dict, logger, archive_id: int | None, plate_id: int | None
  7704. ) -> float | None:
  7705. """Raise the plate into view for the finish photo if it needs it (#2547).
  7706. Returns the Z to park the plate back to once the photo is taken, or None
  7707. when the plate wasn't moved. It needs moving only when the end G-code
  7708. left it lower than the restore height; when it is already at or above it
  7709. (the H2C end G-code puts it back 2 mm under the nozzle), raising would be
  7710. a move away from the camera.
  7711. """
  7712. heights = await _plate_heights_for_current_print(printer_id, data, logger, archive_id, plate_id)
  7713. if heights is None:
  7714. logger.info("[PLATE-RESTORE] printer %s: print height unknown — capturing without restore", printer_id)
  7715. return None
  7716. if heights.end_z <= heights.print_top + _PLATE_RESTORE_CLEARANCE_MM:
  7717. logger.info(
  7718. "[PLATE-RESTORE] printer %s: end G-code left the plate at Z%.2f (print top %.2f) — already in view",
  7719. printer_id,
  7720. heights.end_z,
  7721. heights.print_top,
  7722. )
  7723. return None
  7724. if await _plate_restore_is_blocked_by_queue(printer_id):
  7725. logger.info("[PLATE-RESTORE] printer %s has queued work — skipping plate restore", printer_id)
  7726. return None
  7727. if await _restore_plate_for_finish_photo(printer_id, heights.print_top, logger):
  7728. return heights.end_z
  7729. return None
  7730. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7731. """True if a queue item is about to take this printer (#2547).
  7732. The scheduler dispatches the next job the moment a print completes, and a
  7733. plate move interleaved with a print start is not a race worth having. The
  7734. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7735. this window; this closes the head of it.
  7736. """
  7737. try:
  7738. from backend.app.models.print_queue import PrintQueueItem
  7739. async with async_session() as db:
  7740. result = await db.execute(
  7741. select(PrintQueueItem.id)
  7742. .where(
  7743. PrintQueueItem.printer_id == printer_id,
  7744. PrintQueueItem.status.in_(("pending", "printing")),
  7745. )
  7746. .limit(1)
  7747. )
  7748. return result.scalar_one_or_none() is not None
  7749. except Exception as e:
  7750. # Fail closed: if we can't tell, don't move the plate.
  7751. logging.getLogger(__name__).debug(
  7752. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7753. )
  7754. return True
  7755. async def on_finish_photo_moment(printer_id: int, data: dict):
  7756. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7757. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7758. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7759. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7760. HMS halt, firmware variants). Grabs one frame via the same
  7761. external-camera / RTSP path the post-completion fallback uses, stores
  7762. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7763. ``_background_finish_photo`` consume the cached bytes when it runs.
  7764. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7765. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7766. set to Smooth (#1721). No force-on now means the user's explicit
  7767. timelapse=off in the slicer send dialog is respected.
  7768. """
  7769. logger = logging.getLogger(__name__)
  7770. trigger = data.get("trigger", "unknown")
  7771. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7772. logger.info(
  7773. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7774. printer_id,
  7775. trigger,
  7776. timelapse_was_active,
  7777. )
  7778. # If a timelapse is actively recording, skip the pre-capture — the
  7779. # post-completion path will extract the last frame from the recorded
  7780. # video, which still provides the best framing (toolhead parked,
  7781. # before bed drop) without the per-layer parking side effects.
  7782. if timelapse_was_active:
  7783. logger.info(
  7784. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7785. printer_id,
  7786. )
  7787. return
  7788. # #1790: register the producer-done event BEFORE the first await so the
  7789. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7790. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7791. # The `finally` below guarantees `set()` runs on every exit, including
  7792. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7793. producer_done = asyncio.Event()
  7794. _stage22_finish_in_flight[printer_id] = producer_done
  7795. # #3240: also before the first await. On the FINISH-state path
  7796. # `on_print_complete` is dispatched right behind us and pops both the
  7797. # print's archive binding and its plate; read here, they are still there.
  7798. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7799. # #2547: the Z to park the plate back to, set once the plate has actually
  7800. # been raised, and read by the `finally` below. Declared out here so a
  7801. # failure anywhere after the move — a camera timeout, a DB error — still
  7802. # lowers the plate again.
  7803. park_z: float | None = None
  7804. try:
  7805. async with async_session() as db:
  7806. from backend.app.api.routes.settings import get_setting
  7807. from backend.app.models.printer import Printer
  7808. capture_setting = await get_setting(db, "capture_finish_photo")
  7809. if capture_setting is not None and capture_setting.lower() != "true":
  7810. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7811. return
  7812. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7813. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7814. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7815. printer = result.scalar_one_or_none()
  7816. if printer is None:
  7817. logger.warning(
  7818. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7819. printer_id,
  7820. )
  7821. return
  7822. frame_bytes: bytes | None = None
  7823. # #2708: the banked frame arrives already rotated — it comes from
  7824. # `_capture_snapshot_for_notification`, which rotates before returning.
  7825. # Every other source below is a raw grab. Tracking which lets us store
  7826. # exactly one rotation in `_stage22_finish_frames` either way.
  7827. frame_already_rotated = False
  7828. # On the FINISH-state path the End G-code has already run, and two very
  7829. # different situations arrive here needing opposite answers.
  7830. #
  7831. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7832. # snippet may have ejected the plate — the scene in front of the camera
  7833. # is no longer the finished print, and no amount of moving the plate
  7834. # brings it back. Use the banked in-print frame instead.
  7835. #
  7836. # #2547: otherwise the print is still sitting there — on X1/P1/A1 ~100 mm
  7837. # lower than the camera frames well — and the toolhead is parked out of
  7838. # the way. That is the *best* moment available on firmware that never emits
  7839. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7840. # back. Preferring the bank here unconditionally, as this code used to,
  7841. # is what shipped a mid-print photo with the toolhead over the part.
  7842. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7843. banked = _inprint_frame_bank.get(printer_id)
  7844. if banked:
  7845. frame_bytes = banked
  7846. frame_already_rotated = True
  7847. logger.info(
  7848. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7849. "frame (%d bytes) instead of a post-swap live grab",
  7850. len(banked),
  7851. )
  7852. else:
  7853. logger.warning(
  7854. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7855. "in-print bank is empty — falling back to a live grab, which may show a "
  7856. "swapped or empty plate",
  7857. printer_id,
  7858. )
  7859. # `park_z` is set only once the plate is actually up, because the
  7860. # `finally` reads it to decide whether it owes a move back down.
  7861. #
  7862. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7863. # came up empty above: that machine may have just ejected its plate, and
  7864. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7865. # taking for a photo of a bed we already know may be bare.
  7866. if (
  7867. frame_bytes is None
  7868. and trigger == "finish_state"
  7869. and restore_plate_enabled
  7870. and not print_dispatch_context.end_gcode_injected(printer_id)
  7871. ):
  7872. park_z = await _raise_plate_for_finish_photo(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7873. # Chamber light for the live capture below (#1655). The banked frame
  7874. # above was taken without it, like every in-print bank.
  7875. async with camera_light(printer if frame_bytes is None else None):
  7876. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7877. from backend.app.api.routes.camera import live_frame_for_capture
  7878. from backend.app.services.external_camera import capture_frame
  7879. # #2707: this used to collide with the live view and fail, which is
  7880. # how finish-photo notifications went out with no image attached.
  7881. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7882. defer, buffered = live_frame_for_capture(printer_id)
  7883. if defer:
  7884. frame_bytes = buffered
  7885. else:
  7886. frame_bytes = await capture_frame(
  7887. printer.external_camera_url,
  7888. printer.external_camera_type or "mjpeg",
  7889. snapshot_url=printer.external_camera_snapshot_url,
  7890. )
  7891. if frame_bytes:
  7892. logger.info(
  7893. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7894. len(frame_bytes),
  7895. )
  7896. elif frame_bytes is None:
  7897. from backend.app.api.routes.camera import get_buffered_frame
  7898. buffered = get_buffered_frame(printer_id)
  7899. if buffered:
  7900. frame_bytes = buffered
  7901. logger.info(
  7902. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7903. len(frame_bytes),
  7904. )
  7905. else:
  7906. from backend.app.services.camera import capture_camera_frame_bytes
  7907. frame_bytes = await capture_camera_frame_bytes(
  7908. ip_address=printer.ip_address,
  7909. access_code=printer.access_code,
  7910. model=printer.model,
  7911. timeout=15,
  7912. )
  7913. if frame_bytes:
  7914. logger.info(
  7915. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7916. len(frame_bytes),
  7917. )
  7918. if frame_bytes:
  7919. if not frame_already_rotated:
  7920. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7921. _stage22_finish_frames[printer_id] = frame_bytes
  7922. else:
  7923. logger.warning(
  7924. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7925. printer_id,
  7926. )
  7927. except Exception as e:
  7928. logger.warning(
  7929. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7930. printer_id,
  7931. e,
  7932. )
  7933. finally:
  7934. # #2547: we raised the plate, so we own lowering it — including when the
  7935. # capture above failed or threw partway through.
  7936. if park_z is not None:
  7937. try:
  7938. _park_plate_after_finish_photo(printer_id, park_z, logger)
  7939. except Exception as e:
  7940. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7941. # #1790: always unblock the consumer's bounded wait — whether we stored
  7942. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7943. # dict entry by the consumer doesn't affect signalling.
  7944. producer_done.set()
  7945. def _subtask_name_from_filename(filename: str) -> str:
  7946. """Recover the subtask name a print command would have carried for *filename*.
  7947. The dispatcher derives the printer-facing subtask name from the archive's
  7948. file name, so stripping the extensions back off gives the value MQTT echoes
  7949. on completion. Only the two extensions Bambuddy actually stores are removed,
  7950. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7951. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7952. """
  7953. name = PurePosixPath(filename).name
  7954. for suffix in (".3mf", ".gcode"):
  7955. if name.lower().endswith(suffix):
  7956. name = name[: -len(suffix)]
  7957. return name
  7958. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7959. """Whether the subtask name is the printed 3MF's own file name.
  7960. A print started from the printer's screen reports the same full name, with
  7961. its extension, as both subtask and file (#3009). A dispatched print reports
  7962. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7963. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7964. """
  7965. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7966. return False
  7967. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7968. # How the printer marks a subtask name it had to cut short. Observed on real
  7969. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7970. # (a name with multibyte characters came back at 98), so match the marker
  7971. # rather than a length.
  7972. _SUBTASK_TRUNCATION_MARKER = "..."
  7973. def _normalise_subtask_name(name: str) -> str:
  7974. """Canonical form for comparing a dispatched name against MQTT's echo.
  7975. The printer does not echo the name back verbatim: it substitutes
  7976. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7977. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7978. The 3MF lookup in this module has always known that -- it builds
  7979. space-to-underscore variants of every candidate filename, and its
  7980. directory search normalises both sides before comparing. This exists so
  7981. the completion check reads the same rule from the same place instead of
  7982. growing its own, which is exactly how it came to disagree (#2829).
  7983. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7984. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7985. are dropped after the substitution so both sides agree (#3241).
  7986. """
  7987. return name.strip().replace(" ", "_").strip("_").casefold()
  7988. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7989. """The 3MF files of the printer's folder listings that are this print's.
  7990. A file of the print's own name wins, in whichever folder. Only without one
  7991. is a file that merely contains the name taken, and then only when it is
  7992. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7993. candidates none can be told apart. Paths keep the listings' order.
  7994. """
  7995. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7996. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7997. if exact:
  7998. return exact
  7999. term = _normalise_subtask_name(search_term)
  8000. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  8001. if len(partial) > 1:
  8002. logging.getLogger(__name__).info(
  8003. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  8004. )
  8005. return []
  8006. return partial
  8007. def _subtask_names_match(expected: str, observed: str) -> bool:
  8008. """Whether two subtask names describe the same print.
  8009. Beyond the space/underscore substitution, the printer truncates long names
  8010. and marks the cut with ``...``. A truncated echo has to count as a match or
  8011. every print with a long name strands its queue item the same way.
  8012. """
  8013. expected_n = _normalise_subtask_name(expected)
  8014. observed_n = _normalise_subtask_name(observed)
  8015. if expected_n == observed_n:
  8016. return True
  8017. # Either side can be the truncated one: the printer truncates what it
  8018. # echoes, and an archive whose own filename was recorded from a previous
  8019. # truncated echo carries the marker too.
  8020. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  8021. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  8022. continue
  8023. # The full side has lost its edge underscores; a cut that lands right
  8024. # after one keeps it, so drop it here too (#3241). Nothing left before
  8025. # the marker is no evidence of anything, and must not match every name.
  8026. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  8027. if kept and full.startswith(kept):
  8028. return True
  8029. return False
  8030. def _dispatched_name_matches_echo(expected: str, observed: str) -> bool:
  8031. """Whether the printer's subtask echo is the name a print was dispatched as.
  8032. A dispatched print is echoed under its bare name at start, but a printer
  8033. that picks a print back up -- Bambuddy reconnecting to a print already
  8034. running, or an A1 mini resuming after power-loss recovery -- can report the
  8035. file name with its extension instead (#3485). The echo is tried both as it
  8036. came and with the extensions stripped; the raw form still has to count, so
  8037. a model named ``Foo.3mf`` (file ``Foo.3mf.gcode.3mf``) keeps matching.
  8038. """
  8039. return _subtask_names_match(expected, observed) or _subtask_names_match(
  8040. expected, _subtask_name_from_filename(observed)
  8041. )
  8042. async def _queue_item_dispatched_name(db, item) -> str:
  8043. """The subtask name *item* was dispatched under, or "" when unknowable.
  8044. A row with no archive, or an archive with no file name, is unverifiable
  8045. rather than wrong; every caller answers that with its permissive branch.
  8046. """
  8047. if item.archive_id is None:
  8048. return ""
  8049. from backend.app.models.archive import PrintArchive
  8050. archive = await db.get(PrintArchive, item.archive_id)
  8051. if archive is None or not archive.filename:
  8052. return ""
  8053. return _subtask_name_from_filename(archive.filename)
  8054. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  8055. """Whether this completion event is plausibly about *item*'s print.
  8056. The caller finds its queue row by printer and ``status='printing'`` alone,
  8057. which is all a completion event gives it -- there is no run identifier in
  8058. the MQTT payload to match on. That makes the lookup indiscriminate: any
  8059. completion delivered for this printer closes whichever row happens to be
  8060. printing, however unrelated. Comparing the subtask name against the archive
  8061. the row was dispatched with costs one primary-key load and rules that out.
  8062. Deliberately permissive: it answers False only on a positive disagreement
  8063. between two names we actually have. A row with no archive, an archive with
  8064. no file name, or an event with no subtask name is unverifiable rather than
  8065. wrong, and refusing those would strand the item in ``printing`` and wedge
  8066. the printer's queue -- a worse failure than the one being prevented.
  8067. """
  8068. observed = (data.get("subtask_name") or "").strip()
  8069. if not observed or item.archive_id is None:
  8070. return True
  8071. from backend.app.models.archive import PrintArchive
  8072. archive = await db.get(PrintArchive, item.archive_id)
  8073. if archive is None or not archive.filename:
  8074. return True
  8075. expected = _subtask_name_from_filename(archive.filename)
  8076. if not expected or _dispatched_name_matches_echo(expected, observed):
  8077. return True
  8078. logging.getLogger(__name__).warning(
  8079. "Ignoring print completion for queue item %s: it was dispatched as %r "
  8080. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  8081. "printing rather than closing a run this event is not about.",
  8082. item.id,
  8083. expected,
  8084. archive.id,
  8085. archive.filename,
  8086. observed,
  8087. )
  8088. return False
  8089. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  8090. """Spend the 3MF download cache on a still-empty fallback archive.
  8091. ``on_print_complete`` drops the cache as its first act, which deletes the
  8092. file. If the cover endpoint (or anything else) pulled the 3MF while the
  8093. print ran and the archive never got one, this is the last moment those bytes
  8094. exist (#2957).
  8095. """
  8096. logger = logging.getLogger(__name__)
  8097. names = [
  8098. n
  8099. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  8100. if n
  8101. ]
  8102. for name in names:
  8103. try:
  8104. cached = get_cached_3mf(printer_id, name)
  8105. # The print has ended: its completion prices the archive, so no
  8106. # print-start estimate is scheduled to race it.
  8107. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  8108. return
  8109. except Exception as e:
  8110. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  8111. # Longest the print's end waits for its file to be deleted from the SD card
  8112. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  8113. async def _cleanup_sd_card_after_print(
  8114. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  8115. ) -> None:
  8116. """Delete a finished print's file from the printer's SD card."""
  8117. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  8118. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  8119. # auto-start files found in root on power cycle, causing ghost prints.
  8120. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  8121. try:
  8122. if subtask_name:
  8123. archive_filename: str | None = None
  8124. async with async_session() as db:
  8125. from backend.app.models.archive import PrintArchive
  8126. from backend.app.models.printer import Printer
  8127. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8128. printer = result.scalar_one_or_none()
  8129. if archive_id:
  8130. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  8131. archive_filename = archive_row.scalar_one_or_none()
  8132. if printer:
  8133. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  8134. from backend.app.utils.filename import derive_remote_filename
  8135. # Primary candidate: the exact path the dispatcher uploaded to
  8136. # (derived from archive.filename via the same rule as upload).
  8137. # Without it, a library row that ended up with a doubled
  8138. # .gcode.3mf (#1542) leaves the real file behind because the
  8139. # subtask_name + ext fallbacks below don't match what's on the
  8140. # SD card. Fallbacks remain for archive-less prints (subtask
  8141. # never resolved to an archive) and for older naming variants.
  8142. candidate_paths: list[str] = []
  8143. if archive_filename:
  8144. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  8145. for ext in (".3mf", ".gcode"):
  8146. fallback = f"/{subtask_name}{ext}"
  8147. if fallback not in candidate_paths:
  8148. candidate_paths.append(fallback)
  8149. # Three outcomes track across all candidates so the final log
  8150. # line reflects what actually happened. The A1 in #1721 always
  8151. # ends here with ``any_not_found=True`` and the others False
  8152. # — its firmware auto-cleans the SD card before our cleanup
  8153. # runs, every candidate FTP-DELE returns 550, and the old
  8154. # code burned 3 retries × 2 s × 3 candidates per print
  8155. # logging a misleading "may linger" WARNING on a successful
  8156. # print.
  8157. any_deleted = False
  8158. any_real_failure = False
  8159. any_not_found = False
  8160. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  8161. for remote_path in candidate_paths:
  8162. if PurePosixPath(remote_path).name.lower() in files_in_use:
  8163. logger.info(
  8164. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  8165. remote_path,
  8166. printer.name,
  8167. )
  8168. continue
  8169. # Retry only the FAILED case — 550 NOT_FOUND will never
  8170. # recover by waiting, so a "file isn't here" answer
  8171. # advances immediately to the next candidate without
  8172. # consuming the retry budget.
  8173. for attempt in range(1, 4):
  8174. try:
  8175. delete_result = await delete_file_async(
  8176. printer.ip_address,
  8177. printer.access_code,
  8178. remote_path,
  8179. printer_model=printer.model,
  8180. )
  8181. except Exception as e:
  8182. delete_result = DeleteResult.FAILED
  8183. logger.warning(
  8184. "SD card cleanup attempt %d/3 raised for %s: %s",
  8185. attempt,
  8186. remote_path,
  8187. e,
  8188. )
  8189. if delete_result == DeleteResult.DELETED:
  8190. any_deleted = True
  8191. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  8192. break
  8193. if delete_result == DeleteResult.NOT_FOUND:
  8194. any_not_found = True
  8195. break # 550 will not recover; try next candidate
  8196. # FAILED: real error — retry with backoff, then give up
  8197. if attempt < 3:
  8198. await asyncio.sleep(2)
  8199. else:
  8200. any_real_failure = True
  8201. logger.warning(
  8202. "SD card cleanup failed after 3 attempts for %s "
  8203. "(network/auth/transient error — file may linger on SD card)",
  8204. remote_path,
  8205. )
  8206. if not any_deleted and not any_real_failure and any_not_found:
  8207. # Every candidate said "not here." Either the printer
  8208. # firmware swept the SD card itself (common on A1) or the
  8209. # dispatcher's upload path doesn't match our candidate
  8210. # rule. Either way: nothing to clean up, no warning.
  8211. logger.debug(
  8212. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  8213. "(printer likely self-cleaned)",
  8214. printer.name,
  8215. )
  8216. except Exception as e:
  8217. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8218. async def on_print_complete(printer_id: int, data: dict):
  8219. """Handle print completion - update the archive status.
  8220. The printer counts as printing until the print's usage is booked (or this
  8221. ends), so the AMS remain% weight sync can't charge it a second time while
  8222. the usage tracker works (WU-3). Marked before the first await.
  8223. """
  8224. from backend.app.services.usage_tracker import done_completing, mark_completing
  8225. mark_completing(printer_id)
  8226. try:
  8227. await _close_out_print(printer_id, data)
  8228. finally:
  8229. done_completing(printer_id)
  8230. async def _close_out_print(printer_id: int, data: dict):
  8231. import time
  8232. logger = logging.getLogger(__name__)
  8233. start_time = time.time()
  8234. def log_timing(section: str):
  8235. elapsed = time.time() - start_time
  8236. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8237. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8238. octoeverywhere_detection_service.reset_printer(printer_id)
  8239. # A kill-switch stop sends its provider notification immediately. Keep the
  8240. # task so the later notification path can await it and avoid a duplicate;
  8241. # if that immediate attempt failed, the regular completion path retries.
  8242. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8243. # Last chance before the bytes go: if this print's archive is still an empty
  8244. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8245. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8246. # below deletes the file (#2957).
  8247. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8248. # A pending cool-off retry has nothing left to recover for — the cache is
  8249. # about to be dropped and the print is over.
  8250. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8251. if retry_task and not retry_task.done():
  8252. retry_task.cancel()
  8253. # Drop the 3MF download cache for this printer (#972). The print is over,
  8254. # nothing else legitimately needs the bytes; keeping them would only risk
  8255. # handing a stale file to the next print if it reuses the same name.
  8256. clear_3mf_cache(printer_id)
  8257. try:
  8258. ws_data = {
  8259. "status": data.get("status"),
  8260. "filename": data.get("filename"),
  8261. "subtask_name": data.get("subtask_name"),
  8262. "timelapse_was_active": data.get("timelapse_was_active"),
  8263. }
  8264. await ws_manager.send_print_complete(printer_id, ws_data)
  8265. log_timing("WebSocket send_print_complete")
  8266. except Exception as e:
  8267. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8268. # Capture user info before clearing (needed for print log entry)
  8269. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8270. # Clear current print user tracking (Issue #206)
  8271. printer_manager.clear_current_print_user(printer_id)
  8272. # If the user explicitly stopped this print from the queue UI the printer will
  8273. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8274. # correct "print stopped" notification/email is sent instead of a failure alert.
  8275. _raw_status = data.get("status", "completed")
  8276. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8277. logger.info(
  8278. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8279. _raw_status,
  8280. printer_id,
  8281. )
  8282. data = {**data, "status": "cancelled"}
  8283. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8284. logger.info(
  8285. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8286. _raw_status,
  8287. printer_id,
  8288. )
  8289. data = {**data, "status": "cancelled", "_kill_switch": True}
  8290. _user_stopped_printers.discard(printer_id)
  8291. _kill_switch_stopped.discard(printer_id)
  8292. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8293. # may have left material on the bed: a user can cancel ten hours into a
  8294. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8295. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8296. # `_user_stopped_printers` is only populated when the user stops via the
  8297. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8298. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8299. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8300. # Auto Off power cycles and Bambuddy restarts.
  8301. try:
  8302. notify_live_activities.print_finished(printer_id, data)
  8303. except Exception:
  8304. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8305. _final_status = data.get("status", "completed")
  8306. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8307. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8308. # MQTT relay - publish print complete
  8309. try:
  8310. printer_info = printer_manager.get_printer(printer_id)
  8311. if printer_info:
  8312. await mqtt_relay.on_print_complete(
  8313. printer_id,
  8314. printer_info.name,
  8315. printer_info.serial_number,
  8316. data.get("filename", ""),
  8317. data.get("subtask_name", ""),
  8318. data.get("status", "completed"),
  8319. )
  8320. except Exception:
  8321. pass # Don't fail print complete callback if MQTT fails
  8322. filename = data.get("filename", "")
  8323. subtask_name = data.get("subtask_name", "")
  8324. if not filename and not subtask_name:
  8325. # Which print ended can't be told: the printer reported no name since
  8326. # Bambuddy started (a print that failed while preparing, a calibration).
  8327. # Charge nothing, but close the print session, which otherwise kept the
  8328. # AMS weight sync off until the next print (AS-5). A print archived as
  8329. # running is closed and charged by the reconnect reconcile.
  8330. logger.warning("Print complete without filename or subtask_name")
  8331. try:
  8332. from backend.app.services.usage_tracker import discard_session
  8333. async with async_session() as db:
  8334. await discard_session(db, printer_id)
  8335. except Exception as e:
  8336. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8337. return
  8338. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8339. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8340. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8341. # Find the archive for this print
  8342. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8343. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8344. archive_id = None
  8345. for key in possible_keys:
  8346. archive_id = _active_prints.pop(key, None)
  8347. if archive_id:
  8348. _owned_print_archive_ids.discard(archive_id)
  8349. logger.info("Found archive %s with key %s", archive_id, key)
  8350. # Also clean up the printer's other keys pointing to this archive;
  8351. # another printer's are a plate of it still printing there.
  8352. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8353. for k in keys_to_remove:
  8354. _active_prints.pop(k, None)
  8355. break
  8356. # The archive bound when the print started, before the name search below.
  8357. # Only this one may give the finish-photo plate restore a height (#3240):
  8358. # the search matches names by substring.
  8359. bound_archive_id = archive_id
  8360. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8361. # The reconcile names the archive whose run on this printer it
  8362. # closes. Only while that run is open: the print's real end may have
  8363. # closed it meanwhile, or closed the print without managing to write
  8364. # it, and either way there is nothing left to end twice.
  8365. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8366. logger.info(
  8367. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8368. data["_reconciled_archive_id"],
  8369. printer_id,
  8370. )
  8371. return
  8372. archive_id = data["_reconciled_archive_id"]
  8373. ending_job = str(data.get("subtask_id") or "").strip()
  8374. if not archive_id and ending_job not in ("", "0"):
  8375. # Not bound (a restart since the start): this job's run, open on the
  8376. # printer. Only by its job id: a run open there can be of the print
  8377. # running now, while the end is of an earlier one closed late (the
  8378. # restart's reconcile of a missed end).
  8379. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8380. if archive_id:
  8381. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8382. if not archive_id:
  8383. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8384. async with async_session() as db:
  8385. from backend.app.models.archive import PrintArchive
  8386. # Try matching by subtask_name (stored as print_name) first. The
  8387. # same name rule as the queue's completion check: a name inside
  8388. # another ("Clip" in "Cable Clip") is a different print, and the
  8389. # printer's underscores for spaces and truncation still match.
  8390. if subtask_name:
  8391. printing = await db.scalars(
  8392. select(PrintArchive)
  8393. .where(PrintArchive.printer_id == printer_id)
  8394. .where(PrintArchive.status == "printing")
  8395. .order_by(PrintArchive.created_at.desc())
  8396. )
  8397. # A print started from the printer's screen reports its file
  8398. # name, extensions included, as the subtask (#3009).
  8399. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8400. archive = next(
  8401. (
  8402. candidate
  8403. for candidate in printing
  8404. if any(
  8405. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8406. or (
  8407. candidate.filename
  8408. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8409. )
  8410. for name in reported
  8411. )
  8412. ),
  8413. None,
  8414. )
  8415. if archive:
  8416. archive_id = archive.id
  8417. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8418. # Also try by filename
  8419. if not archive_id and filename:
  8420. result = await db.execute(
  8421. select(PrintArchive)
  8422. .where(PrintArchive.printer_id == printer_id)
  8423. .where(PrintArchive.filename == filename)
  8424. .where(PrintArchive.status == "printing")
  8425. .order_by(PrintArchive.created_at.desc())
  8426. .limit(1)
  8427. )
  8428. archive = result.scalar_one_or_none()
  8429. if archive:
  8430. archive_id = archive.id
  8431. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8432. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8433. # closed below. The stranded-job closer gives up after five and closed it
  8434. # first, so the job's auto-off and its billing never ran. Inline rather
  8435. # than in the background, so the next job of the same file isn't released
  8436. # (and uploaded under the name being deleted) while the cleanup still
  8437. # works on it. A delete already sent may still finish in its FTP thread
  8438. # after the cutoff, as one past delete_file_async's own timeout always did.
  8439. try:
  8440. await asyncio.wait_for(
  8441. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8442. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8443. )
  8444. except TimeoutError:
  8445. logger.warning(
  8446. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8447. printer_id,
  8448. _SD_CLEANUP_BUDGET_SECONDS,
  8449. )
  8450. log_timing("SD card cleanup")
  8451. # Update queue item status early — must run before the archive_id early-return
  8452. # so queue items don't get stuck in "printing" when archive lookup fails.
  8453. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8454. queue_item_id = None
  8455. billing_run_id: str | None = None
  8456. billing_user_id: int | None = None
  8457. billing_cost_center_id: int | None = None
  8458. billing_plate_id: int | None = None
  8459. queue_status = None
  8460. queue_auto_off = False
  8461. try:
  8462. from backend.app.core.database import run_with_retry
  8463. from backend.app.models.print_queue import PrintQueueItem
  8464. async def _update_queue_status(db):
  8465. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8466. nonlocal queue_item_id, queue_status, queue_auto_off
  8467. result = await db.execute(
  8468. select(PrintQueueItem)
  8469. .where(PrintQueueItem.printer_id == printer_id)
  8470. .where(PrintQueueItem.status == "printing")
  8471. )
  8472. printing_items = list(result.scalars().all())
  8473. if len(printing_items) > 1:
  8474. logger.warning(
  8475. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8476. printer_id,
  8477. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8478. )
  8479. item = printing_items[0] if printing_items else None
  8480. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8481. return
  8482. if item:
  8483. queue_status = data.get("status", "completed")
  8484. # MQTT sends "aborted" for cancelled prints; normalise to
  8485. # "cancelled" so it matches the queue schema Literal.
  8486. if queue_status == "aborted":
  8487. queue_status = "cancelled"
  8488. item.status = queue_status
  8489. item.completed_at = datetime.now(timezone.utc)
  8490. if queue_status == "failed" and not item.error_message:
  8491. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8492. # Bump usage counters on the source library file so admins can
  8493. # sort by "last printed" and (eventually) auto-purge stale
  8494. # files — #1008.
  8495. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8496. await db.commit()
  8497. queue_item_id = item.id
  8498. billing_run_id = item.billing_run_id
  8499. billing_user_id = item.created_by_id
  8500. billing_cost_center_id = item.cost_center_id
  8501. billing_plate_id = item.plate_id
  8502. queue_auto_off = item.auto_off_after
  8503. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8504. await run_with_retry(_update_queue_status, label="queue status update")
  8505. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8506. # their own sessions and have their own error handling — no retry needed.
  8507. if queue_item_id is not None:
  8508. # Batch orders (#342): this run may have been the last one an order
  8509. # owed. Re-evaluate here rather than lazily on read, so a finished
  8510. # order reports itself complete without someone opening the page.
  8511. try:
  8512. from backend.app.services.print_batch import refresh_batch_status_for_item
  8513. async with async_session() as db:
  8514. await refresh_batch_status_for_item(db, queue_item_id)
  8515. await db.commit()
  8516. except Exception as e:
  8517. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8518. # MQTT relay - publish queue job completed
  8519. try:
  8520. printer_info = printer_manager.get_printer(printer_id)
  8521. await mqtt_relay.on_queue_job_completed(
  8522. job_id=queue_item_id,
  8523. filename=filename or subtask_name,
  8524. printer_id=printer_id,
  8525. printer_name=printer_info.name if printer_info else "Unknown",
  8526. status=queue_status,
  8527. )
  8528. except Exception:
  8529. pass # Don't fail if MQTT fails
  8530. # Check if queue is now empty and send notification
  8531. try:
  8532. from sqlalchemy import func as sa_func
  8533. async with async_session() as db:
  8534. count_result = await db.execute(
  8535. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8536. )
  8537. pending_count = count_result.scalar() or 0
  8538. if pending_count == 0:
  8539. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8540. completed_result = await db.execute(
  8541. select(sa_func.count(PrintQueueItem.id)).where(
  8542. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8543. PrintQueueItem.completed_at >= today_start,
  8544. )
  8545. )
  8546. completed_count = completed_result.scalar() or 1
  8547. await notification_service.on_queue_completed(
  8548. completed_count=completed_count,
  8549. db=db,
  8550. )
  8551. except Exception:
  8552. pass # Don't fail if notification fails
  8553. # Handle auto_off_after - power off printer if the queue item opted
  8554. # in. Delegates to the smart-plug manager so the off honours each
  8555. # plug's configured strategy (time delay or temperature threshold),
  8556. # is cancelled if the printer starts printing again, and never cuts
  8557. # power on a loaded print (#1890). Previously an inline block here
  8558. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8559. # timeout regardless of print state — cutting a touchscreen reprint.
  8560. if queue_auto_off:
  8561. try:
  8562. async with async_session() as db:
  8563. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8564. except Exception as e:
  8565. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8566. except Exception as e:
  8567. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8568. log_timing("Queue item update")
  8569. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8570. # Must run before archive_id early-return so it fires for all prints (including
  8571. # prints started from BambuStudio/touchscreen that have no archive).
  8572. if data.get("status") == "completed":
  8573. try:
  8574. from backend.app.api.routes.settings import get_setting
  8575. async with async_session() as db:
  8576. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8577. threshold = float(threshold_str) if threshold_str else 35.0
  8578. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8579. async with async_session() as db:
  8580. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8581. if providers:
  8582. _bed_cool_waiters[printer_id] = {
  8583. "threshold": threshold,
  8584. "filename": filename or subtask_name or "",
  8585. "registered_at": time.time(),
  8586. }
  8587. logger.info(
  8588. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8589. printer_id,
  8590. threshold,
  8591. )
  8592. else:
  8593. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8594. except Exception as e:
  8595. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8596. # Capture the slicer estimate before usage tracking runs. The tracker may
  8597. # update archive.cost with this run's measured cost; billing partial runs
  8598. # against that already-partial value would discount the charge twice.
  8599. billing_planned_grams: float | None = None
  8600. billing_base_cost: float | None = None
  8601. if archive_id:
  8602. try:
  8603. async with async_session() as db:
  8604. from backend.app.models.archive import PrintArchive
  8605. billing_archive = await db.get(PrintArchive, archive_id)
  8606. if billing_archive:
  8607. billing_path = (
  8608. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8609. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8610. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8611. billing_archive,
  8612. billing_path,
  8613. billing_plate_id
  8614. if billing_plate_id is not None
  8615. else _get_start_plate_id(printer_id, archive_id),
  8616. )
  8617. except Exception as e:
  8618. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8619. # --- Track filament consumption (must run before archive_id early-return so usage
  8620. # is recorded even when auto-archive is disabled) ---
  8621. usage_results: list[dict] = []
  8622. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8623. stored_ams_mapping = data.get("ams_mapping")
  8624. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8625. # Drained either way, like the plate below: left over, it would be read by
  8626. # the archive's next run, dispatched without a mapping.
  8627. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8628. if not stored_ams_mapping:
  8629. stored_ams_mapping = registered_ams_mapping
  8630. # Always drain the plate_id register on completion — the session already
  8631. # consumed it at print-start injection; leaving it would leak into the next
  8632. # print on the same archive_id (rare but possible with reprints) (#1697).
  8633. # Capture the popped value so the completion notification can scope the
  8634. # archive-level (summed-across-plates per #1593) filament + time totals
  8635. # down to the single plate that was actually printed (#1785).
  8636. notify_plate_id: int | None = None
  8637. if archive_id:
  8638. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8639. # The start estimate must not outlive the real cost written below (COST-4).
  8640. if archive_id:
  8641. await _settle_archive_cost_estimate(archive_id)
  8642. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8643. try:
  8644. async with async_session() as db:
  8645. from backend.app.api.routes.settings import get_setting
  8646. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8647. if not _spoolman_on or _spoolman_on.lower() != "true":
  8648. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8649. async with async_session() as db:
  8650. usage_results = await usage_on_print_complete(
  8651. printer_id,
  8652. data,
  8653. printer_manager,
  8654. db,
  8655. archive_id=archive_id,
  8656. ams_mapping=stored_ams_mapping,
  8657. )
  8658. if usage_results:
  8659. await ws_manager.broadcast(
  8660. {
  8661. "type": "spool_usage_logged",
  8662. "printer_id": printer_id,
  8663. "usage": usage_results,
  8664. }
  8665. )
  8666. log_timing("Usage tracker")
  8667. except Exception as e:
  8668. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8669. # Drop the print-start context unconditionally — the Spoolman branch above
  8670. # skips the internal tracker entirely, so nothing else would clear what
  8671. # print start captured, and a row surviving its print would be restored
  8672. # onto the next one after a restart.
  8673. try:
  8674. from backend.app.services.usage_tracker import discard_session
  8675. async with async_session() as db:
  8676. await discard_session(db, printer_id)
  8677. except Exception as e:
  8678. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8679. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8680. # A partial run's cost from the Spoolman spools it was charged to; the
  8681. # built-in inventory's comes in usage_results.
  8682. spoolman_run_cost: float | None = None
  8683. if archive_id:
  8684. if data.get("status") == "completed":
  8685. try:
  8686. await _report_spoolman_usage(printer_id, archive_id)
  8687. log_timing("Spoolman usage report")
  8688. except Exception as e:
  8689. logger.warning("Spoolman usage reporting failed: %s", e)
  8690. else:
  8691. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8692. try:
  8693. async with async_session() as db:
  8694. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8695. printer_id,
  8696. archive_id,
  8697. db,
  8698. last_layer_num=data.get("last_layer_num"),
  8699. last_progress=data.get("last_progress"),
  8700. status=data.get("status") or "failed",
  8701. )
  8702. except Exception as e:
  8703. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8704. await _release_archived_spoolman_slots(printer_id)
  8705. log_timing("Filament usage tracking")
  8706. if not archive_id:
  8707. # The printer's own calibration run has no archive by design, so this
  8708. # arrives here every time one finishes. Returning before the no-archive
  8709. # notification keeps a calibration from being announced as a finished
  8710. # print. Everything above this point has already run — the plate-clear
  8711. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8712. # notification is skipped.
  8713. if is_internal_printer_job(filename, subtask_name):
  8714. logger.info(
  8715. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8716. filename,
  8717. subtask_name,
  8718. )
  8719. return
  8720. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8721. # Still send print-complete/failed/stopped notifications even without an archive.
  8722. # Try to enrich with queue/library-file data so user-specific emails work too.
  8723. async def _notify_no_archive():
  8724. try:
  8725. async with async_session() as db:
  8726. from backend.app.models.library import LibraryFile
  8727. from backend.app.models.print_queue import PrintQueueItem
  8728. from backend.app.models.printer import Printer
  8729. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8730. printer_obj = result.scalar_one_or_none()
  8731. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8732. # Only the queue item this completion itself closed (the
  8733. # reconciliation above, which checks the run belongs to it).
  8734. # A print started outside Bambuddy closed none, and must not
  8735. # borrow an earlier job's owner, email or times.
  8736. no_archive_data: dict | None = None
  8737. try:
  8738. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8739. if queue_item:
  8740. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8741. # How long it really ran, as the archive path reports it (#1198).
  8742. started = to_naive_utc(queue_item.started_at)
  8743. ended = to_naive_utc(queue_item.completed_at)
  8744. # Not for a completion reconciled at reconnect: it
  8745. # ended at an unknown time while the printer was
  8746. # offline, and "now" is the reconnect (DB-C9).
  8747. if (
  8748. not data.get("_reconciled")
  8749. and started
  8750. and ended
  8751. and (ended - started).total_seconds() > 0
  8752. ):
  8753. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8754. # Estimated time: the queue item caches it from its
  8755. # archive or library file; otherwise read the library
  8756. # file's metadata (LibraryFile has no column for it).
  8757. if queue_item.print_time_seconds:
  8758. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8759. elif queue_item.library_file_id:
  8760. lib_result = await db.execute(
  8761. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8762. )
  8763. lib_file = lib_result.scalar_one_or_none()
  8764. estimate = (
  8765. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8766. )
  8767. if estimate:
  8768. no_archive_data["print_time_seconds"] = estimate
  8769. except Exception as lookup_err:
  8770. logger.debug(
  8771. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8772. )
  8773. # Enrich with usage tracker results (captured in enclosing scope)
  8774. if usage_results:
  8775. if no_archive_data is None:
  8776. no_archive_data = {}
  8777. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8778. if total_from_usage > 0:
  8779. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8780. no_archive_data["usage_results"] = usage_results
  8781. # Try MQTT remaining_time for print duration when no queue/library data
  8782. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8783. mqtt_remaining = data.get("remaining_time")
  8784. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8785. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8786. ps = data.get("status", "completed")
  8787. logger.info(
  8788. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8789. )
  8790. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8791. await notification_service.on_print_complete(
  8792. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8793. )
  8794. else:
  8795. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8796. # Send user-specific email if we have a created_by_id
  8797. if no_archive_data and no_archive_data.get("created_by_id"):
  8798. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8799. await _dispatch_user_print_email(
  8800. ps,
  8801. no_archive_data["created_by_id"],
  8802. p_name,
  8803. raw_filename,
  8804. db,
  8805. )
  8806. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8807. except Exception as e:
  8808. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8809. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8810. return
  8811. log_timing("Archive lookup")
  8812. # Update archive status
  8813. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8814. try:
  8815. async with async_session() as db:
  8816. service = ArchiveService(db)
  8817. status = data.get("status", "completed")
  8818. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8819. if hms_errors:
  8820. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8821. failure_reason = derive_failure_reason(status, hms_errors)
  8822. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8823. # A reconciled completion closes out a stale archive at
  8824. # reconnect — it is not a user action, so don't mislabel it
  8825. # "userCancelled". It shares the stale-cleanup path's key
  8826. # (issue #2974) and records that the real end time is unknown,
  8827. # which is also why its logged duration is 0 (#2592). A failed
  8828. # one the printer's errors explain keeps their reason (#3310).
  8829. failure_reason = "noStatusUpdate"
  8830. elif data.get("_kill_switch"):
  8831. # Not the user's cancel: the kill switch stopped a print that did
  8832. # not come from Bambuddy.
  8833. failure_reason = "killSwitch"
  8834. if failure_reason:
  8835. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8836. elif status == "failed" and hms_errors:
  8837. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8838. await service.update_archive_status(
  8839. archive_id,
  8840. status=status,
  8841. completed_at=(
  8842. # A reconciled completed print ended at an estimated time,
  8843. # not at the reconnect (#3310).
  8844. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8845. if status in ("completed", "failed", "aborted", "cancelled")
  8846. else None
  8847. ),
  8848. failure_reason=failure_reason,
  8849. )
  8850. logger.info(
  8851. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8852. )
  8853. await ws_manager.send_archive_updated(
  8854. {
  8855. "id": archive_id,
  8856. "status": status,
  8857. }
  8858. )
  8859. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8860. # MQTT relay - publish archive updated
  8861. try:
  8862. await mqtt_relay.on_archive_updated(
  8863. archive_id=archive_id,
  8864. print_name=filename or subtask_name,
  8865. status=status,
  8866. )
  8867. except Exception:
  8868. pass # Don't fail if MQTT fails
  8869. except Exception as e:
  8870. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8871. # Continue with other operations even if archive update fails
  8872. log_timing("Archive status update")
  8873. # Apply finance wallet charge or release reservations once. For all partial
  8874. # terminal states (failed, aborted at the printer display, or cancelled via
  8875. # Bambuddy) use this run's measured spool delta, falling back to the last
  8876. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8877. # estimate and therefore cannot represent an interrupted run.
  8878. try:
  8879. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8880. async with async_session() as db:
  8881. from backend.app.models.archive import PrintArchive
  8882. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8883. from backend.app.services.print_log import run_being_ended
  8884. archive = await db.get(PrintArchive, archive_id)
  8885. # The run this end fills in below: charged as its own, not as
  8886. # the archive's latest dispatch (another plate of it, maybe).
  8887. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8888. if archive and billing_run_id is None and charged_run is None:
  8889. billing_run_id = getattr(archive, "billing_run_id", None)
  8890. if archive and archive.created_by_id is None and _print_user_info:
  8891. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8892. await db.flush()
  8893. run_status = data.get("status", "completed")
  8894. last_progress = data.get("last_progress")
  8895. if last_progress is None:
  8896. last_progress = data.get("progress")
  8897. actual_run_grams = _compute_run_filament_grams(
  8898. run_status,
  8899. billing_planned_grams,
  8900. last_progress,
  8901. usage_results,
  8902. )
  8903. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8904. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8905. charged = await apply_print_charge_for_archive(
  8906. db,
  8907. archive_id,
  8908. charged_user_id=billing_user_id,
  8909. cost_center_id=(
  8910. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8911. ),
  8912. print_queue_id=queue_item_id,
  8913. print_run_id=billing_run_id,
  8914. base_cost_override=billing_base_cost,
  8915. filament_usage=filament_usage,
  8916. run_entry_id=charged_run.id if charged_run is not None else None,
  8917. run_status=run_status,
  8918. )
  8919. await db.commit()
  8920. if charged:
  8921. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8922. except Exception as e:
  8923. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8924. printer_info = printer_manager.get_printer(printer_id)
  8925. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8926. billing_filename = filename or subtask_name or "Unknown"
  8927. billing_error = str(e)
  8928. try:
  8929. await ws_manager.broadcast(
  8930. {
  8931. "type": "billing_charge_failed",
  8932. "printer_id": printer_id,
  8933. "printer_name": billing_printer_name,
  8934. "filename": billing_filename,
  8935. "archive_id": archive_id,
  8936. }
  8937. )
  8938. except Exception as notification_error:
  8939. logger.error(
  8940. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8941. archive_id,
  8942. notification_error,
  8943. )
  8944. async def _notify_billing_charge_failed() -> None:
  8945. try:
  8946. async with async_session() as notification_db:
  8947. await notification_service.on_billing_charge_failed(
  8948. printer_id,
  8949. billing_printer_name,
  8950. billing_filename,
  8951. archive_id,
  8952. billing_error,
  8953. notification_db,
  8954. )
  8955. except Exception as provider_error:
  8956. logger.error(
  8957. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8958. archive_id,
  8959. provider_error,
  8960. exc_info=True,
  8961. )
  8962. spawn_background_task(
  8963. _notify_billing_charge_failed(),
  8964. name=f"billing-charge-failed-{archive_id}",
  8965. )
  8966. log_timing("Finance charge update")
  8967. # Write independent print log entry (separate table, never touches archives)
  8968. # The run's id, for the energy work below: the archive's newest run is
  8969. # the one started last, which with plates of it on two printers need not
  8970. # be the one that just ended.
  8971. completed_run_id: int | None = None
  8972. async def _write_run(db):
  8973. # Retried on a locked SQLite database: a run left open here would be
  8974. # closed again by the next reconnect's reconcile.
  8975. nonlocal completed_run_id
  8976. from backend.app.models.archive import PrintArchive
  8977. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8978. archive = await db.get(PrintArchive, archive_id)
  8979. if archive is None:
  8980. # Deleted while it printed: its run has nothing left to end on.
  8981. discarded = await discard_open_runs(db, printer_id)
  8982. await db.commit()
  8983. await _announce_discarded_runs(discarded, printer_id)
  8984. if archive:
  8985. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8986. # source archive row rather than creating a new one, so an
  8987. # archive that was auto-created from a printer-initiated
  8988. # print (created_by_id=NULL) would otherwise stay unattributed
  8989. # forever. When we have a print-session user AND the archive
  8990. # has no attribution yet, credit the current user. Never
  8991. # overwrite an existing attribution — the original uploader
  8992. # keeps ownership.
  8993. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8994. if archive.created_by_id is None and _print_user_id is not None:
  8995. archive.created_by_id = _print_user_id
  8996. p_info = printer_manager.get_printer(printer_id)
  8997. # Per-run actuals — written to PrintLogEntry so stats reflect
  8998. # what THIS print actually used, not the source archive's
  8999. # first-run values (#1378). Helper handles the partial-print
  9000. # math (failed / cancelled / stopped get scaled to progress
  9001. # or to tracked spool deltas).
  9002. _run_status = data.get("status", "completed")
  9003. # #2614: scope the per-run estimate to the printed plate. For a
  9004. # multi-plate 3MF dispatched one plate at a time, the archive's
  9005. # filament/cost are the whole-file totals; the PrintLogEntry must
  9006. # reflect only this plate. No effect on single-plate archives (the
  9007. # plate estimate equals the whole-file value) or on the tracker
  9008. # path (measured spool deltas win in _compute_run_filament_grams).
  9009. _est_full_path = (
  9010. app_settings.base_dir / archive.file_path if archive.file_path else None
  9011. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  9012. # The plate that printed, as billing reads it: a reprint of
  9013. # another plate must not log the archive's first plate.
  9014. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  9015. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  9016. if _run_plate_id is None:
  9017. _run_plate_id = archive.plate_id
  9018. _run_grams = _compute_run_filament_grams(
  9019. _run_status,
  9020. _est_grams,
  9021. data.get("last_progress", data.get("progress")),
  9022. usage_results,
  9023. )
  9024. # Per-run cost — prefer usage_results sum. For partial prints
  9025. # we deliberately skip the topup-to-estimate logic in
  9026. # usage_tracker (which assumes the print completed); the raw
  9027. # tracked-spool sum is closer to what THIS run actually cost.
  9028. _run_cost: float | None = None
  9029. if usage_results:
  9030. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  9031. if _run_cost is None and _run_status != "completed":
  9032. _run_cost = spoolman_run_cost
  9033. if _run_cost is None and _run_status == "completed":
  9034. _run_cost = _est_cost
  9035. from backend.app.models.printer import Printer as _Printer
  9036. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  9037. run_entry = await write_log_entry(
  9038. db,
  9039. archive_id=archive.id,
  9040. # Captured by _update_queue_status above; None for
  9041. # printer-initiated prints with no queue row. Batch
  9042. # cost/energy roll-up joins on it (#342).
  9043. queue_item_id=queue_item_id,
  9044. status=_run_status,
  9045. print_name=archive.print_name,
  9046. # The plate this run printed, as the estimate above takes
  9047. # it; the archive's own is the latest run's.
  9048. plate_id=_run_plate_id,
  9049. printer_name=p_info.name if p_info else None,
  9050. printer_id=printer_id,
  9051. started_at=archive.started_at,
  9052. completed_at=archive.completed_at,
  9053. filament_type=archive.filament_type,
  9054. filament_color=archive.filament_color,
  9055. filament_used_grams=_run_grams,
  9056. cost=_run_cost,
  9057. wear_cost_per_hour=_wear_rate,
  9058. failure_reason=archive.failure_reason,
  9059. thumbnail_path=archive.thumbnail_path,
  9060. created_by_id=archive.created_by_id,
  9061. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  9062. # Reconciled completions have an unknown real end time —
  9063. # log 0 duration instead of the whole disconnect gap (#2592),
  9064. # unless it was estimated (#3310).
  9065. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  9066. # Its time is the estimate or nothing, never measured (#3310).
  9067. duration_unmeasured=bool(data.get("_reconciled")),
  9068. # The real end of a print stopped while its printer was offline.
  9069. replaces_offline_stop=True,
  9070. )
  9071. await record_archive_wear(db, archive, run_entry)
  9072. await db.commit()
  9073. completed_run_id = run_entry.id
  9074. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  9075. try:
  9076. from backend.app.core.database import run_with_retry
  9077. await run_with_retry(_write_run, label="print log entry")
  9078. except Exception as e:
  9079. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  9080. await _publish_run_completed(completed_run_id, printer_id)
  9081. log_timing("Print log entry")
  9082. # Run slow operations as background tasks to avoid blocking the event loop
  9083. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  9084. async def _background_energy_calculation():
  9085. """Calculate and save energy usage in background.
  9086. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  9087. backend restart no longer loses per-print energy data).
  9088. """
  9089. try:
  9090. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  9091. async with async_session() as db:
  9092. from backend.app.models.archive import PrintArchive
  9093. from backend.app.models.print_log import PrintLogEntry
  9094. from backend.app.services.print_log import energy_start_of
  9095. archive = await db.get(PrintArchive, archive_id)
  9096. if archive is None:
  9097. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  9098. return
  9099. # The ended run's own start reading: the archive's is its
  9100. # latest start's, maybe another plate's on another printer.
  9101. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9102. start = energy_start_of(run_row, archive)
  9103. if start is None:
  9104. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  9105. return
  9106. starting_kwh = start.kwh
  9107. candidates = await energy_plug_candidates(db, printer_id)
  9108. if not candidates:
  9109. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  9110. return
  9111. # Same ordering as the start reading, so the delta below is
  9112. # against the counter that produced `starting_kwh` (#2859).
  9113. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  9114. if selected is None:
  9115. logger.warning(
  9116. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  9117. printer_id,
  9118. ", ".join(plug.name for plug in candidates),
  9119. )
  9120. return
  9121. plug, energy = selected
  9122. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  9123. energy_used = round(energy["total"] - starting_kwh, 4)
  9124. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  9125. if energy_used < 0:
  9126. logger.warning(
  9127. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  9128. archive_id,
  9129. starting_kwh,
  9130. energy["total"],
  9131. )
  9132. return
  9133. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  9134. # Each hour of the print at the price of that hour (#1251). If
  9135. # that fails, the last price known, as before, rather than no
  9136. # energy at all. Read first: the session may be unusable after.
  9137. last_price = await stored_price(db)
  9138. try:
  9139. energy_cost_value = round(
  9140. await print_energy_cost(
  9141. db,
  9142. plug_id=start.plug_id,
  9143. start_at=start.at,
  9144. start_kwh=starting_kwh,
  9145. start_price=start.price,
  9146. end_kwh=energy["total"],
  9147. end_plug_id=plug.id,
  9148. price_now=await current_price(db),
  9149. ),
  9150. 3,
  9151. )
  9152. except Exception as e:
  9153. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  9154. energy_cost_value = round(energy_used * last_price, 3)
  9155. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  9156. # reprint doesn't visually clobber the source archive's energy data
  9157. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  9158. from sqlalchemy import func
  9159. existing_runs = await db.scalar(
  9160. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  9161. )
  9162. if (existing_runs or 0) <= 1:
  9163. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  9164. # we just wrote for THIS print. Either way it's the first run.
  9165. archive.energy_kwh = energy_used
  9166. archive.energy_cost = energy_cost_value
  9167. # The ended run's energy (write_log_entry above ran before this
  9168. # background task, so its energy fields are still NULL). With
  9169. # no run written, none: the archive's newest is another print's.
  9170. if run_row is not None:
  9171. run_row.energy_kwh = energy_used
  9172. run_row.energy_cost = energy_cost_value
  9173. await db.commit()
  9174. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  9175. except Exception as e:
  9176. logger.warning("[ENERGY-BG] Failed: %s", e)
  9177. async def _background_finish_photo() -> str | None:
  9178. """Capture finish photo in background. Returns photo filename if captured."""
  9179. # #2547: the Z to park the plate back to, set once this function has
  9180. # raised the plate itself (the timelapse path, where the moment producer
  9181. # returned without doing it). Declared out here so the `finally` can
  9182. # lower it again no matter where the capture below fails.
  9183. park_z: float | None = None
  9184. try:
  9185. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  9186. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  9187. # Read phase: settings + printer + archive in a short session, released
  9188. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  9189. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  9190. # tens of seconds; holding this session across it pinned one pooled
  9191. # connection idle-in-transaction per finishing print (issue #2572).
  9192. async with async_session() as db:
  9193. from backend.app.api.routes.settings import get_setting
  9194. from backend.app.models.archive import PrintArchive
  9195. from backend.app.models.printer import Printer
  9196. capture_enabled = await get_setting(db, "capture_finish_photo")
  9197. if capture_enabled is not None and capture_enabled.lower() != "true":
  9198. return None
  9199. if not archive_id:
  9200. return None
  9201. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  9202. archive = (
  9203. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9204. ).scalar_one_or_none()
  9205. if not printer or not archive:
  9206. return None
  9207. import uuid
  9208. from datetime import datetime
  9209. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  9210. if not archive.file_path:
  9211. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  9212. archive_dir = resolve_archive_dir(archive)
  9213. photo_filename = None
  9214. # Prefer the timelapse last-frame source when a timelapse was
  9215. # recording — it captures the moment after the toolhead parks
  9216. # but before the bed drops, which the live-camera grab below
  9217. # would miss (#1397). Skipped for external cameras (those have
  9218. # their own framing and don't see a Bambu timelapse). Only
  9219. # runs when the USER explicitly enabled timelapse for this
  9220. # print — #1721 removed Bambuddy's force-on at dispatch
  9221. # because it caused per-layer nozzle parking on Smooth-mode
  9222. # slicer profiles.
  9223. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9224. printer.external_camera_enabled and printer.external_camera_url
  9225. )
  9226. timelapse_still_pending = False
  9227. if prefer_timelapse_source:
  9228. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9229. archive_id=archive_id,
  9230. archive_dir=archive_dir,
  9231. rotation=getattr(printer, "camera_rotation", 0),
  9232. run_id=completed_run_id,
  9233. )
  9234. # #1721: replacement framing path — on_finish_photo_moment
  9235. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9236. # parked, bed not yet dropped) and cached the JPEG bytes in
  9237. # _stage22_finish_frames. Consume them now so the saved photo
  9238. # has the better framing instead of the post-bed-drop angle
  9239. # the live-camera fallback below would give.
  9240. if not photo_filename:
  9241. # #1790: on the FINISH-state fallback path the producer
  9242. # task is dispatched back-to-back with this consumer, so
  9243. # a bare pop would race past with an empty result and
  9244. # the RTSP fallback below would collide with the
  9245. # producer's still-in-flight grab (single-client RTSP
  9246. # on Bambu printers). Wait for the producer to finish
  9247. # or give up before touching the cache.
  9248. #
  9249. # #2547: 20s was enough when the producer only ever grabbed a
  9250. # frame. It now also raises the plate first, which costs the
  9251. # settle window before the grab even starts — so the budget has
  9252. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9253. # under the notification's own photo wait below.
  9254. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9255. if in_flight is not None:
  9256. try:
  9257. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9258. except TimeoutError:
  9259. logger.warning(
  9260. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9261. printer_id,
  9262. )
  9263. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9264. if cached_frame:
  9265. # Already rotated by the producer (#2708) — rotating again
  9266. # here would undo the fix on the banked-frame path, whose
  9267. # bytes reach the cache having been rotated once already.
  9268. photos_dir = archive_dir / "photos"
  9269. photos_dir.mkdir(parents=True, exist_ok=True)
  9270. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9271. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9272. photo_path = photos_dir / photo_filename
  9273. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9274. logger.info(
  9275. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9276. photo_filename,
  9277. len(cached_frame),
  9278. )
  9279. # #2547: the timelapse path reaches the live grab below whenever the
  9280. # video hasn't landed in time — the documented usual outcome on
  9281. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9282. # returned early for those prints without raising the plate, so
  9283. # without this the photo that actually ships in the notification is
  9284. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9285. # asked us to fix. The archive still gets the better video frame
  9286. # later; this is about the image the user is sent.
  9287. #
  9288. # Gated on `timelapse_was_active` precisely because that is the
  9289. # condition under which the producer skipped. On every other path it
  9290. # has already raised and lowered the plate, and repeating that here
  9291. # would be a second pointless round trip.
  9292. if (
  9293. not photo_filename
  9294. and data.get("timelapse_was_active")
  9295. and not print_dispatch_context.end_gcode_injected(printer_id)
  9296. ):
  9297. try:
  9298. async with async_session() as db:
  9299. from backend.app.api.routes.settings import get_setting
  9300. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9301. if restore_setting is None or restore_setting.lower() == "true":
  9302. park_z = await _raise_plate_for_finish_photo(
  9303. printer_id, data, logger, bound_archive_id, notify_plate_id
  9304. )
  9305. except Exception as e:
  9306. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9307. # Fallback chain: external camera → buffered live frame →
  9308. # fresh RTSP capture. Only runs if the timelapse path above
  9309. # didn't already produce a photo.
  9310. # Chamber light for the live capture below (#1655).
  9311. async with camera_light(printer if not photo_filename else None):
  9312. if not photo_filename:
  9313. if printer.external_camera_enabled and printer.external_camera_url:
  9314. logger.info("[PHOTO-BG] Using external camera")
  9315. from backend.app.api.routes.camera import live_frame_for_capture
  9316. from backend.app.services.external_camera import capture_frame
  9317. # #2707: the second half of the finish-photo failure — the
  9318. # pre-capture and this fallback both collided with the live
  9319. # view. None here continues down the fallback chain.
  9320. defer, buffered = live_frame_for_capture(printer_id)
  9321. if defer:
  9322. frame_data = buffered
  9323. else:
  9324. frame_data = await capture_frame(
  9325. printer.external_camera_url,
  9326. printer.external_camera_type or "mjpeg",
  9327. snapshot_url=printer.external_camera_snapshot_url,
  9328. )
  9329. if frame_data:
  9330. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9331. photos_dir = archive_dir / "photos"
  9332. photos_dir.mkdir(parents=True, exist_ok=True)
  9333. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9334. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9335. photo_path = photos_dir / photo_filename
  9336. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9337. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9338. else:
  9339. # Check if camera stream is active - use buffered frame to avoid freeze
  9340. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9341. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9342. active_chamber_for_printer = [
  9343. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9344. ]
  9345. buffered_frame = get_buffered_frame(printer_id)
  9346. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9347. # Use frame from active stream
  9348. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9349. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9350. photos_dir = archive_dir / "photos"
  9351. photos_dir.mkdir(parents=True, exist_ok=True)
  9352. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9353. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9354. photo_path = photos_dir / photo_filename
  9355. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9356. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9357. else:
  9358. # No active stream - capture new frame
  9359. from backend.app.services.camera import capture_finish_photo
  9360. photo_filename = await capture_finish_photo(
  9361. printer_id=printer_id,
  9362. ip_address=printer.ip_address,
  9363. access_code=printer.access_code,
  9364. model=printer.model,
  9365. archive_dir=archive_dir,
  9366. rotation=getattr(printer, "camera_rotation", 0),
  9367. )
  9368. # Write phase: attach the photo in a fresh short-lived session.
  9369. if photo_filename:
  9370. async with async_session() as db:
  9371. from backend.app.models.archive import PrintArchive
  9372. from backend.app.services.print_log import add_run_photo, run_of
  9373. arch = await db.get(PrintArchive, archive_id)
  9374. # The ended print's own list takes it too: the archive's
  9375. # holds every print's.
  9376. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9377. if arch is not None:
  9378. # A new list: appended in place, the ORM sees no
  9379. # change and a second print's photo is never saved.
  9380. photos = list(arch.photos or [])
  9381. photos.append(photo_filename)
  9382. arch.photos = photos
  9383. add_run_photo(run, photo_filename)
  9384. await db.commit()
  9385. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9386. # The short wait above is bounded so a slow printer can't hold up
  9387. # the print-complete notification, which is what the caller is
  9388. # blocking on. When it ran out with the video still on its way,
  9389. # keep waiting off to the side and swap the better frame into the
  9390. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9391. # users, whose videos routinely take minutes to transfer, never get
  9392. # the pre-bed-drop framing this path exists to provide.
  9393. #
  9394. # Spawned here rather than at the point the wait gave up: both this
  9395. # function and the upgrade do a read-modify-write on `photos`, and
  9396. # the live-camera fallback above can take tens of seconds. Starting
  9397. # the upgrade before that write means the two can interleave and one
  9398. # silently drops the other's entry, leaving a JPEG on disk that the
  9399. # gallery never lists.
  9400. if timelapse_still_pending:
  9401. from backend.app.services import archive_work
  9402. spawn_background_task(
  9403. archive_work.held_while(
  9404. archive_id,
  9405. _upgrade_finish_photo_from_timelapse(
  9406. archive_id,
  9407. archive_dir,
  9408. rotation=getattr(printer, "camera_rotation", 0),
  9409. run_id=completed_run_id,
  9410. replace=photo_filename,
  9411. ),
  9412. ),
  9413. name=f"finish-photo-upgrade-{archive_id}",
  9414. )
  9415. return photo_filename
  9416. except Exception as e:
  9417. logger.warning("[PHOTO-BG] Failed: %s", e)
  9418. return None
  9419. finally:
  9420. # #2547: we raised the plate, so we owe the move back down — even if
  9421. # the capture in between threw. Otherwise the user finds the print
  9422. # pinned under the nozzle.
  9423. if park_z is not None:
  9424. try:
  9425. _park_plate_after_finish_photo(printer_id, park_z, logger)
  9426. except Exception as e:
  9427. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9428. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9429. # Photo capture task - result will be used by notifications
  9430. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9431. log_timing("Background tasks scheduled (energy, photo)")
  9432. # Also run smart plug, notifications, and maintenance as background tasks
  9433. print_status = data.get("status", "completed")
  9434. async def _background_smart_plug():
  9435. """Handle smart plug automation in background."""
  9436. try:
  9437. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9438. async with async_session() as db:
  9439. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9440. logger.info("[AUTO-OFF-BG] Completed")
  9441. except Exception as e:
  9442. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9443. async def _background_notifications(finish_photo_filename: str | None = None):
  9444. """Send print complete notifications in background."""
  9445. try:
  9446. logger.info(
  9447. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9448. )
  9449. async with async_session() as db:
  9450. from backend.app.models.archive import PrintArchive
  9451. from backend.app.models.printer import Printer
  9452. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9453. printer = result.scalar_one_or_none()
  9454. printer_name = printer.name if printer else f"Printer {printer_id}"
  9455. archive_data = None
  9456. if archive_id:
  9457. from backend.app.models.print_log import PrintLogEntry
  9458. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9459. archive = archive_result.scalar_one_or_none()
  9460. # The run that ended: the archive shows its latest, which
  9461. # with another plate of it printing elsewhere is not this.
  9462. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9463. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9464. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9465. if archive:
  9466. # Actual elapsed time from started_at/completed_at when both are
  9467. # populated (every terminal status sets completed_at after #1198).
  9468. # Falls back to None so the notification path can decide whether to
  9469. # render the slicer estimate as a last resort.
  9470. actual_time_seconds = None
  9471. # Unknown for a completion reconciled at reconnect: the
  9472. # print ended while the printer was offline and
  9473. # completed_at is the reconnect, so the gap would read
  9474. # as the duration -- 14 h for a night offline (DB-C9).
  9475. # An estimated end (#3310) gives the estimate.
  9476. if (
  9477. run_started
  9478. and run_completed
  9479. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9480. ):
  9481. elapsed = (run_completed - run_started).total_seconds()
  9482. if elapsed > 0:
  9483. actual_time_seconds = int(elapsed)
  9484. archive_data = {
  9485. "print_time_seconds": archive.print_time_seconds,
  9486. "actual_time_seconds": actual_time_seconds,
  9487. "actual_filament_grams": archive.filament_used_grams,
  9488. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9489. "created_by_id": archive.created_by_id,
  9490. }
  9491. # Scale filament usage for partial prints
  9492. if print_status != "completed" and archive.filament_used_grams:
  9493. progress = data.get("progress") or 0
  9494. scale = _partial_progress_scale(progress)
  9495. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9496. archive_data["progress"] = progress
  9497. # Pass per-slot data from archive.extra_data
  9498. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9499. slots = archive.extra_data["filament_slots"]
  9500. if print_status != "completed":
  9501. scale = _partial_progress_scale(data.get("progress"))
  9502. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9503. archive_data["filament_slots"] = slots
  9504. # Scope project-summed totals down to the plate that was
  9505. # actually printed — see _scope_notification_archive_data_to_plate
  9506. # for the why (#1785).
  9507. archive_data = _scope_notification_archive_data_to_plate(
  9508. archive_data,
  9509. archive.file_path,
  9510. notify_plate_id,
  9511. print_status,
  9512. data.get("progress"),
  9513. app_settings.base_dir,
  9514. )
  9515. # Enrich filament_grams from usage_results when archive has no 3MF data
  9516. if not archive_data.get("actual_filament_grams") and usage_results:
  9517. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9518. if total_from_usage > 0:
  9519. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9520. # Pass usage tracker results for AMS slot info in notifications
  9521. if usage_results:
  9522. archive_data["usage_results"] = usage_results
  9523. # Which archive and print it was (archive redesign).
  9524. archive_data["archive_id"] = archive_id
  9525. archive_data["run_id"] = completed_run_id
  9526. # Add finish photo URL and image bytes if available
  9527. if finish_photo_filename:
  9528. photo_url, photo_bytes = await _finish_photo_for_notification(
  9529. db, archive, archive_id, finish_photo_filename
  9530. )
  9531. if photo_url:
  9532. archive_data["finish_photo_url"] = photo_url
  9533. if photo_bytes:
  9534. archive_data["image_data"] = photo_bytes
  9535. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9536. await notification_service.on_print_complete(
  9537. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9538. )
  9539. else:
  9540. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9541. # Post-print outcome confirmation (#1898). Runs in this
  9542. # background task so the finish photo fetched above rides
  9543. # along with the prompt.
  9544. if print_status == "completed" and archive_id:
  9545. await _dispatch_outcome_confirmation_safely(
  9546. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9547. )
  9548. # Send user-specific email notification
  9549. if archive_data:
  9550. created_by_id = archive_data.get("created_by_id")
  9551. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9552. await _dispatch_user_print_email(
  9553. print_status,
  9554. created_by_id,
  9555. printer_name,
  9556. raw_filename,
  9557. db,
  9558. image_data=archive_data.get("image_data"),
  9559. finish_photo_url=archive_data.get("finish_photo_url"),
  9560. )
  9561. logger.info("[NOTIFY-BG] Completed")
  9562. except Exception as e:
  9563. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9564. async def _background_maintenance_check():
  9565. """Check for maintenance due in background."""
  9566. if print_status != "completed":
  9567. return
  9568. try:
  9569. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9570. async with async_session() as db:
  9571. from backend.app.models.printer import Printer
  9572. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9573. printer = result.scalar_one_or_none()
  9574. printer_name = printer.name if printer else f"Printer {printer_id}"
  9575. await ensure_default_types(db)
  9576. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9577. attention = [
  9578. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9579. ]
  9580. items_needing_attention = [
  9581. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9582. for item in attention
  9583. ]
  9584. if items_needing_attention:
  9585. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9586. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9587. # MQTT relay - publish maintenance alerts
  9588. for item in attention:
  9589. current_value, threshold, unit = maintenance_alert_values(item)
  9590. try:
  9591. await mqtt_relay.on_maintenance_alert(
  9592. printer_id=printer_id,
  9593. printer_name=printer_name,
  9594. maintenance_type=item.maintenance_type_name,
  9595. current_value=current_value,
  9596. threshold=threshold,
  9597. unit=unit,
  9598. )
  9599. except Exception:
  9600. pass # Don't fail if MQTT fails
  9601. else:
  9602. logger.info("[MAINT-BG] Completed (no items need attention)")
  9603. except Exception as e:
  9604. logger.warning("[MAINT-BG] Failed: %s", e)
  9605. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9606. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9607. # Notification task waits for photo capture to complete first (with timeout).
  9608. # When a timelapse was recording, photo sourcing polls the per-print
  9609. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9610. # carries the correct bed-up photo instead of falling through to the
  9611. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9612. #
  9613. # #2547: both budgets now have to cover a plate restore as well.
  9614. #
  9615. # Without timelapse, the wait is on the moment producer, which raises the
  9616. # plate before its grab — so this has to outlast that producer's own budget.
  9617. #
  9618. # With timelapse, the capture polls up to
  9619. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9620. # falls back to a live grab, which is the case that raises the plate. At the
  9621. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9622. # restore would have moved the plate for a photo nobody waited for.
  9623. photo_wait_timeout = (
  9624. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9625. if data.get("timelapse_was_active")
  9626. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9627. )
  9628. async def _photo_then_notify():
  9629. """Wait for photo capture, then send notification with photo URL."""
  9630. finish_photo = None
  9631. try:
  9632. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9633. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9634. except TimeoutError:
  9635. logger.warning(
  9636. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9637. photo_wait_timeout,
  9638. )
  9639. except Exception as e:
  9640. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9641. try:
  9642. await _background_notifications(finish_photo)
  9643. except Exception as e:
  9644. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9645. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9646. # Stitch external camera layer timelapse if session was active
  9647. print_status = data.get("status", "completed")
  9648. async def _background_layer_timelapse():
  9649. """Stitch layer timelapse and attach to archive."""
  9650. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9651. try:
  9652. if print_status == "completed":
  9653. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9654. # The run the frames belong to, read before the stitch: it can
  9655. # take long enough for the archive to start printing again.
  9656. run_started_at = None
  9657. if archive_id:
  9658. async with async_session() as db:
  9659. run_archive = await ArchiveService(db).get_archive(archive_id)
  9660. run_started_at = run_archive.started_at if run_archive else None
  9661. timelapse_path = await tl_complete(printer_id)
  9662. if timelapse_path and archive_id:
  9663. await _attach_layer_timelapse(
  9664. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9665. )
  9666. elif timelapse_path:
  9667. # Timelapse created but no archive - just clean up
  9668. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9669. else:
  9670. # Print failed or cancelled - cancel timelapse session
  9671. cancel_session(printer_id)
  9672. logger.info(
  9673. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9674. )
  9675. except Exception as e:
  9676. logger.warning("[LAYER-TL] Failed: %s", e)
  9677. # A completed print's session left _active_sessions when its stitch
  9678. # began: the one there now belongs to the next print, which may have
  9679. # started during the stitch, and must not lose its frames.
  9680. if print_status != "completed":
  9681. try:
  9682. cancel_session(printer_id)
  9683. except Exception:
  9684. pass # Best-effort timelapse session cancellation on error
  9685. from backend.app.services import archive_work
  9686. # Held through the stitch, which can take longer than a merge waits after
  9687. # a print (archive redesign P2).
  9688. layer_timelapse = _background_layer_timelapse()
  9689. if archive_id:
  9690. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9691. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9692. log_timing("All background tasks scheduled")
  9693. # Auto-scan for timelapse if recording was active during the print. A
  9694. # failed or cancelled print gets one too: the printer writes the video of
  9695. # the run so far when it stops (measured on an H2C, #3481), and that video
  9696. # is how the user sees what went wrong. A model that writes none costs one
  9697. # poll that finds nothing new.
  9698. if archive_id and data.get("timelapse_was_active"):
  9699. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9700. # Schedule timelapse scan as background task with retries
  9701. # The printer needs time to encode the video after print completion
  9702. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9703. log_timing("Timelapse scan scheduled")
  9704. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9705. # AMS sensor history recording
  9706. _ams_history_task: asyncio.Task | None = None
  9707. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9708. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9709. def _retention_days(stored: str | None, default: int) -> int:
  9710. """A history retention setting as days to keep: at least 1, the default
  9711. when unset or unreadable. A stored 0 or less (the API took one before it
  9712. had a minimum) would put the cutoff at now and delete all history."""
  9713. try:
  9714. return max(1, int(stored)) if stored is not None else default
  9715. except (TypeError, ValueError):
  9716. return default
  9717. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9718. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9719. _ams_alarm_cooldown: dict[str, datetime] = {}
  9720. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9721. # (printer_id, ams_id) already reported as sending the drop index and no
  9722. # percentage. Logged once each so a supported printer that turns out to do this
  9723. # shows up in a support bundle rather than as a user wondering where the
  9724. # humidity reading went -- see the note at the read site below (#3140).
  9725. _ams_index_only_logged: set[tuple[int, int]] = set()
  9726. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9727. """Temperature at which the AMS alarm fires, falling back to the display band.
  9728. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9729. when a notification was sent as well, which is why a room above it made the
  9730. alarm fire once an hour for as long as the weather lasted -- and the only way
  9731. to stop that was to raise the display band and lose the colour that says the
  9732. unit is warm (#2905).
  9733. Unset resolves to the fair threshold, so an install that never sets one is
  9734. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9735. so that arrives here as a string and is handled by the same branch as any
  9736. other unparseable value -- there is no separate sentinel to keep in sync.
  9737. A non-positive value is refused rather than honoured: zero would alarm
  9738. permanently, and it is far more likely to be a cleared field than a
  9739. deliberate choice.
  9740. """
  9741. if raw_alarm_value is None:
  9742. return fair_threshold
  9743. try:
  9744. value = float(raw_alarm_value)
  9745. except (TypeError, ValueError):
  9746. return fair_threshold
  9747. if not math.isfinite(value) or value <= 0:
  9748. return fair_threshold
  9749. return value
  9750. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9751. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9752. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9753. # partway through a cool-down would otherwise resume alarming about heat the
  9754. # user asked for — the same internal-timestamp-row pattern as
  9755. # support.py's debug_logging_enabled_at.
  9756. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9757. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9758. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9759. # matters when it never does.
  9760. AMS_DRYING_GRACE_MINUTES = 120
  9761. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9762. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9763. Anything older than the grace cap would expire on its next visit anyway, so
  9764. discarding it here costs nothing and stops rows for deleted printers from
  9765. accumulating.
  9766. Stamps ahead of now get two defences, because a box whose clock jumps
  9767. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9768. ones are discarded outright, and the rest are clamped to now. Without the
  9769. clamp the cap would measure from a moment that has not happened yet and hold
  9770. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9771. after a clock jump is a far better failure than an alarm silently disabled
  9772. for hours.
  9773. """
  9774. from backend.app.models.settings import Settings
  9775. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9776. setting = result.scalar_one_or_none()
  9777. if not setting or not setting.value:
  9778. return {}
  9779. try:
  9780. raw = json.loads(setting.value)
  9781. except (ValueError, TypeError):
  9782. return {} # Corrupted row → no latch, alarms behave as they did before
  9783. if not isinstance(raw, dict):
  9784. return {}
  9785. now = datetime.now(timezone.utc)
  9786. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9787. latch: dict[str, datetime] = {}
  9788. for key, value in raw.items():
  9789. try:
  9790. stamp = datetime.fromisoformat(str(value))
  9791. except (ValueError, TypeError):
  9792. continue
  9793. if stamp.tzinfo is None:
  9794. stamp = stamp.replace(tzinfo=timezone.utc)
  9795. if not (now - window <= stamp <= now + window):
  9796. continue
  9797. # Nothing may sit in the future: suppression is measured as now minus
  9798. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9799. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9800. latch[str(key)] = min(stamp, now)
  9801. return latch
  9802. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9803. """Persist the latch, writing only when it actually changed.
  9804. Adds the session change but does not commit — the caller's own commit
  9805. carries it, so the latch lands in the same transaction as the sensor rows
  9806. that produced it.
  9807. """
  9808. from backend.app.models.settings import Settings
  9809. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9810. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9811. setting = result.scalar_one_or_none()
  9812. if setting is None:
  9813. # Don't create the row on installs that never dry anything.
  9814. if payload != "{}":
  9815. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9816. elif setting.value != payload:
  9817. setting.value = payload
  9818. def _ams_has_filament(ams_data: dict) -> bool:
  9819. """True if this AMS unit has at least one tray slot holding filament.
  9820. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9821. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9822. still report sensor readings, but those readings are ambient and not
  9823. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9824. humidity/temperature alarms on this check so empty units don't generate
  9825. hourly noise. Sensor history still records regardless so the UI charts
  9826. stay continuous.
  9827. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9828. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9829. """
  9830. bits = ams_data.get("tray_exist_bits")
  9831. if isinstance(bits, str) and bits.strip():
  9832. try:
  9833. return int(bits, 16) > 0
  9834. except ValueError:
  9835. pass
  9836. trays = ams_data.get("tray")
  9837. if isinstance(trays, list):
  9838. return any(
  9839. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9840. )
  9841. return False
  9842. async def record_ams_history():
  9843. """Background task to record AMS humidity and temperature data."""
  9844. logger = logging.getLogger(__name__)
  9845. # Wait a short time for MQTT connections to establish on startup
  9846. await asyncio.sleep(10)
  9847. while True:
  9848. try:
  9849. from backend.app.models.ams_history import AMSSensorHistory
  9850. from backend.app.models.printer import Printer
  9851. from backend.app.models.settings import Settings
  9852. async with async_session() as db:
  9853. # Get all active printers
  9854. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9855. printers = result.scalars().all()
  9856. # Get alarm thresholds from settings
  9857. humidity_threshold = 60.0 # Default: fair threshold
  9858. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9859. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9860. setting = result.scalar_one_or_none()
  9861. if setting:
  9862. try:
  9863. humidity_threshold = float(setting.value)
  9864. except (ValueError, TypeError):
  9865. pass # Keep default threshold if stored value is invalid
  9866. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9867. setting = result.scalar_one_or_none()
  9868. if setting:
  9869. try:
  9870. temp_fair_threshold = float(setting.value)
  9871. except (ValueError, TypeError):
  9872. pass # Keep default threshold if stored value is invalid
  9873. # The alarm gets its own threshold, seeded from the resolved fair
  9874. # value so an install that has never set one behaves exactly as
  9875. # it did before (#2905). ams_temp_fair decides when the card turns
  9876. # amber; 35 C is a reasonable place to change a colour and not a
  9877. # reasonable place to page someone. A room above it makes the
  9878. # alarm fire once an hour for as long as the weather lasts, and
  9879. # the only way to stop it was to raise the display band and lose
  9880. # the colour that says the unit is warm.
  9881. #
  9882. # An unset value is stored as the literal "None", which the except
  9883. # below swallows the same way it swallows garbage -- so the
  9884. # fallback costs nothing and needs no sentinel of its own.
  9885. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9886. setting = result.scalar_one_or_none()
  9887. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9888. temp_fair_threshold, setting.value if setting else None
  9889. )
  9890. # Per-filament humidity threshold overrides (#1605) — resolved
  9891. # per-AMS below from the loaded tray types. Reuses the same
  9892. # resolver as the auto-drying scheduler so behavior stays in
  9893. # lockstep across both consumers.
  9894. from backend.app.services.print_scheduler import PrintScheduler
  9895. per_type_humidity_thresholds: dict[str, int] = {}
  9896. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9897. setting = result.scalar_one_or_none()
  9898. if setting and setting.value:
  9899. try:
  9900. raw = json.loads(setting.value)
  9901. if isinstance(raw, dict):
  9902. for k, v in raw.items():
  9903. try:
  9904. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9905. v
  9906. )
  9907. except (TypeError, ValueError):
  9908. continue
  9909. except (ValueError, TypeError):
  9910. pass # Invalid JSON → no overrides, fall through to global threshold
  9911. # Per-AMS drying latch (#1802), loaded once per pass and written
  9912. # back below only if a unit changed it.
  9913. drying_latch = await _load_ams_drying_latch(db)
  9914. drying_latch_before = dict(drying_latch)
  9915. recorded_count = 0
  9916. for printer in printers:
  9917. # Get current state from printer manager
  9918. state = printer_manager.get_status(printer.id)
  9919. if not state or not state.connected or not state.raw_data:
  9920. continue # Skip disconnected printers - don't use stale data
  9921. raw_data = state.raw_data
  9922. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9923. continue
  9924. # Record data for each AMS unit
  9925. for ams_data in raw_data["ams"]:
  9926. ams_id = int(ams_data.get("id", 0))
  9927. # Percentage only. The 1-5 index is inverted, so
  9928. # charting it as a percentage drew the wettest units as
  9929. # the driest (#3140); a unit that reports no percentage
  9930. # leaves a gap in the chart instead. See
  9931. # utils/ams_humidity.
  9932. humidity = ams_humidity_percent(ams_data)
  9933. # No supported printer is known to send the index
  9934. # alone -- the report came from unsupported firmware,
  9935. # and no install has been seen using the old fallback.
  9936. # "Known" is doing work there, so say so once per unit:
  9937. # the alternative is a silent blank card.
  9938. if humidity is None and ams_data.get("humidity") is not None:
  9939. unit_key = (printer.id, ams_id)
  9940. if unit_key not in _ams_index_only_logged:
  9941. _ams_index_only_logged.add(unit_key)
  9942. logger.info(
  9943. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9944. "percentage. The index is inverted and is not shown as a percentage "
  9945. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9946. "Please report this with the printer and AMS firmware versions.",
  9947. printer.name,
  9948. ams_id,
  9949. )
  9950. # Get temperature
  9951. temperature = None
  9952. temp_str = ams_data.get("temp")
  9953. if temp_str is not None:
  9954. try:
  9955. temperature = float(temp_str)
  9956. except (ValueError, TypeError):
  9957. pass # Skip unparseable temperature value
  9958. # Skip if no data
  9959. if humidity is None and temperature is None:
  9960. continue
  9961. # Record the data point
  9962. history = AMSSensorHistory(
  9963. printer_id=printer.id,
  9964. ams_id=ams_id,
  9965. humidity=humidity,
  9966. # Both columns hold the same reading now that the
  9967. # index can no longer reach ``humidity``. Writing it
  9968. # through the same value also stops a genuine 0%
  9969. # from being stored as NULL, which the old truthiness
  9970. # test did.
  9971. humidity_raw=humidity,
  9972. temperature=temperature,
  9973. )
  9974. db.add(history)
  9975. recorded_count += 1
  9976. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9977. ams_type = unit_ams_type(ams_id, ams_data.get("info"))
  9978. is_ams_ht = ams_type == AmsType.N3S
  9979. ams_label = unit_label(ams_id, ams_type)
  9980. # Skip alarm dispatch for empty AMS units — humidity /
  9981. # temperature readings are ambient with no filament to
  9982. # protect, and the hourly notification just becomes
  9983. # noise. Sensor history was already recorded above so
  9984. # the UI charts stay continuous (#1619). Per-AMS check
  9985. # so a multi-AMS setup with one loaded + one empty
  9986. # still alarms on the loaded unit.
  9987. if not _ams_has_filament(ams_data):
  9988. continue
  9989. # Resolve per-filament humidity threshold for this AMS
  9990. # unit (#1605). Falls back to the global ams_humidity_fair
  9991. # when no per-type overrides are configured.
  9992. trays = ams_data.get("tray", []) or []
  9993. effective_humidity_threshold = float(
  9994. PrintScheduler.resolve_humidity_threshold(
  9995. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9996. )
  9997. )
  9998. # Check humidity alarm (only if above threshold)
  9999. if humidity is not None and humidity > effective_humidity_threshold:
  10000. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  10001. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  10002. now = datetime.now(timezone.utc)
  10003. if (
  10004. last_alarm is None
  10005. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  10006. ):
  10007. _ams_alarm_cooldown[cooldown_key] = now
  10008. logger.info(
  10009. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  10010. )
  10011. try:
  10012. # Call different notification method based on AMS type
  10013. if is_ams_ht:
  10014. await notification_service.on_ams_ht_humidity_high(
  10015. printer.id,
  10016. printer.name,
  10017. ams_label,
  10018. humidity,
  10019. effective_humidity_threshold,
  10020. db,
  10021. )
  10022. else:
  10023. await notification_service.on_ams_humidity_high(
  10024. printer.id,
  10025. printer.name,
  10026. ams_label,
  10027. humidity,
  10028. effective_humidity_threshold,
  10029. db,
  10030. )
  10031. except Exception as e:
  10032. logger.warning("Failed to send humidity alarm: %s", e)
  10033. # A drying cycle heats the unit far past ams_temp_fair on
  10034. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  10035. # AMS-HT, against a 35 C default — so the alarm fired
  10036. # once an hour for the whole cycle and kept firing while
  10037. # the unit cooled back down (#1802). Latch on the
  10038. # firmware's own drying state and hold until the reading
  10039. # returns to normal. Humidity is deliberately left alone:
  10040. # it falls during drying, which is the whole point.
  10041. latch_key = f"{printer.id}:{ams_id}"
  10042. # The latch releases at `threshold`, so it takes the alarm
  10043. # number too. Handing it the display band would strand the
  10044. # latch on any unit that settles back above it -- a room
  10045. # where the AMS rests at 37.7 C never returns under a 35 C
  10046. # band, so the latch could only expire on the grace cap
  10047. # rather than releasing when the unit had actually cooled.
  10048. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  10049. drying_active=is_drying_active(ams_data),
  10050. temperature=temperature,
  10051. threshold=temp_alarm_threshold,
  10052. latched_at=drying_latch.get(latch_key),
  10053. now=datetime.now(timezone.utc),
  10054. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  10055. )
  10056. if new_latch is None:
  10057. drying_latch.pop(latch_key, None)
  10058. else:
  10059. drying_latch[latch_key] = new_latch
  10060. # Check temperature alarm (only if above threshold)
  10061. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  10062. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  10063. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  10064. now = datetime.now(timezone.utc)
  10065. if (
  10066. last_alarm is None
  10067. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  10068. ):
  10069. _ams_alarm_cooldown[cooldown_key] = now
  10070. logger.info(
  10071. f"Sending temperature alarm for {printer.name} {ams_label}: "
  10072. f"{temperature}°C > {temp_alarm_threshold}°C"
  10073. )
  10074. try:
  10075. # Call different notification method based on AMS type
  10076. if is_ams_ht:
  10077. # The reported threshold has to be the one
  10078. # that fired, or the message says "> 35 °C"
  10079. # while firing at 45.
  10080. await notification_service.on_ams_ht_temperature_high(
  10081. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  10082. )
  10083. else:
  10084. await notification_service.on_ams_temperature_high(
  10085. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  10086. )
  10087. except Exception as e:
  10088. logger.warning("Failed to send temperature alarm: %s", e)
  10089. if drying_latch != drying_latch_before:
  10090. await _save_ams_drying_latch(db, drying_latch)
  10091. await db.commit()
  10092. if recorded_count > 0:
  10093. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  10094. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  10095. global _ams_cleanup_counter
  10096. _ams_cleanup_counter += 1
  10097. if _ams_cleanup_counter >= 288:
  10098. _ams_cleanup_counter = 0
  10099. # Get retention days from settings
  10100. from backend.app.models.settings import Settings
  10101. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  10102. setting = result.scalar_one_or_none()
  10103. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  10104. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10105. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  10106. await db.commit()
  10107. if result.rowcount > 0:
  10108. logger.info(
  10109. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  10110. )
  10111. # Wait until next recording interval
  10112. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  10113. except asyncio.CancelledError:
  10114. break
  10115. except Exception as e:
  10116. logger.warning("AMS history recording failed: %s", e)
  10117. await asyncio.sleep(60) # Wait a bit before retrying
  10118. def start_ams_history_recording():
  10119. """Start the AMS history recording background task."""
  10120. global _ams_history_task
  10121. if _ams_history_task is None:
  10122. _ams_history_task = asyncio.create_task(record_ams_history())
  10123. logging.getLogger(__name__).info("AMS history recording started")
  10124. def stop_ams_history_recording():
  10125. """Stop the AMS history recording background task."""
  10126. global _ams_history_task
  10127. if _ams_history_task:
  10128. _ams_history_task.cancel()
  10129. _ams_history_task = None
  10130. logging.getLogger(__name__).info("AMS history recording stopped")
  10131. # Printer sensor history recording (nozzle / bed / chamber)
  10132. _printer_sensor_history_task: asyncio.Task | None = None
  10133. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  10134. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  10135. _printer_sensor_cleanup_counter = 0
  10136. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  10137. # MQTT parser writes, so we don't need to handle per-model field aliases here
  10138. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  10139. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  10140. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  10141. _SENSOR_TARGET_KEYS = {
  10142. "nozzle": "nozzle_target",
  10143. "nozzle_2": "nozzle_2_target",
  10144. "bed": "bed_target",
  10145. "chamber": "chamber_target",
  10146. }
  10147. async def record_printer_sensor_history():
  10148. """Background task to record nozzle / bed / chamber readings.
  10149. Pulls from `state.temperatures` (already normalised across all printer
  10150. models by the MQTT parser) rather than re-parsing raw_data, so we get
  10151. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  10152. """
  10153. logger = logging.getLogger(__name__)
  10154. await asyncio.sleep(10)
  10155. while True:
  10156. try:
  10157. from backend.app.models.printer import Printer
  10158. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  10159. from backend.app.models.settings import Settings
  10160. async with async_session() as db:
  10161. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  10162. printers = result.scalars().all()
  10163. recorded_count = 0
  10164. for printer in printers:
  10165. state = printer_manager.get_status(printer.id)
  10166. if not state or not state.connected:
  10167. continue
  10168. temps = getattr(state, "temperatures", None) or {}
  10169. if not isinstance(temps, dict):
  10170. continue
  10171. for kind in _SENSOR_KINDS:
  10172. if kind not in temps:
  10173. continue
  10174. try:
  10175. value = float(temps[kind])
  10176. except (ValueError, TypeError):
  10177. continue
  10178. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  10179. target_val: float | None = None
  10180. if target_raw is not None:
  10181. try:
  10182. target_val = float(target_raw)
  10183. except (ValueError, TypeError):
  10184. target_val = None
  10185. db.add(
  10186. PrinterSensorHistory(
  10187. printer_id=printer.id,
  10188. sensor_kind=kind,
  10189. value=value,
  10190. target=target_val,
  10191. )
  10192. )
  10193. recorded_count += 1
  10194. await db.commit()
  10195. if recorded_count > 0:
  10196. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  10197. # Periodic cleanup — once every ~24h at this interval.
  10198. global _printer_sensor_cleanup_counter
  10199. _printer_sensor_cleanup_counter += 1
  10200. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  10201. if _printer_sensor_cleanup_counter >= cleanup_every:
  10202. _printer_sensor_cleanup_counter = 0
  10203. result = await db.execute(
  10204. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  10205. )
  10206. setting = result.scalar_one_or_none()
  10207. retention_days = _retention_days(
  10208. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  10209. )
  10210. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10211. cleanup = await db.execute(
  10212. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  10213. )
  10214. await db.commit()
  10215. if cleanup.rowcount > 0:
  10216. logger.info(
  10217. "Cleaned up %s old printer sensor history entries (older than %s days)",
  10218. cleanup.rowcount,
  10219. retention_days,
  10220. )
  10221. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10222. except asyncio.CancelledError:
  10223. break
  10224. except Exception as e:
  10225. logger.warning("Printer sensor history recording failed: %s", e)
  10226. await asyncio.sleep(60)
  10227. def start_printer_sensor_history_recording():
  10228. global _printer_sensor_history_task
  10229. if _printer_sensor_history_task is None:
  10230. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10231. logging.getLogger(__name__).info("Printer sensor history recording started")
  10232. def stop_printer_sensor_history_recording():
  10233. global _printer_sensor_history_task
  10234. if _printer_sensor_history_task:
  10235. _printer_sensor_history_task.cancel()
  10236. _printer_sensor_history_task = None
  10237. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10238. # Printer runtime tracking
  10239. _runtime_tracking_task: asyncio.Task | None = None
  10240. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10241. # Printers the runtime tracker has seen connected since startup. One of them
  10242. # going offline clears its timestamp, so the time it was away is not counted
  10243. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10244. # connecting after a restart -- keeps it for a grace period: a print that ran
  10245. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10246. _runtime_seen_connected: set[int] = set()
  10247. # A printer never seen connected this long after the tracker started is
  10248. # offline, not still connecting: its stored timestamp predates a gap too.
  10249. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10250. async def track_printer_runtime():
  10251. """Background task to track printer active runtime (RUNNING state only).
  10252. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10253. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10254. which track mechanical wear. Pause time has no motion and no wear, so
  10255. counting it inflates maintenance warnings (#1521).
  10256. """
  10257. logger = logging.getLogger(__name__)
  10258. # Wait for MQTT connections to establish on startup
  10259. await asyncio.sleep(15)
  10260. started = time.monotonic()
  10261. while True:
  10262. try:
  10263. from backend.app.models.printer import Printer
  10264. # Fetch printer IDs in a short-lived read-only session
  10265. async with async_session() as db:
  10266. result = await db.execute(
  10267. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10268. Printer.is_active.is_(True)
  10269. )
  10270. )
  10271. printer_rows = result.all()
  10272. now = datetime.now(timezone.utc)
  10273. updated_count = 0
  10274. # Update each printer in its own short session to minimise write-lock
  10275. # hold time and avoid blocking critical commits like queue status
  10276. # updates (#897).
  10277. for pid, pname, runtime_secs, last_update in printer_rows:
  10278. state = printer_manager.get_status(pid)
  10279. if not state:
  10280. logger.debug("[%s] Runtime tracking: no state available", pname)
  10281. continue
  10282. if not state.connected:
  10283. logger.debug("[%s] Runtime tracking: not connected", pname)
  10284. offline = pid in _runtime_seen_connected or (
  10285. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10286. )
  10287. if offline and last_update is not None:
  10288. try:
  10289. async with async_session() as db:
  10290. printer = await db.get(Printer, pid)
  10291. if printer:
  10292. printer.last_runtime_update = None
  10293. await db.commit()
  10294. except Exception as e:
  10295. # Still marked: the next offline tick tries again.
  10296. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10297. continue
  10298. _runtime_seen_connected.discard(pid)
  10299. continue
  10300. _runtime_seen_connected.add(pid)
  10301. needs_commit = False
  10302. new_runtime = runtime_secs
  10303. new_last_update = last_update
  10304. if state.state == "RUNNING":
  10305. if last_update:
  10306. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10307. elapsed = (now - lu).total_seconds()
  10308. if elapsed > 0:
  10309. new_runtime = runtime_secs + int(elapsed)
  10310. updated_count += 1
  10311. needs_commit = True
  10312. logger.debug(
  10313. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10314. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10315. )
  10316. else:
  10317. needs_commit = True
  10318. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10319. new_last_update = now
  10320. else:
  10321. if last_update is not None:
  10322. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10323. new_last_update = None
  10324. needs_commit = True
  10325. if needs_commit:
  10326. try:
  10327. async with async_session() as db:
  10328. result = await db.execute(select(Printer).where(Printer.id == pid))
  10329. printer = result.scalar_one_or_none()
  10330. if printer:
  10331. printer.runtime_seconds = new_runtime
  10332. printer.last_runtime_update = new_last_update
  10333. await db.commit()
  10334. except Exception as e:
  10335. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10336. if updated_count > 0:
  10337. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10338. except asyncio.CancelledError:
  10339. logger.info("Runtime tracking cancelled")
  10340. break
  10341. except Exception as e:
  10342. logger.warning("Runtime tracking failed: %s", e)
  10343. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10344. def start_runtime_tracking():
  10345. """Start the printer runtime tracking background task."""
  10346. global _runtime_tracking_task
  10347. if _runtime_tracking_task is None:
  10348. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10349. logging.getLogger(__name__).info("Printer runtime tracking started")
  10350. def stop_runtime_tracking():
  10351. """Stop the printer runtime tracking background task."""
  10352. global _runtime_tracking_task
  10353. if _runtime_tracking_task:
  10354. _runtime_tracking_task.cancel()
  10355. _runtime_tracking_task = None
  10356. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10357. # SpoolBuddy device watchdog
  10358. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10359. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10360. async def _spoolbuddy_watchdog_loop():
  10361. """Periodic check for SpoolBuddy devices that have gone offline."""
  10362. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10363. while True:
  10364. try:
  10365. await spoolbuddy_watchdog()
  10366. except asyncio.CancelledError:
  10367. break
  10368. except Exception as e:
  10369. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10370. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10371. def start_spoolbuddy_watchdog():
  10372. global _spoolbuddy_watchdog_task
  10373. if _spoolbuddy_watchdog_task is None:
  10374. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10375. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10376. def stop_spoolbuddy_watchdog():
  10377. global _spoolbuddy_watchdog_task
  10378. if _spoolbuddy_watchdog_task:
  10379. _spoolbuddy_watchdog_task.cancel()
  10380. _spoolbuddy_watchdog_task = None
  10381. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10382. # Dead-MQTT-session recovery
  10383. #
  10384. # check_staleness() covers the "connected but silent" half-broken session. It
  10385. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10386. # is the only thing left watching at that point. When paho stops making
  10387. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10388. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10389. # offline with the UI open the whole time, recovered only when something
  10390. # happened to nudge it.
  10391. #
  10392. # This loop is that backstop. It only touches printers that had a working
  10393. # session and lost it, and only when the MQTT port still answers — a printer
  10394. # that is simply switched off is left to paho, since rebuilding a client
  10395. # against an unreachable host achieves nothing and would fill the log every
  10396. # night.
  10397. _connection_watchdog_task: asyncio.Task | None = None
  10398. CONNECTION_WATCHDOG_INTERVAL = 60
  10399. # How long a printer must have been silent before we stop trusting paho.
  10400. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10401. # so a session that is recovering on its own is never interrupted.
  10402. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10403. # Per-printer floor between rebuild attempts.
  10404. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10405. _connection_watchdog_last_attempt: dict[int, float] = {}
  10406. async def _recover_dead_printer_sessions() -> int:
  10407. """Rebuild MQTT clients that have been offline too long to still be trying.
  10408. Returns the number of printers a rebuild was attempted for (for tests and
  10409. for the caller's logging). Never raises: one unreachable printer must not
  10410. stop the sweep for the rest of the farm.
  10411. """
  10412. logger = logging.getLogger(__name__)
  10413. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10414. now = time.monotonic()
  10415. recovered = 0
  10416. for printer_id, client in list(printer_manager._clients.items()):
  10417. try:
  10418. if client.state.connected:
  10419. _connection_watchdog_last_attempt.pop(printer_id, None)
  10420. continue
  10421. # Time since the last inbound message is the age of the last known
  10422. # good session — no extra bookkeeping needed, and it is the same
  10423. # clock is_stale() reads. 0 means this client has never had one:
  10424. # that is the initial-connect path, where paho retrying is the
  10425. # correct and only behaviour, so leave it be.
  10426. last_msg = client._last_message_time
  10427. if not last_msg:
  10428. continue
  10429. offline_for = time.time() - last_msg
  10430. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10431. continue
  10432. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10433. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10434. continue
  10435. if not await check_port(client.ip_address, PORT_MQTT):
  10436. # Switched off, unplugged, or off the network. Paho's retry is
  10437. # the right handler; say so at debug level and move on.
  10438. logger.debug(
  10439. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10440. "— leaving the reconnect to paho",
  10441. printer_id,
  10442. offline_for,
  10443. )
  10444. _connection_watchdog_last_attempt[printer_id] = now
  10445. continue
  10446. _connection_watchdog_last_attempt[printer_id] = now
  10447. recovered += 1
  10448. logger.warning(
  10449. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10450. "rebuilding the client with a fresh session (last connect error: %s)",
  10451. printer_id,
  10452. offline_for,
  10453. PORT_MQTT,
  10454. client.last_connect_error or "none recorded",
  10455. )
  10456. # Async context, so this takes the hard-reset path: fresh client_id,
  10457. # paho's QoS 1 queue dropped. That matters — a project_file left
  10458. # unacked on the dead session would otherwise replay into the new
  10459. # one and trip 0500_4003 on the printer (#1136).
  10460. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10461. except Exception as e:
  10462. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10463. return recovered
  10464. async def _connection_watchdog_loop():
  10465. logger = logging.getLogger(__name__)
  10466. # Let the initial connects settle before judging anyone offline.
  10467. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10468. while True:
  10469. try:
  10470. await _recover_dead_printer_sessions()
  10471. except asyncio.CancelledError:
  10472. break
  10473. except Exception as e:
  10474. logger.warning("Connection watchdog sweep failed: %s", e)
  10475. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10476. def start_connection_watchdog():
  10477. global _connection_watchdog_task
  10478. if _connection_watchdog_task is None:
  10479. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10480. logging.getLogger(__name__).info("Printer connection watchdog started")
  10481. def stop_connection_watchdog():
  10482. global _connection_watchdog_task
  10483. if _connection_watchdog_task:
  10484. _connection_watchdog_task.cancel()
  10485. _connection_watchdog_task = None
  10486. _connection_watchdog_last_attempt.clear()
  10487. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10488. # Camera stream orphan cleanup
  10489. _camera_cleanup_task: asyncio.Task | None = None
  10490. CAMERA_CLEANUP_INTERVAL = 60
  10491. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10492. # kept frames of a failed stitch go after a day, not at the next restart.
  10493. TIMELAPSE_CLEANUP_EVERY = 60
  10494. async def _camera_cleanup_loop():
  10495. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10496. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10497. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10498. rounds = 0
  10499. while True:
  10500. try:
  10501. rounds += 1
  10502. await cleanup_orphaned_streams()
  10503. except asyncio.CancelledError:
  10504. break
  10505. except Exception as e:
  10506. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10507. try:
  10508. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10509. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10510. except asyncio.CancelledError:
  10511. break
  10512. except Exception as e:
  10513. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10514. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10515. def start_camera_cleanup():
  10516. global _camera_cleanup_task
  10517. if _camera_cleanup_task is None:
  10518. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10519. logging.getLogger(__name__).info("Camera stream cleanup started")
  10520. def stop_camera_cleanup():
  10521. global _camera_cleanup_task
  10522. if _camera_cleanup_task:
  10523. _camera_cleanup_task.cancel()
  10524. _camera_cleanup_task = None
  10525. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10526. # ---------------------------------------------------------------------------
  10527. # Expected-print TTL eviction
  10528. # ---------------------------------------------------------------------------
  10529. def _evict_stale_expected_prints() -> None:
  10530. """Remove entries from _expected_prints / _expected_print_creators that are
  10531. older than _EXPECTED_PRINT_TTL_SECONDS.
  10532. This prevents unbounded growth when a print is registered (via
  10533. register_expected_print) but on_print_start never fires — e.g. because the
  10534. printer disconnects, the app restarts, or the print is started directly from
  10535. the printer panel without going through the queue.
  10536. """
  10537. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10538. # (e.g. NTP sync, DST changes).
  10539. # A print that ended without its archive being found at completion leaves
  10540. # its id here; only running prints are owned.
  10541. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10542. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10543. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10544. if not stale_keys:
  10545. return
  10546. evicted: set[tuple[int, int]] = set()
  10547. for key in stale_keys:
  10548. archive_id = _expected_prints.pop(key, None)
  10549. if archive_id is not None:
  10550. evicted.add((key[0], archive_id))
  10551. _expected_print_creators.pop(key, None)
  10552. _expected_print_registered_at.pop(key, None)
  10553. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10554. # that have no remaining live keys in _expected_prints (all variants
  10555. # were just evicted) and are not printing right now. Print start pops
  10556. # only the names the printer reported, so the "<base>.gcode" variant
  10557. # outlives it; without the printing check its eviction two hours after
  10558. # dispatch threw away a running print's plate, AMS mapping and cost
  10559. # centre, which completion still reads (#3275).
  10560. for printer_id, archive_id in evicted:
  10561. if not _expected_or_printing_here(printer_id, archive_id):
  10562. _drop_dispatch(printer_id, archive_id)
  10563. logging.getLogger(__name__).info(
  10564. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10565. )
  10566. async def _expected_prints_cleanup_loop() -> None:
  10567. """Background task: periodically evict stale expected-print entries."""
  10568. while True:
  10569. try:
  10570. _evict_stale_expected_prints()
  10571. except asyncio.CancelledError:
  10572. raise
  10573. except Exception as e:
  10574. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10575. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10576. def start_expected_prints_cleanup() -> None:
  10577. global _expected_prints_cleanup_task
  10578. if _expected_prints_cleanup_task is None:
  10579. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10580. logging.getLogger(__name__).info("Expected prints cleanup started")
  10581. def stop_expected_prints_cleanup() -> None:
  10582. global _expected_prints_cleanup_task
  10583. if _expected_prints_cleanup_task:
  10584. _expected_prints_cleanup_task.cancel()
  10585. _expected_prints_cleanup_task = None
  10586. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10587. # ---------------------------------------------------------------------------
  10588. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10589. # ---------------------------------------------------------------------------
  10590. _auth_cleanup_task: asyncio.Task | None = None
  10591. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10592. async def _run_auth_cleanup() -> None:
  10593. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10594. from backend.app.core.database import async_session
  10595. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10596. from backend.app.models.user_totp import UserTOTP
  10597. now = datetime.now(timezone.utc)
  10598. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10599. try:
  10600. async with async_session() as db:
  10601. stale_cutoff = now - timedelta(hours=1)
  10602. result = await db.execute(
  10603. select(UserTOTP).where(
  10604. UserTOTP.is_enabled.is_(False),
  10605. UserTOTP.created_at < stale_cutoff,
  10606. )
  10607. )
  10608. stale_records = result.scalars().all()
  10609. if stale_records:
  10610. for rec in stale_records:
  10611. await db.delete(rec)
  10612. await db.commit()
  10613. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10614. except Exception as e:
  10615. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10616. # Remove expired revoked-JTI entries (they are no longer needed once the
  10617. # original token's exp has passed — the token would be rejected by JWT
  10618. # signature verification regardless).
  10619. try:
  10620. async with async_session() as db:
  10621. await db.execute(
  10622. delete(AuthEphemeralToken).where(
  10623. AuthEphemeralToken.token_type == "revoked_jti",
  10624. AuthEphemeralToken.expires_at < now,
  10625. )
  10626. )
  10627. await db.commit()
  10628. except Exception as e:
  10629. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10630. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10631. # Events outside this window can never affect rate-limit decisions — they only
  10632. # consume DB space. Use the same window constant as the rate limiter so the
  10633. # two are always in sync.
  10634. try:
  10635. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10636. async with async_session() as db:
  10637. await db.execute(
  10638. delete(AuthRateLimitEvent).where(
  10639. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10640. )
  10641. )
  10642. await db.commit()
  10643. except Exception as e:
  10644. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10645. async def _auth_cleanup_loop() -> None:
  10646. """Periodic background task: run auth cleanup every hour."""
  10647. while True:
  10648. try:
  10649. await _run_auth_cleanup()
  10650. except asyncio.CancelledError:
  10651. break
  10652. except Exception as e:
  10653. logging.warning("Auth cleanup loop error: %s", e)
  10654. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10655. def start_auth_cleanup() -> None:
  10656. global _auth_cleanup_task
  10657. if _auth_cleanup_task is None:
  10658. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10659. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10660. def stop_auth_cleanup() -> None:
  10661. global _auth_cleanup_task
  10662. if _auth_cleanup_task:
  10663. _auth_cleanup_task.cancel()
  10664. _auth_cleanup_task = None
  10665. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10666. async def initialize_wled_printers(db: AsyncSession) -> None:
  10667. """Seed WLED settings and apply offline presets before MQTT connections start."""
  10668. from backend.app.api.routes.settings import get_setting, setting_is_true
  10669. from backend.app.models.printer import Printer
  10670. wled_manager.require_plate_clear = setting_is_true(await get_setting(db, "require_plate_clear"))
  10671. result = await db.execute(select(Printer.id, Printer.wled_config, Printer.is_active))
  10672. for printer_id, config, is_active in result.all():
  10673. wled_manager.configure_printer(printer_id, config)
  10674. if not is_active and config:
  10675. wled_manager.handle_offline(printer_id)
  10676. @asynccontextmanager
  10677. async def lifespan(app: FastAPI):
  10678. # Startup
  10679. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10680. # anything else can spawn tasks that might trip it.
  10681. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10682. install_proactor_reset_filter()
  10683. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10684. # what turned descriptor exhaustion into a corrupted database (#2883).
  10685. from backend.app.core.fd_limit import raise_open_file_limit
  10686. raise_open_file_limit()
  10687. # Before init_db, so the warning is near the top of the log rather than
  10688. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10689. warn_if_running_on_uvloop()
  10690. await init_db()
  10691. # Browser download tokens expire after five minutes. Remove abandoned
  10692. # prepared ZIPs at startup as well as before each new preparation so a
  10693. # quiet appliance cannot retain an unusable bundle indefinitely.
  10694. try:
  10695. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10696. await prune_stale_printer_file_bundles()
  10697. except Exception as exc:
  10698. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10699. # After migrations, so the is_env_managed column exists. Never raises --
  10700. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10701. # startup (see apply_env_oidc_provider).
  10702. from backend.app.core.oidc_env import apply_env_oidc_provider
  10703. async with async_session() as oidc_db:
  10704. await apply_env_oidc_provider(oidc_db)
  10705. # Close out batches that finished before `completed` was a reachable status
  10706. # (#342). Without this the Batches tab opens on every batch created since
  10707. # the feature shipped, all still marked active. Never blocks startup.
  10708. try:
  10709. from backend.app.services.print_batch import backfill_batch_statuses
  10710. async with async_session() as batch_db:
  10711. await backfill_batch_statuses(batch_db)
  10712. except Exception as exc:
  10713. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10714. # Each plate's estimate of archives made before they were kept (#3375),
  10715. # read from their 3MFs in the background: the readers use the whole
  10716. # file's figures until then.
  10717. global _plate_estimates_task
  10718. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10719. # Register an app-scoped httpx client for Bambu Cloud services so
  10720. # per-request BambuCloudService instances reuse the same connection pool
  10721. # (important for routes like /cloud/filament-info that chain many
  10722. # get_setting_detail calls). The shared client stores no region/token
  10723. # state, so the per-request ownership pattern that fixed the region-bleed
  10724. # bug is preserved.
  10725. import httpx as _httpx
  10726. from backend.app.services.bambu_cloud import set_shared_http_client
  10727. from backend.app.services.model_providers.makerworld.service import (
  10728. set_shared_http_client as set_shared_makerworld_http_client,
  10729. )
  10730. from backend.app.services.orca_cloud import (
  10731. set_shared_http_client as set_shared_orca_http_client,
  10732. )
  10733. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10734. set_shared_http_client(_shared_cloud_http_client)
  10735. # Reuse the same connection pool for MakerWorld — different host, same
  10736. # keep-alive pool saves a TLS handshake per request.
  10737. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10738. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10739. # each spun up (and never closed) its own client, leaking sockets.
  10740. set_shared_orca_http_client(_shared_cloud_http_client)
  10741. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10742. # This can happen when a print was cancelled mid-print on versions before this fix.
  10743. try:
  10744. async with async_session() as db:
  10745. from backend.app.models.print_queue import PrintQueueItem
  10746. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10747. aborted_items = result.scalars().all()
  10748. if aborted_items:
  10749. for item in aborted_items:
  10750. item.status = "cancelled"
  10751. await db.commit()
  10752. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10753. except Exception as e:
  10754. logging.warning("Failed to fix aborted queue items: %s", e)
  10755. # Restore debug logging state from previous session
  10756. await init_debug_logging()
  10757. # Set up printer manager callbacks
  10758. loop = asyncio.get_event_loop()
  10759. printer_manager.set_event_loop(loop)
  10760. printer_manager.set_status_change_callback(on_printer_status_change)
  10761. printer_manager.set_print_start_callback(on_print_start)
  10762. printer_manager.set_print_complete_callback(on_print_complete)
  10763. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10764. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10765. printer_manager.set_ams_change_callback(on_ams_change)
  10766. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10767. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10768. await printer_manager.load_awaiting_plate_clear_from_db()
  10769. # Before any printer connects, or its first report re-sends every fault
  10770. # still listed (#3486).
  10771. await _load_notified_hms_faults()
  10772. # WLED is entirely optional. Seed its in-memory per-printer configuration
  10773. # before MQTT connections begin emitting status callbacks.
  10774. async with async_session() as db:
  10775. await initialize_wled_printers(db)
  10776. # Layer change callback for external camera timelapse
  10777. async def on_layer_change(printer_id: int, layer_num: int):
  10778. """Capture timelapse frame on layer change + first layer notification."""
  10779. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10780. await tl_layer_change(printer_id, layer_num)
  10781. # #1867: bank a recent in-print frame so the finish-photo path has a
  10782. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10783. # #2547 added `on_print_progress` as a second driver — this one alone
  10784. # stops firing once the final layer begins.
  10785. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10786. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10787. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10788. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10789. # nozzle clean), so a bare layer_num check can fire minutes before the
  10790. # first real extrusion. We require gcode_state == RUNNING and
  10791. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10792. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10793. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10794. # edge fires later; _first_layer_notified stays clear until we actually send
  10795. # so a deferred re-evaluation can win. See issue #1837.
  10796. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10797. client = printer_manager.get_client(printer_id)
  10798. state = client.state if client else None
  10799. if not state or state.state != "RUNNING":
  10800. return
  10801. if state.mc_print_sub_stage not in (None, 0):
  10802. return
  10803. _first_layer_notified[printer_id] = True
  10804. try:
  10805. async with async_session() as db:
  10806. from backend.app.models.printer import Printer
  10807. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10808. printer = result.scalar_one_or_none()
  10809. if not printer:
  10810. return
  10811. printer_name = printer.name
  10812. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10813. total_layers = state.total_layers if state else 0
  10814. image_data = await _capture_snapshot_for_notification(
  10815. printer_id, printer, logging.getLogger(__name__)
  10816. )
  10817. await notification_service.on_first_layer_complete(
  10818. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10819. )
  10820. except Exception as e:
  10821. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10822. printer_manager.set_layer_change_callback(on_layer_change)
  10823. async def on_print_progress(printer_id: int, percent: int):
  10824. """#2547: keep the in-print frame bank fresh through the final layer.
  10825. `on_layer_change` stops the moment the last layer starts, which on the
  10826. H2C capture that closed #2547 left the bank stale for the three minutes
  10827. that layer took. Progress is the only field that keeps advancing there,
  10828. and it freezes before the End G-code runs — so banking on it stays
  10829. inside the print and never sees a swapped plate.
  10830. """
  10831. client = printer_manager.get_client(printer_id)
  10832. state = client.state if client else None
  10833. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10834. printer_manager.set_print_progress_callback(on_print_progress)
  10835. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10836. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10837. waiter = _bed_cool_waiters.get(printer_id)
  10838. if not waiter:
  10839. return
  10840. threshold = waiter["threshold"]
  10841. if bed_temp > threshold:
  10842. return
  10843. # Bed is at or below threshold — fire notification and remove waiter
  10844. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10845. if not waiter_info:
  10846. return # Another callback already handled it
  10847. bed_cool_logger = logging.getLogger(__name__)
  10848. bed_cool_logger.info(
  10849. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10850. bed_temp,
  10851. printer_id,
  10852. threshold,
  10853. )
  10854. try:
  10855. printer_info = printer_manager.get_printer(printer_id)
  10856. p_name = printer_info.name if printer_info else "Unknown"
  10857. async with async_session() as db:
  10858. await notification_service.on_bed_cooled(
  10859. printer_id=printer_id,
  10860. printer_name=p_name,
  10861. bed_temp=bed_temp,
  10862. threshold=threshold,
  10863. filename=waiter_info["filename"],
  10864. db=db,
  10865. )
  10866. except Exception as e:
  10867. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10868. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10869. async def on_drying_complete(printer_id: int, ams_id: int):
  10870. """Smart-plug auto-off-after-drying trigger (#1349).
  10871. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10872. manager walks all plugs linked to this printer and turns off only
  10873. the ones with ``auto_off_after_drying`` enabled, after their
  10874. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10875. dual-AMS dry that ends within the same MQTT push) call this once
  10876. per unit — the manager's ``_cancel_pending_off`` collapses
  10877. repeated scheduling on the same plug to one timer, so duplicate
  10878. fires are safe.
  10879. """
  10880. try:
  10881. async with async_session() as db:
  10882. await smart_plug_manager.on_drying_complete(printer_id, db)
  10883. except Exception as e:
  10884. logging.getLogger(__name__).warning(
  10885. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10886. printer_id,
  10887. ams_id,
  10888. e,
  10889. )
  10890. printer_manager.set_drying_complete_callback(on_drying_complete)
  10891. async def on_drying_cycle_end(printer_id: int, cycle):
  10892. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10893. from backend.app.services.spool_drying import record_drying_cycle
  10894. try:
  10895. async with async_session() as db:
  10896. await record_drying_cycle(db, printer_id, cycle)
  10897. except Exception as e:
  10898. logging.getLogger(__name__).warning(
  10899. "Failed to record drying for printer %d (AMS %d): %s",
  10900. printer_id,
  10901. cycle.ams_id,
  10902. e,
  10903. )
  10904. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10905. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10906. """Surface the read-back result of a spool assignment to the UI (#2582).
  10907. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10908. echoed back the filament id we pushed. We relay that as a websocket
  10909. event so the frontend can toast "loaded" / "assignment didn't take"
  10910. instead of the historic silent fire-and-forget, which made the
  10911. AMS→Studio hand-off feel random to users.
  10912. """
  10913. try:
  10914. from backend.app.services.spool_assignment_notifications import (
  10915. _slot_label_from_global_tray,
  10916. )
  10917. layout = printer_tray_layout(printer_id, printer_manager)
  10918. global_id = layout.tray_from_slot_key(ams_id, tray_id)
  10919. slot_label = _slot_label_from_global_tray(global_id, layout)
  10920. printer_info = printer_manager.get_printer(printer_id)
  10921. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10922. await ws_manager.broadcast(
  10923. {
  10924. "type": "spool_assignment_verified",
  10925. "printer_id": printer_id,
  10926. "printer_name": printer_name,
  10927. "ams_id": ams_id,
  10928. "tray_id": tray_id,
  10929. "slot": slot_label,
  10930. "verified": verified,
  10931. # Present on success: False means the filament setting landed
  10932. # but the K-profile (cali_idx) did not — the reporter's exact
  10933. # "loaded but no flow profile" symptom.
  10934. "kprofile_applied": detail.get("kprofile_applied", True),
  10935. }
  10936. )
  10937. except Exception as e:
  10938. logging.getLogger(__name__).warning(
  10939. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10940. printer_id,
  10941. ams_id,
  10942. tray_id,
  10943. e,
  10944. )
  10945. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10946. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10947. """Persist a mid-print tray change for completion-time attribution.
  10948. AMS filament backup switches trays without telling the slicer, so the
  10949. tray-change log is the only record of which spool fed which layers.
  10950. Keeping it only in memory meant a restart mid-print charged everything
  10951. to the tray that finished the job.
  10952. """
  10953. try:
  10954. from backend.app.services.usage_tracker import record_tray_change
  10955. async with async_session() as db:
  10956. await record_tray_change(db, printer_id, tray_global, layer_num)
  10957. except Exception as e:
  10958. logging.getLogger(__name__).warning(
  10959. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10960. printer_id,
  10961. tray_global,
  10962. layer_num,
  10963. e,
  10964. )
  10965. printer_manager.set_tray_change_callback(on_tray_change)
  10966. # Initialize MQTT relay from settings
  10967. async with async_session() as db:
  10968. from backend.app.api.routes.settings import get_setting
  10969. mqtt_settings = {
  10970. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10971. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10972. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10973. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10974. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10975. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10976. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10977. }
  10978. await mqtt_relay.configure(mqtt_settings)
  10979. # Restore MQTT smart plug subscriptions
  10980. if mqtt_settings.get("mqtt_enabled"):
  10981. from backend.app.models.smart_plug import SmartPlug
  10982. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10983. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10984. mqtt_plugs = result.scalars().all()
  10985. restored = 0
  10986. for plug in mqtt_plugs:
  10987. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10988. restored += 1
  10989. if restored:
  10990. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10991. # Connect to all active printers
  10992. async with async_session() as db:
  10993. await init_printer_connections(db)
  10994. # Auto-connect to Spoolman if enabled
  10995. async with async_session() as db:
  10996. from backend.app.api.routes.settings import get_setting
  10997. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10998. spoolman_url = await get_setting(db, "spoolman_url")
  10999. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  11000. try:
  11001. client = await init_spoolman_client(spoolman_url)
  11002. if await client.health_check():
  11003. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  11004. # Ensure the 'tag' extra field exists for RFID/UUID storage
  11005. field_ok = await client.ensure_tag_extra_field()
  11006. if not field_ok:
  11007. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  11008. # Register the BambuStudio slicer-preset fields used by the
  11009. # spool-edit / assign flow. Spoolman rejects PATCHes with
  11010. # unknown extra keys, so these must exist before any update
  11011. # that touches them.
  11012. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  11013. if not await client.ensure_extra_field(field_name):
  11014. logging.warning(
  11015. "Spoolman extra field %r registration failed — "
  11016. "spool slicer-preset edits will return 502",
  11017. field_name,
  11018. )
  11019. else:
  11020. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  11021. except Exception as e:
  11022. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  11023. # Start the print scheduler
  11024. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  11025. # Start the smart plug scheduler for time-based on/off
  11026. smart_plug_manager.start_scheduler()
  11027. # Start the Home Assistant sensor poller (#1148)
  11028. ha_sensor_manager.start()
  11029. location_ha_sensor_manager.start()
  11030. # Resume any pending auto-offs that were interrupted by restart
  11031. await smart_plug_manager.resume_pending_auto_offs()
  11032. # Start the notification digest scheduler
  11033. notification_service.start_digest_scheduler()
  11034. notify_live_activities.start()
  11035. notify_widgets.start()
  11036. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  11037. # provider in reactions/both mode; the notification routes resync them.
  11038. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  11039. # until the next provider save, not the whole startup.
  11040. try:
  11041. await telegram_reaction_poller.start()
  11042. except Exception as e:
  11043. logging.warning("Telegram reaction poller did not start: %s", e)
  11044. # Start the GitHub backup scheduler
  11045. await github_backup_service.start_scheduler()
  11046. # Start the local backup scheduler
  11047. await local_backup_service.start_scheduler()
  11048. await obico_detection_service.start()
  11049. await octoeverywhere_detection_service.start()
  11050. # Start the library trash sweeper (#1008)
  11051. await library_trash_service.start_scheduler()
  11052. # Start the archive auto-purge sweeper (#1008 follow-up)
  11053. await archive_purge_service.start_scheduler()
  11054. # Start AMS history recording
  11055. start_ams_history_recording()
  11056. # Start printer sensor (nozzle / bed / chamber) history recording
  11057. start_printer_sensor_history_recording()
  11058. # Start printer runtime tracking
  11059. start_runtime_tracking()
  11060. # Start SpoolBuddy device watchdog
  11061. start_spoolbuddy_watchdog()
  11062. # Start camera stream orphan cleanup
  11063. start_camera_cleanup()
  11064. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  11065. start_connection_watchdog()
  11066. # One-shot sweep for timelapse session directories orphaned by a crash
  11067. # or restart that happened mid-print (in-memory session tracking can't
  11068. # survive that, and nothing else reaps the leftover frames/output file)
  11069. try:
  11070. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  11071. removed = cleanup_orphaned_timelapse_sessions()
  11072. if removed:
  11073. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  11074. except Exception as e:
  11075. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  11076. # Start expected-print TTL eviction (prevents memory leak when prints are
  11077. # registered but on_print_start never fires)
  11078. start_expected_prints_cleanup()
  11079. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  11080. start_auth_cleanup()
  11081. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  11082. from backend.app.services import announcements as announcements_service
  11083. announcements_service.start()
  11084. from backend.app.services.printer_media import start_printer_download_cleanup
  11085. start_printer_download_cleanup()
  11086. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  11087. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  11088. from backend.app.services.loop_watchdog import start_loop_watchdog
  11089. start_loop_watchdog()
  11090. # Initialize virtual printer manager and sync from DB
  11091. from backend.app.services.virtual_printer import virtual_printer_manager
  11092. virtual_printer_manager.set_session_factory(async_session)
  11093. virtual_printer_manager.set_printer_manager(printer_manager)
  11094. try:
  11095. await virtual_printer_manager.sync_from_db()
  11096. logging.info("Virtual printer manager synced from database")
  11097. except Exception as e:
  11098. logging.warning("Failed to sync virtual printers: %s", e)
  11099. yield
  11100. # Shutdown
  11101. print_scheduler.stop()
  11102. smart_plug_manager.stop_scheduler()
  11103. ha_sensor_manager.stop()
  11104. location_ha_sensor_manager.stop()
  11105. notification_service.stop_digest_scheduler()
  11106. await notify_live_activities.close()
  11107. await notify_widgets.close()
  11108. await telegram_reaction_poller.aclose()
  11109. github_backup_service.stop_scheduler()
  11110. local_backup_service.stop_scheduler()
  11111. library_trash_service.stop_scheduler()
  11112. archive_purge_service.stop_scheduler()
  11113. obico_detection_service.stop()
  11114. octoeverywhere_detection_service.stop()
  11115. stop_ams_history_recording()
  11116. stop_printer_sensor_history_recording()
  11117. stop_runtime_tracking()
  11118. stop_spoolbuddy_watchdog()
  11119. stop_camera_cleanup()
  11120. stop_connection_watchdog()
  11121. from backend.app.services.loop_watchdog import stop_loop_watchdog
  11122. stop_loop_watchdog()
  11123. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  11124. # cleanly rather than waiting on a queue that nothing will ever fill.
  11125. try:
  11126. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  11127. await shutdown_all_broadcasters()
  11128. except Exception as e:
  11129. logging.warning("Failed to shut down camera broadcasters: %s", e)
  11130. stop_expected_prints_cleanup()
  11131. stop_auth_cleanup()
  11132. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  11133. _plate_estimates_task.cancel()
  11134. from backend.app.services import announcements as announcements_service
  11135. announcements_service.stop()
  11136. from backend.app.services.printer_media import stop_printer_download_cleanup
  11137. await stop_printer_download_cleanup()
  11138. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  11139. from backend.app.services import timelapse_jobs
  11140. await timelapse_jobs.cancel_all()
  11141. printer_manager.disconnect_all()
  11142. slot_unlink_grace.reset()
  11143. await close_spoolman_client()
  11144. # Stop all virtual printer services
  11145. await virtual_printer_manager.stop_all()
  11146. await mqtt_smart_plug_service.disconnect(timeout=2)
  11147. await mqtt_relay.disconnect(timeout=2)
  11148. await wled_manager.shutdown()
  11149. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  11150. set_shared_http_client(None)
  11151. set_shared_makerworld_http_client(None)
  11152. set_shared_orca_http_client(None)
  11153. await _shared_cloud_http_client.aclose()
  11154. # Checkpoint WAL (SQLite only) and close all database connections
  11155. from backend.app.core.db_dialect import is_sqlite
  11156. if is_sqlite():
  11157. try:
  11158. async with engine.begin() as conn:
  11159. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  11160. logging.info("WAL checkpoint completed")
  11161. except Exception as e:
  11162. logging.warning("WAL checkpoint failed: %s", e)
  11163. await engine.dispose()
  11164. app = FastAPI(
  11165. title=app_settings.app_name,
  11166. description="Archive and manage Bambu Lab 3MF files",
  11167. version=APP_VERSION,
  11168. lifespan=lifespan,
  11169. )
  11170. # Added first so it sits innermost, next to the routes: a refused header's value
  11171. # (often a stored token) masked in every JSON body. See core.response_redaction.
  11172. app.add_middleware(RefusedHeaderResponseMask)
  11173. def _json_safe(value):
  11174. """The validation errors with every non-finite number written as text."""
  11175. if isinstance(value, float) and not math.isfinite(value):
  11176. return str(value)
  11177. if isinstance(value, dict):
  11178. return {key: _json_safe(item) for key, item in value.items()}
  11179. if isinstance(value, list | tuple):
  11180. return [_json_safe(item) for item in value]
  11181. return value
  11182. @app.exception_handler(RequestValidationError)
  11183. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  11184. """FastAPI's own 422, except that it survives a non-finite number.
  11185. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  11186. them), and the default handler echoes the input back in its errors,
  11187. which JSON cannot hold: the request ended in an error instead of a 422.
  11188. """
  11189. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  11190. # =============================================================================
  11191. # Authentication Middleware - Secures ALL API routes by default
  11192. # =============================================================================
  11193. # Public routes that don't require authentication even when auth is enabled
  11194. PUBLIC_API_ROUTES = {
  11195. # Auth routes needed before/during login
  11196. "/api/v1/auth/status",
  11197. "/api/v1/auth/login",
  11198. "/api/v1/auth/setup", # Needed for initial setup and recovery
  11199. # Advanced auth status needed for login page
  11200. "/api/v1/auth/advanced-auth/status",
  11201. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  11202. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  11203. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  11204. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  11205. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  11206. # OIDC routes that must be reachable without a JWT
  11207. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  11208. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  11209. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  11210. # Connected apps: the app's server swaps a code for the user's identity,
  11211. # authenticated by its client secret rather than a login token.
  11212. "/api/v1/connect/token",
  11213. # Version check for updates (no sensitive data)
  11214. "/api/v1/updates/version",
  11215. # Metrics endpoint handles its own prometheus_token authentication
  11216. "/api/v1/metrics",
  11217. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  11218. # this BEFORE a JWT is available to pick up the firstboot wizard's
  11219. # hostname / timezone / locale and the chrony NTP-gate state. The
  11220. # response contains user-set defaults and a public sync flag — no
  11221. # secrets. Without this entry the global auth middleware returns 401
  11222. # before the route handler runs, regardless of the route's own
  11223. # "no auth required" intent.
  11224. "/api/v1/system/appliance",
  11225. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  11226. # authenticates with a long-lived ``camwall``-scoped token in the query
  11227. # string — exactly like the camera streams two lists below, and for the same
  11228. # reason (no header to put a JWT in). "Public" here only means the middleware
  11229. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  11230. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  11231. # plain ``camera_stream`` token does NOT open this door.
  11232. "/api/v1/camwall/printers",
  11233. # Overlay branding: the route enforces overlay-scoped token authentication.
  11234. "/api/v1/overlay-branding/logo",
  11235. }
  11236. # Route prefixes that are public (for routes with dynamic segments)
  11237. PUBLIC_API_PREFIXES = [
  11238. # WebSocket connections handle their own auth
  11239. "/api/v1/ws",
  11240. # OIDC authorize redirects — include provider_id in path
  11241. "/api/v1/auth/oidc/authorize/",
  11242. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11243. # a phone with no session, so no header can carry a JWT — the single-use
  11244. # capability token in the path IS the credential (same reasoning as the
  11245. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11246. # good/reject on the one archive the token was minted for.
  11247. "/api/v1/archives/confirm/",
  11248. ]
  11249. # Route patterns that are public (read-only display data)
  11250. # These are checked with "in path" - needed because browsers load images/videos
  11251. # via <img src> and <video src> which don't include Authorization headers
  11252. PUBLIC_API_PATTERNS = [
  11253. # Thumbnails
  11254. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11255. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11256. # Images and media
  11257. "/photos/", # /archives/{id}/photos/{filename}
  11258. "/project-image/", # /archives/{id}/project-image/{path}
  11259. "/qrcode", # /archives/{id}/qrcode
  11260. "/timelapse", # /archives/{id}/timelapse (video)
  11261. "/cover", # /printers/{id}/cover
  11262. "/icon", # /external-links/{id}/icon
  11263. # Camera (streams loaded via <img> tag)
  11264. "/camera/stream", # /printers/{id}/camera/stream
  11265. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11266. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11267. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11268. # string (same reasoning as the camera streams above — no header to carry a
  11269. # JWT). "Public" only means the middleware steps aside; the route still runs
  11270. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11271. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11272. "/overlay-status", # /printers/{id}/overlay-status
  11273. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11274. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11275. # download token in the URL path instead.
  11276. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11277. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11278. # and these patterns match by substring. Without its own entry the middleware
  11279. # 401s the slicer's header-less request before the route's token check runs,
  11280. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11281. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11282. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11283. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11284. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11285. ]
  11286. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11287. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11288. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11289. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11290. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11291. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11292. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11293. Invalid entries are dropped with a warning rather than failing startup, so
  11294. a typo in one origin doesn't take the whole deployment down.
  11295. """
  11296. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11297. if not raw:
  11298. return ()
  11299. valid: list[str] = []
  11300. for item in raw.split(","):
  11301. candidate = item.strip()
  11302. if not candidate:
  11303. continue
  11304. try:
  11305. parsed = urlparse(candidate)
  11306. except ValueError as e:
  11307. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11308. continue
  11309. if parsed.scheme not in ("http", "https"):
  11310. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11311. continue
  11312. if not parsed.netloc:
  11313. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11314. continue
  11315. if parsed.path and parsed.path != "/":
  11316. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11317. continue
  11318. if parsed.query or parsed.fragment:
  11319. _security_headers_logger.warning(
  11320. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11321. )
  11322. continue
  11323. if "*" in parsed.netloc:
  11324. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11325. continue
  11326. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11327. if valid:
  11328. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11329. return tuple(valid)
  11330. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11331. def _frame_ancestors(default_value: str) -> str:
  11332. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11333. ``default_value`` is the strict directive used when the operator has not
  11334. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11335. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11336. Settings URL builder's preview). When trusted origins
  11337. are configured, ``'self'`` is always included so same-origin embedding never
  11338. breaks even if an operator forgets to add their own origin to the list.
  11339. """
  11340. if _TRUSTED_FRAME_ORIGINS:
  11341. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11342. return f"frame-ancestors {default_value};"
  11343. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11344. # patterns are anchored on the exact emitted name so the relaxed policies
  11345. # below can never apply to any other asset.
  11346. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11347. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11348. # -> /assets/pdf.worker.min-<hash>.js
  11349. # Vite also emits a one-line chunk under the second name that only exports the
  11350. # worker's URL. The page imports it as a module, and a module script is run
  11351. # under the importing document's policy, never its own response's, so it
  11352. # matching as well changes nothing.
  11353. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11354. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11355. @app.middleware("http")
  11356. async def security_headers_middleware(request, call_next):
  11357. """Add standard HTTP security headers to every response."""
  11358. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11359. # changes nothing for Bambuddy's own pages — index.html has no inline
  11360. # scripts since the SW registration moved to /sw-register.js. The reason
  11361. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11362. # script injected into the HTML on the edge, with a fresh hash on every
  11363. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11364. # it clones the same nonce onto its injected <script>, and the inline
  11365. # script passes the policy without us needing 'unsafe-inline'. See
  11366. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11367. csp_nonce = secrets.token_urlsafe(16)
  11368. # Routes that render their own HTML need it too, or their inline script is
  11369. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11370. # one that does: it submits its own form so a verdict still costs one tap.
  11371. request.state.csp_nonce = csp_nonce
  11372. response = await call_next(request)
  11373. response.headers["X-Content-Type-Options"] = "nosniff"
  11374. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11375. # browsers honour CSP frame-ancestors instead, and the legacy
  11376. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11377. # When operators have explicitly allowlisted trusted frame origins (#1191
  11378. # — typically Home Assistant on a different port), drop X-Frame-Options
  11379. # and let the CSP-side frame-ancestors directive govern embedding.
  11380. if not _TRUSTED_FRAME_ORIGINS:
  11381. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11382. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11383. # Content-Security-Policy for the React SPA.
  11384. # Notes:
  11385. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11386. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11387. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11388. # - media-src blob:: timelapse video player uses Blob URLs.
  11389. # - font-src data:: some icon fonts are embedded as data URIs.
  11390. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11391. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11392. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11393. # default CSP would render a blank page.
  11394. response.headers["Content-Security-Policy"] = (
  11395. "default-src 'self'; "
  11396. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11397. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11398. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11399. "connect-src 'self'; "
  11400. "font-src 'self' data: https://fonts.gstatic.com; "
  11401. "worker-src 'self' blob:; "
  11402. "object-src 'none'; "
  11403. "base-uri 'self'; " + _frame_ancestors("'none'")
  11404. )
  11405. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11406. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11407. # its emscripten/embind glue generates invoker functions with `new
  11408. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11409. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11410. # own response — not the document's — so relaxing it here confines
  11411. # eval to that DOM-less worker context. The document policy below
  11412. # stays nonce-strict, and this response header has no effect when the
  11413. # file is merely fetched (a fetch's CSP is enforced against the
  11414. # requesting document, not the resource's own headers).
  11415. response.headers["Content-Security-Policy"] = (
  11416. "default-src 'self'; "
  11417. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11418. "connect-src 'self'; "
  11419. "object-src 'none'; "
  11420. "base-uri 'self'; " + _frame_ancestors("'none'")
  11421. )
  11422. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11423. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11424. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11425. # rule as the STEP worker above: the policy that governs a dedicated
  11426. # worker is the one delivered with its own script, so the wasm compile
  11427. # has to be permitted here rather than on the document. Unlike the STEP
  11428. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11429. response.headers["Content-Security-Policy"] = (
  11430. "default-src 'self'; "
  11431. "script-src 'self' 'wasm-unsafe-eval'; "
  11432. "connect-src 'self'; "
  11433. "object-src 'none'; "
  11434. "base-uri 'self'; " + _frame_ancestors("'none'")
  11435. )
  11436. else:
  11437. # The streaming overlay is embedded same-origin by the URL builder's
  11438. # preview in Settings (#1422), so this branch allows 'self'.
  11439. # Embedding from anywhere else is still refused: 'self'
  11440. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11441. # a clickjacking page on another host is blocked exactly as before.
  11442. # (The overlay draws status over a camera feed and its only interactive
  11443. # element is the logo link, so there is nothing to bait a click into
  11444. # even from a same-origin framer.) Cross-origin embedding of the
  11445. # overlay — Home Assistant on another port — remains what
  11446. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11447. # allowlist in.
  11448. #
  11449. # The connected-app consent page (/connect/authorize) gets the same
  11450. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11451. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11452. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11453. # requires every ancestor to be this origin, so a foreign page -- a
  11454. # sidebar link's site included -- still cannot frame the consent
  11455. # screen to bait a click.
  11456. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11457. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11458. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11459. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11460. # the policy served with their own script, so each gets it in its own
  11461. # branch above and the document policy stays as strict as it was.
  11462. response.headers["Content-Security-Policy"] = (
  11463. "default-src 'self'; "
  11464. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11465. "style-src 'self' 'unsafe-inline'; "
  11466. "img-src 'self' data: blob:; "
  11467. "media-src 'self' blob:; "
  11468. "connect-src 'self' ws: wss:; "
  11469. "font-src 'self' data:; "
  11470. "object-src 'none'; "
  11471. "base-uri 'self'; "
  11472. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11473. )
  11474. if request.url.scheme == "https":
  11475. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11476. return response
  11477. @app.middleware("http")
  11478. async def auth_middleware(request, call_next):
  11479. """Enforce authentication on all API routes when auth is enabled.
  11480. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11481. regardless of whether individual routes have auth dependencies.
  11482. """
  11483. from starlette.responses import JSONResponse
  11484. path = request.url.path
  11485. # Only apply to API routes
  11486. if not path.startswith("/api/"):
  11487. return await call_next(request)
  11488. # Allow public routes
  11489. if path in PUBLIC_API_ROUTES:
  11490. return await call_next(request)
  11491. # Allow public prefixes
  11492. for prefix in PUBLIC_API_PREFIXES:
  11493. if path.startswith(prefix):
  11494. return await call_next(request)
  11495. # Allow public patterns (read-only display data like thumbnails)
  11496. for pattern in PUBLIC_API_PATTERNS:
  11497. if pattern in path:
  11498. return await call_next(request)
  11499. # Check if auth is enabled. Fail CLOSED on any exception during the
  11500. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11501. # an attacker who could force a DB exception (e.g. file-descriptor
  11502. # exhaustion via login flood) bypass auth on every protected endpoint.
  11503. # Only the probe is guarded: the request itself runs outside the try, so an
  11504. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11505. try:
  11506. async with async_session() as db:
  11507. from backend.app.core.auth import is_auth_enabled
  11508. auth_enabled = await is_auth_enabled(db)
  11509. except Exception:
  11510. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11511. return JSONResponse(
  11512. status_code=503,
  11513. content={"detail": "Authentication service temporarily unavailable"},
  11514. )
  11515. if not auth_enabled:
  11516. # Auth disabled, allow all requests
  11517. return await call_next(request)
  11518. # Auth is enabled - require valid token
  11519. auth_header = request.headers.get("Authorization")
  11520. x_api_key = request.headers.get("X-API-Key")
  11521. # Check for API key auth first
  11522. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11523. # API key authentication - let the request through to be validated by route handler
  11524. # API keys are validated per-route since they have different permission levels
  11525. return await call_next(request)
  11526. # Check for JWT auth
  11527. if not auth_header or not auth_header.startswith("Bearer "):
  11528. return JSONResponse(
  11529. status_code=401,
  11530. content={"detail": "Authentication required"},
  11531. headers={"WWW-Authenticate": "Bearer"},
  11532. )
  11533. # Validate JWT token
  11534. import jwt
  11535. try:
  11536. from backend.app.core.auth import (
  11537. ALGORITHM,
  11538. SECRET_KEY,
  11539. _is_token_fresh,
  11540. get_user_by_username,
  11541. is_jti_revoked,
  11542. )
  11543. token = auth_header.replace("Bearer ", "")
  11544. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11545. username = payload.get("sub")
  11546. if not username:
  11547. raise ValueError("No username in token")
  11548. jti = payload.get("jti")
  11549. if not jti:
  11550. raise ValueError("No jti in token")
  11551. iat = payload.get("iat")
  11552. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11553. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11554. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11555. async with async_session() as db:
  11556. if await is_jti_revoked(jti, db):
  11557. return JSONResponse(
  11558. status_code=401,
  11559. content={"detail": "Token has been revoked"},
  11560. headers={"WWW-Authenticate": "Bearer"},
  11561. )
  11562. user = await get_user_by_username(db, username)
  11563. if not user or not user.is_active:
  11564. return JSONResponse(
  11565. status_code=401,
  11566. content={"detail": "User not found or inactive"},
  11567. headers={"WWW-Authenticate": "Bearer"},
  11568. )
  11569. if not _is_token_fresh(iat, user):
  11570. return JSONResponse(
  11571. status_code=401,
  11572. content={"detail": "Token no longer valid"},
  11573. headers={"WWW-Authenticate": "Bearer"},
  11574. )
  11575. except jwt.ExpiredSignatureError:
  11576. return JSONResponse(
  11577. status_code=401,
  11578. content={"detail": "Token has expired"},
  11579. headers={"WWW-Authenticate": "Bearer"},
  11580. )
  11581. except (jwt.InvalidTokenError, ValueError):
  11582. return JSONResponse(
  11583. status_code=401,
  11584. content={"detail": "Invalid token"},
  11585. headers={"WWW-Authenticate": "Bearer"},
  11586. )
  11587. except Exception:
  11588. # Not a bad token but a failure checking it (database, pool): refuse,
  11589. # as for the probe above, rather than answer 401 -- the frontend reads
  11590. # a 401 from /auth/me as final and signs the user out.
  11591. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11592. return JSONResponse(
  11593. status_code=503,
  11594. content={"detail": "Authentication service temporarily unavailable"},
  11595. )
  11596. return await call_next(request)
  11597. @app.middleware("http")
  11598. async def trace_id_middleware(request, call_next):
  11599. """Stamp every HTTP request with a trace ID and echo it back.
  11600. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11601. @app.middleware decorators LIFO, so the last-decorated runs first
  11602. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11603. which means auth-middleware log lines (and every line emitted on the
  11604. way down to and back from the route handler) all carry the same
  11605. trace ID. If we put it before auth, auth's logs would be stamped
  11606. with the *previous* request's ID — useless for correlation.
  11607. Honours an inbound ``X-Trace-Id`` header so callers running their
  11608. own tracing can correlate their span IDs with our log lines, but
  11609. only if the value passes the whitelist gate in
  11610. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11611. rejected (too long, contains control chars, etc.) silently triggers
  11612. a freshly minted server-side ID rather than failing the request.
  11613. The minted (or echoed) ID is set on a ContextVar so that every log
  11614. record emitted during the request — application logs *and* uvicorn's
  11615. access log — carries it via TraceIDFilter, and is also written to
  11616. the ``X-Trace-Id`` response header so clients can pin a server-side
  11617. log search to the exact request they made.
  11618. """
  11619. from backend.app.core.trace import (
  11620. generate_trace_id,
  11621. normalise_inbound_trace_id,
  11622. trace_id_var,
  11623. )
  11624. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11625. trace_id = inbound if inbound is not None else generate_trace_id()
  11626. token = trace_id_var.set(trace_id)
  11627. try:
  11628. response = await call_next(request)
  11629. finally:
  11630. # Reset the ContextVar so a record emitted in a totally
  11631. # unrelated background task that just happens to inherit this
  11632. # context doesn't keep referencing this request's ID forever.
  11633. # In practice ContextVar.reset is best-effort under asyncio
  11634. # task-spawn semantics, but the cost is one attribute write so
  11635. # we may as well do it.
  11636. trace_id_var.reset(token)
  11637. response.headers["X-Trace-Id"] = trace_id
  11638. return response
  11639. # API routes
  11640. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11641. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11642. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11643. app.include_router(users.router, prefix=app_settings.api_prefix)
  11644. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11645. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11646. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11647. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11648. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11649. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11650. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11651. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11652. app.include_router(label_templates.router, prefix=app_settings.api_prefix)
  11653. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11654. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11655. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11656. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11657. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11658. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11659. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11660. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11661. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11662. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11663. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11664. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11665. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11666. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11667. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11668. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11669. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11670. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11671. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11672. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11673. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11674. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11675. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11676. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11677. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11678. app.include_router(library.router, prefix=app_settings.api_prefix)
  11679. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11680. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11681. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11682. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11683. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11684. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11685. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11686. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11687. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11688. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11689. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11690. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11691. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11692. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11693. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11694. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11695. app.include_router(system.router, prefix=app_settings.api_prefix)
  11696. app.include_router(support.router, prefix=app_settings.api_prefix)
  11697. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11698. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11699. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11700. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11701. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11702. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11703. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11704. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11705. app.include_router(octoeverywhere.router, prefix=app_settings.api_prefix)
  11706. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11707. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11708. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11709. # Serve static files (React build)
  11710. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11711. # Compressed, and cached for good where Vite hashed the name (#3175).
  11712. app.mount(
  11713. "/assets",
  11714. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11715. name="assets",
  11716. )
  11717. if (app_settings.static_dir / "img").exists():
  11718. app.mount(
  11719. "/img",
  11720. StaticFiles(directory=app_settings.static_dir / "img"),
  11721. name="img",
  11722. )
  11723. if (app_settings.static_dir / "icons").exists():
  11724. app.mount(
  11725. "/icons",
  11726. StaticFiles(directory=app_settings.static_dir / "icons"),
  11727. name="icons",
  11728. )
  11729. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11730. # falls through to the SPA catch-all and returns index.html, which the
  11731. # browser's font sanitizer rejects ("downloadable font: rejected by
  11732. # sanitizer").
  11733. if (app_settings.static_dir / "fonts").exists():
  11734. app.mount(
  11735. "/fonts",
  11736. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11737. name="fonts",
  11738. )
  11739. @app.get("/")
  11740. async def serve_frontend():
  11741. """Serve the React frontend."""
  11742. index_file = app_settings.static_dir / "index.html"
  11743. if index_file.exists():
  11744. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11745. return {
  11746. "message": "Bambuddy API",
  11747. "docs": "/docs",
  11748. "frontend": "Build and place React app in /static directory",
  11749. }
  11750. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11751. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11752. # forever, but the HTML wrapping it is the only file that knows which hash
  11753. # is current. Without explicit cache-control headers Chromium decides
  11754. # heuristically (typically 10% of the time since Last-Modified) and on
  11755. # long-running kiosks happily serves stale HTML across browser restarts.
  11756. # That stale HTML references an old bundle hash, the old bundle is also
  11757. # in the disk cache, and the user ends up running pre-update JS forever
  11758. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11759. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11760. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11761. @app.get("/health")
  11762. async def health_check():
  11763. """Health check endpoint."""
  11764. return {"status": "healthy"}
  11765. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11766. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11767. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11768. # in deployment debugging. One decorator per method, not api_route(methods=
  11769. # [...]): api_route gives both methods the same OpenAPI operation id.
  11770. @app.get("/manifest.json")
  11771. @app.head("/manifest.json")
  11772. async def serve_manifest():
  11773. """Serve PWA manifest."""
  11774. manifest_file = app_settings.static_dir / "manifest.json"
  11775. if manifest_file.exists():
  11776. return FileResponse(manifest_file, media_type="application/manifest+json")
  11777. return {"error": "Manifest not found"}
  11778. @app.get("/sw.js")
  11779. @app.head("/sw.js")
  11780. async def serve_service_worker():
  11781. """Serve service worker."""
  11782. sw_file = app_settings.static_dir / "sw.js"
  11783. if sw_file.exists():
  11784. return FileResponse(
  11785. sw_file,
  11786. media_type="application/javascript",
  11787. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11788. )
  11789. return {"error": "Service worker not found"}
  11790. @app.get("/sw-register.js")
  11791. @app.head("/sw-register.js")
  11792. async def serve_sw_register():
  11793. """Serve the service-worker registration bootstrap script.
  11794. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11795. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11796. """
  11797. reg_file = app_settings.static_dir / "sw-register.js"
  11798. if reg_file.exists():
  11799. return FileResponse(reg_file, media_type="application/javascript")
  11800. return {"error": "sw-register.js not found"}
  11801. # ── GCode viewer static files ────────────────────────────────────────────────
  11802. # Catch-all route for React Router (must be last)
  11803. @app.get("/{full_path:path}")
  11804. async def serve_spa(full_path: str):
  11805. """Serve React app for client-side routing."""
  11806. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11807. if full_path.startswith("api/"):
  11808. from fastapi import HTTPException
  11809. raise HTTPException(status_code=404, detail="Not found")
  11810. index_file = app_settings.static_dir / "index.html"
  11811. if index_file.exists():
  11812. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11813. return {"error": "Frontend not built"}