main.py 324 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803
  1. import asyncio
  2. import json
  3. import logging
  4. import mimetypes as _mimetypes
  5. import os
  6. import posixpath
  7. import secrets
  8. import time
  9. from contextlib import asynccontextmanager
  10. from datetime import datetime, timedelta, timezone
  11. from logging.handlers import RotatingFileHandler
  12. from pathlib import Path
  13. from urllib.parse import urlparse
  14. from fastapi import FastAPI
  15. from fastapi.responses import FileResponse
  16. from fastapi.staticfiles import StaticFiles
  17. from sqlalchemy import delete, or_, select, text
  18. from backend.app.api.routes import (
  19. ams_history,
  20. api_keys,
  21. archive_purge,
  22. archives,
  23. auth,
  24. background_dispatch as background_dispatch_routes,
  25. bug_report,
  26. camera,
  27. cloud,
  28. discovery,
  29. external_links,
  30. filaments,
  31. firmware,
  32. github_backup,
  33. groups,
  34. inventory,
  35. kprofiles,
  36. labels,
  37. library,
  38. library_tags,
  39. library_trash,
  40. local_backup,
  41. local_presets,
  42. maintenance,
  43. makerworld,
  44. metrics,
  45. mfa,
  46. notification_templates,
  47. notifications,
  48. obico,
  49. orca_cloud,
  50. pending_uploads,
  51. print_log,
  52. print_queue,
  53. printer_sensor_history,
  54. printers,
  55. projects,
  56. settings as settings_routes,
  57. slice_jobs,
  58. slicer_presets,
  59. smart_plugs,
  60. sponsor_prompt,
  61. spoolbuddy,
  62. spoolman,
  63. spoolman_inventory,
  64. support,
  65. system,
  66. updates,
  67. user_notifications,
  68. users,
  69. virtual_printers,
  70. webhook,
  71. websocket,
  72. )
  73. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  74. from backend.app.api.routes.support import init_debug_logging
  75. from backend.app.core.config import APP_VERSION, settings as app_settings
  76. from backend.app.core.database import async_session, engine, init_db
  77. from backend.app.core.tasks import spawn_background_task
  78. from backend.app.core.websocket import ws_manager
  79. from backend.app.models.smart_plug import SmartPlug
  80. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  81. from backend.app.services.archive_purge import archive_purge_service
  82. from backend.app.services.background_dispatch import background_dispatch
  83. from backend.app.services.bambu_ftp import (
  84. FileNotOnPrinterError,
  85. cache_3mf_download,
  86. clear_3mf_cache,
  87. download_file_async,
  88. get_cached_3mf,
  89. get_ftp_retry_settings,
  90. with_ftp_retry,
  91. )
  92. from backend.app.services.bambu_mqtt import PrinterState
  93. from backend.app.services.github_backup import github_backup_service
  94. from backend.app.services.homeassistant import homeassistant_service
  95. from backend.app.services.library_trash import library_trash_service
  96. from backend.app.services.local_backup import local_backup_service
  97. from backend.app.services.mqtt_relay import mqtt_relay
  98. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  99. from backend.app.services.notification_service import notification_service
  100. from backend.app.services.obico_detection import obico_detection_service
  101. from backend.app.services.print_scheduler import scheduler as print_scheduler
  102. from backend.app.services.printer_manager import (
  103. init_printer_connections,
  104. parse_plate_id,
  105. printer_manager,
  106. printer_state_to_dict,
  107. )
  108. from backend.app.services.smart_plug_manager import smart_plug_manager
  109. from backend.app.services.spool_assignment_notifications import (
  110. notify_missing_spool_assignments_on_print_start,
  111. )
  112. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  113. from backend.app.services.spoolman_tracking import (
  114. cleanup_tracking as _cleanup_spoolman_tracking,
  115. report_usage as _report_spoolman_usage,
  116. store_print_data as _store_spoolman_print_data,
  117. )
  118. from backend.app.services.tasmota import tasmota_service
  119. # =============================================================================
  120. # Dependency Check - runs before other imports to give helpful error messages
  121. # =============================================================================
  122. def _start_error_server(missing_packages: list):
  123. """Start a minimal HTTP server to display dependency errors in browser."""
  124. import os
  125. import signal
  126. from http.server import BaseHTTPRequestHandler, HTTPServer
  127. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  128. html = f"""<!DOCTYPE html>
  129. <html>
  130. <head>
  131. <title>Bambuddy - Setup Required</title>
  132. <style>
  133. body {{
  134. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  135. background: #0f172a; color: #e2e8f0;
  136. display: flex; justify-content: center; align-items: center;
  137. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  138. }}
  139. .container {{
  140. background: #1e293b; border-radius: 12px; padding: 40px;
  141. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  142. }}
  143. h1 {{ color: #f87171; margin-bottom: 10px; }}
  144. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  145. .packages {{
  146. background: #0f172a; border-radius: 8px; padding: 20px;
  147. margin: 20px 0; text-align: left;
  148. }}
  149. .packages ul {{ margin: 0; padding-left: 20px; }}
  150. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  151. .command {{
  152. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  153. margin: 15px 0; font-family: monospace; color: #4ade80;
  154. text-align: left; overflow-x: auto;
  155. }}
  156. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  157. </style>
  158. </head>
  159. <body>
  160. <div class="container">
  161. <h1>Setup Required</h1>
  162. <h2>Missing Python packages</h2>
  163. <div class="packages"><ul>{packages_html}</ul></div>
  164. <p>To fix, run this command on your server:</p>
  165. <div class="command">pip install -r requirements.txt</div>
  166. <p>Or if using a virtual environment:</p>
  167. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  168. <p class="note">After installing, restart Bambuddy:<br>
  169. <code>sudo systemctl restart bambuddy</code></p>
  170. </div>
  171. </body>
  172. </html>"""
  173. class ErrorHandler(BaseHTTPRequestHandler):
  174. def do_GET(self):
  175. self.send_response(503)
  176. self.send_header("Content-type", "text/html")
  177. self.end_headers()
  178. self.wfile.write(html.encode())
  179. def log_message(self, format, *args):
  180. print(f"[Error Server] {args[0]}")
  181. port = int(os.environ.get("PORT", 8000))
  182. print(f"\nStarting error server on http://0.0.0.0:{port}")
  183. print("Visit this URL in your browser to see the error details.\n")
  184. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  185. def shutdown(signum, frame):
  186. print("\nShutting down error server...")
  187. raise SystemExit(0)
  188. signal.signal(signal.SIGTERM, shutdown)
  189. signal.signal(signal.SIGINT, shutdown)
  190. server.serve_forever()
  191. def check_dependencies():
  192. """Check that all required packages are installed."""
  193. missing = []
  194. # Map of import name -> package name (for pip install)
  195. required = {
  196. "jwt": "PyJWT",
  197. "fastapi": "fastapi",
  198. "uvicorn": "uvicorn",
  199. "sqlalchemy": "sqlalchemy",
  200. "aiosqlite": "aiosqlite",
  201. "pydantic": "pydantic",
  202. "paho.mqtt": "paho-mqtt",
  203. }
  204. for module, package in required.items():
  205. try:
  206. __import__(module)
  207. except ImportError:
  208. missing.append(package)
  209. if missing:
  210. print("\n" + "=" * 60)
  211. print("ERROR: Missing required Python packages!")
  212. print("=" * 60)
  213. print(f"\nMissing packages: {', '.join(missing)}")
  214. print("\nTo fix, run:")
  215. print(" pip install -r requirements.txt")
  216. print("\nOr if using a virtual environment:")
  217. print(" ./venv/bin/pip install -r requirements.txt")
  218. print("=" * 60 + "\n")
  219. _start_error_server(missing)
  220. check_dependencies()
  221. # =============================================================================
  222. # Import settings first for logging configuration
  223. # Configure logging based on settings
  224. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  225. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  226. log_level = getattr(logging, log_level_str, logging.INFO)
  227. # Trace ID column ([-] when no request scope is active — startup, MQTT
  228. # callbacks, scheduled tasks not chained from a request — so the column
  229. # stays visually aligned and missing values are obvious in grep). See
  230. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  231. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  232. # Create root logger
  233. root_logger = logging.getLogger()
  234. root_logger.setLevel(log_level)
  235. # Trace-ID injection: this filter populates record.trace_id from the
  236. # per-request ContextVar so the format string above can reference it.
  237. # Attached to each HANDLER (not the root logger) because Python's
  238. # logging semantics only invoke a logger's filters on records that
  239. # *originated* at that logger — records propagated up from child
  240. # loggers (every named logger in the app) never trigger root's filter.
  241. # Putting it on the handlers means every record any handler emits gets
  242. # trace_id injected just before the formatter runs, regardless of which
  243. # logger created the record. Without this, the formatter raises
  244. # KeyError on every child-logger record and the record is silently
  245. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  246. # partially" bug we hit. See backend/app/core/trace.py for the
  247. # ContextVar the filter reads.
  248. from backend.app.core.trace import TraceIDFilter
  249. _trace_id_filter = TraceIDFilter()
  250. # Console handler - always enabled
  251. console_handler = logging.StreamHandler()
  252. console_handler.setLevel(log_level)
  253. console_handler.setFormatter(logging.Formatter(log_format))
  254. console_handler.addFilter(_trace_id_filter)
  255. root_logger.addHandler(console_handler)
  256. # File handler - only in production or if explicitly enabled
  257. if app_settings.log_to_file:
  258. log_file = app_settings.log_dir / "bambuddy.log"
  259. file_handler = RotatingFileHandler(
  260. log_file,
  261. maxBytes=5 * 1024 * 1024, # 5MB
  262. backupCount=3,
  263. encoding="utf-8",
  264. )
  265. file_handler.setLevel(log_level)
  266. file_handler.setFormatter(logging.Formatter(log_format))
  267. file_handler.addFilter(_trace_id_filter)
  268. root_logger.addHandler(file_handler)
  269. logging.info("Logging to file: %s", log_file)
  270. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  271. # access logger with propagate=False by default, so without this attach
  272. # there is no on-disk record of which endpoint triggered a server-state
  273. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  274. # for exactly this reason. Filtered to write methods only
  275. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  276. # frontend don't churn the rotation window faster than it's useful.
  277. from backend.app.core.logging_filters import (
  278. CancelledPoolNoiseFilter,
  279. WriteRequestsOnlyFilter,
  280. )
  281. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  282. uvicorn_access_logger.addHandler(file_handler)
  283. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  284. # Uvicorn's access logger has propagate=False (its own default), so the
  285. # root-attached TraceIDFilter never sees these records. Attach a
  286. # second instance directly so HTTP access lines carry the same trace
  287. # ID column as the application logs they correlate with.
  288. uvicorn_access_logger.addFilter(TraceIDFilter())
  289. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  290. # BaseHTTPMiddleware cancelling the inner task scope on client
  291. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  292. # underlying transaction leak; this filter only suppresses the residual
  293. # log records that pre-existing pools still emit during their cleanup.
  294. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  295. # Reduce noise from third-party libraries in production
  296. if not app_settings.debug:
  297. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  298. logging.getLogger("httpcore").setLevel(logging.WARNING)
  299. logging.getLogger("httpx").setLevel(logging.WARNING)
  300. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  301. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  302. # Track active prints: {(printer_id, filename): archive_id}
  303. _active_prints: dict[tuple[int, str], int] = {}
  304. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  305. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  306. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  307. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  308. # instead of running its own grab-now chain when present, so the finish photo
  309. # captures the better-framed pre-bed-drop moment without us having to force
  310. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  311. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  312. _stage22_finish_frames: dict[int, bytes] = {}
  313. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  314. # `finally` block (whether it captured a frame or not). The consumer in
  315. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  316. # so the FINISH-state fallback path — where moment and completion are dispatched
  317. # back-to-back — doesn't race past the producer with an empty pop, and the
  318. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  319. # grab (Bambu printers allow only one RTSP client at a time).
  320. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  321. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  322. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  323. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  324. # the first connected status update for that connection; transitions back
  325. # to False whenever we observe `state.connected = False` so the next
  326. # reconnect re-arms reconciliation. Keyed by printer_id.
  327. _printer_reconciled_since_connect: dict[int, bool] = {}
  328. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  329. # {(printer_id, filename): archive_id}
  330. _expected_prints: dict[tuple[int, str], int] = {}
  331. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  332. # Used by usage tracker to map 3MF slots to physical AMS trays
  333. _print_ams_mappings: dict[int, list[int]] = {}
  334. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  335. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  336. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  337. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  338. # for the queue path. Cleared on print completion or TTL eviction.
  339. _print_plate_ids: dict[int, int] = {}
  340. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  341. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  342. _last_progress_milestone: dict[int, int] = {}
  343. # Track whether first layer complete notification has been sent for current print
  344. _first_layer_notified: dict[int, bool] = {}
  345. # Track HMS errors that have been notified: {printer_id: set of error codes}
  346. # This prevents sending duplicate notifications for the same error
  347. _notified_hms_errors: dict[int, set[str]] = {}
  348. # Track when HMS errors were last seen: {printer_id: timestamp}
  349. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  350. _hms_last_seen: dict[int, float] = {}
  351. _HMS_CLEAR_GRACE_SECONDS = 30.0
  352. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  353. # Used for snapshot-diff detection at print completion
  354. _timelapse_baselines: dict[int, set[str]] = {}
  355. # Track printers waiting for bed to cool after print completion.
  356. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  357. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  358. _bed_cool_waiters: dict[int, dict] = {}
  359. # Track printers where the user explicitly stopped the print from the queue UI.
  360. # When on_print_complete fires with status "failed" for these printers we treat it
  361. # as "cancelled" (stopped by user) so the correct notification email is sent.
  362. _user_stopped_printers: set[int] = set()
  363. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  364. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  365. # holds the previous observation so we only fire on the True → False edge (a
  366. # False → False repeat doesn't notify; an initial False at startup doesn't
  367. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  368. # holds the per-printer pending asyncio task that fires the notification
  369. # after a debounce window — cancelled if the printer reconnects before the
  370. # window elapses, so transient MQTT blips don't flood the user.
  371. _printer_last_connected: dict[int, bool] = {}
  372. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  373. # Debounce: a printer must stay offline this long before we notify. Sized
  374. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  375. # so a single stale-trigger cooldown isn't enough to fire — only a real
  376. # offline that survives one reconnect attempt notifies.
  377. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  378. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  379. # when status="failed" to label the print's failure_reason in archives.
  380. #
  381. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  382. # which is wrong on two counts:
  383. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  384. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  385. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  386. # the public wiki) as part of its user-cancel sequence. Matching on the module
  387. # alone caused user-cancellations to be archived as "Layer shift" failures.
  388. # We now match by full short code only — anything not in this map leaves
  389. # failure_reason=None rather than guessing.
  390. _HMS_FAILURE_REASONS: dict[str, str] = {
  391. # Layer shift / step loss
  392. "0300_4057": "Layer shift",
  393. "0300_4068": "Layer shift",
  394. "0300_800C": "Layer shift",
  395. # Filament runout (printer-side & per-AMS-slot)
  396. "0300_8004": "Filament runout",
  397. "0700_8011": "Filament runout",
  398. "0701_8011": "Filament runout",
  399. "0702_8011": "Filament runout",
  400. "0703_8011": "Filament runout",
  401. "0704_8011": "Filament runout",
  402. "0705_8011": "Filament runout",
  403. "0706_8011": "Filament runout",
  404. "0707_8011": "Filament runout",
  405. "07FF_8011": "Filament runout",
  406. # Clogged nozzle / extruder
  407. "0300_4006": "Clogged nozzle",
  408. "0300_8016": "Clogged nozzle",
  409. "0300_801C": "Clogged nozzle",
  410. "0700_8003": "Clogged nozzle",
  411. "0700_8007": "Clogged nozzle",
  412. "0700_8013": "Clogged nozzle",
  413. "0701_8003": "Clogged nozzle",
  414. "0701_8007": "Clogged nozzle",
  415. "0701_8013": "Clogged nozzle",
  416. "0702_8003": "Clogged nozzle",
  417. }
  418. def _hms_short_code(attr: int, code: int | str) -> str:
  419. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  420. if isinstance(code, str):
  421. code_int = int(code.replace("0x", ""), 16) if code else 0
  422. else:
  423. code_int = int(code or 0)
  424. attr_int = int(attr or 0)
  425. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  426. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  427. """Derive a human-readable failure_reason for an archived print.
  428. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  429. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  430. no HMS code matches (don't guess — null is honest).
  431. """
  432. if status in ("aborted", "cancelled"):
  433. return "User cancelled"
  434. if status != "failed":
  435. return None
  436. for err in hms_errors or []:
  437. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  438. if short_code in _HMS_FAILURE_REASONS:
  439. return _HMS_FAILURE_REASONS[short_code]
  440. return None
  441. # Track created_by_id for expected prints so the user email can be sent even when
  442. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  443. # {(printer_id, filename): created_by_id}
  444. _expected_print_creators: dict[tuple[int, str], int] = {}
  445. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  446. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  447. # updates for the same printer in quick succession (~30 ms apart, observed in
  448. # the wild on H2D + dual AMS).
  449. #
  450. # Without this serialisation, two concurrent on_ams_change callbacks each read
  451. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  452. # the second commit hits
  453. # IntegrityError: duplicate key value violates unique constraint
  454. # "spool_assignment_printer_id_ams_id_tray_id_key"
  455. # SQLite's WAL serial-write semantics had been silently swallowing the race
  456. # until optional Postgres support landed (asyncpg allows true concurrent
  457. # transactions and surfaces the constraint violation).
  458. #
  459. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  460. # assign) are inside the lock. The Spoolman sync block further down stays
  461. # concurrent because it's network-bound and idempotent.
  462. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  463. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  464. """Return the per-printer assignment lock, creating it on first use."""
  465. lock = _ams_assignment_locks.get(printer_id)
  466. if lock is None:
  467. lock = asyncio.Lock()
  468. _ams_assignment_locks[printer_id] = lock
  469. return lock
  470. # TTL for expected-print entries: evict registrations older than this to prevent
  471. # unbounded growth when a print is registered but never starts (e.g. printer
  472. # disconnect, app restart, print started from the printer panel).
  473. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  474. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  475. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  476. # Cleanup loop interval
  477. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  478. _expected_prints_cleanup_task: asyncio.Task | None = None
  479. async def _get_plug_energy(plug, db) -> dict | None:
  480. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  481. For HA plugs, configures the service with current settings from DB.
  482. For MQTT plugs, returns data from the subscription service.
  483. For REST plugs, polls the status URL with JSON path extraction.
  484. """
  485. if plug.plug_type == "homeassistant":
  486. from backend.app.api.routes.settings import get_homeassistant_settings
  487. ha_settings = await get_homeassistant_settings(db)
  488. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  489. return await homeassistant_service.get_energy(plug)
  490. elif plug.plug_type == "mqtt":
  491. # MQTT plugs report "today" energy, not lifetime total
  492. # For per-print tracking, we use "today" as the counter (resets at midnight)
  493. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  494. if mqtt_data:
  495. return {
  496. "power": mqtt_data.power,
  497. "today": mqtt_data.energy,
  498. "total": mqtt_data.energy, # Use today as total for per-print calculations
  499. }
  500. return None
  501. elif plug.plug_type == "rest":
  502. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  503. return await rest_smart_plug_service.get_energy(plug)
  504. else:
  505. return await tasmota_service.get_energy(plug)
  506. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  507. """Capture the smart plug lifetime counter on the archive at print start.
  508. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  509. tracking survives a backend restart mid-print. The print-end handler reads
  510. this value back from the DB and computes the delta against the current
  511. plug counter.
  512. """
  513. _logger = logging.getLogger(__name__)
  514. try:
  515. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  516. plug = plug_result.scalar_one_or_none()
  517. if not plug:
  518. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  519. return False
  520. energy = await _get_plug_energy(plug, db)
  521. if not energy or energy.get("total") is None:
  522. _logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  523. return False
  524. archive.energy_start_kwh = float(energy["total"])
  525. await db.commit()
  526. _logger.info(
  527. "[ENERGY] Recorded starting energy%s for archive %s: %s kWh",
  528. f" ({context})" if context else "",
  529. archive.id,
  530. energy["total"],
  531. )
  532. return True
  533. except Exception as e:
  534. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  535. return False
  536. def register_expected_print(
  537. printer_id: int,
  538. filename: str,
  539. archive_id: int,
  540. ams_mapping: list[int] | None = None,
  541. created_by_id: int | None = None,
  542. plate_id: int | None = None,
  543. ):
  544. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  545. # Store with multiple filename variations to catch different naming patterns
  546. _expected_prints[(printer_id, filename)] = archive_id
  547. # Also store without .3mf extension if present
  548. if filename.endswith(".3mf"):
  549. base = filename[:-4]
  550. _expected_prints[(printer_id, base)] = archive_id
  551. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  552. # Store AMS mapping for usage tracking at print completion
  553. if ams_mapping is not None:
  554. _print_ams_mappings[archive_id] = ams_mapping
  555. # Store plate_id for usage tracking when this is a single-plate dispatch from
  556. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  557. # file's filament total to the spool instead of just the printed plate (#1697).
  558. if plate_id is not None:
  559. _print_plate_ids[archive_id] = plate_id
  560. # Store created_by_id so the user start email can be sent even when the archive
  561. # itself has no created_by_id (e.g. library-file-based queue prints)
  562. if created_by_id is not None:
  563. _expected_print_creators[(printer_id, filename)] = created_by_id
  564. if filename.endswith(".3mf"):
  565. base = filename[:-4]
  566. _expected_print_creators[(printer_id, base)] = created_by_id
  567. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  568. # Record registration time for TTL-based eviction
  569. _registered_at = time.monotonic()
  570. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  571. if filename.endswith(".3mf"):
  572. base = filename[:-4]
  573. _expected_print_registered_at[(printer_id, base)] = _registered_at
  574. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  575. logging.getLogger(__name__).info(
  576. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  577. )
  578. def _compute_run_filament_grams(
  579. status: str,
  580. archive_filament_used_grams: float | None,
  581. progress: float | int | None,
  582. usage_results: list[dict] | None,
  583. ) -> float | None:
  584. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  585. Priority for every status:
  586. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  587. weight delta — same source that drives "Total Consumed" on the
  588. Inventory page, so Stats and Inventory totals stay aligned).
  589. 2. For ``completed``: the slicer estimate (no tracker available, fall
  590. back to the canonical "this print used X" value).
  591. 3. For partial statuses: ``estimate * progress%``.
  592. 4. ``None`` if nothing is known.
  593. """
  594. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  595. if tracked_grams > 0:
  596. return round(tracked_grams, 1)
  597. if status == "completed":
  598. return archive_filament_used_grams
  599. if archive_filament_used_grams:
  600. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  601. if scale > 0:
  602. return round(archive_filament_used_grams * scale, 1)
  603. return None
  604. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  605. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  606. stored_ams_mapping = data.get("ams_mapping")
  607. if not stored_ams_mapping and archive_id:
  608. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  609. return stored_ams_mapping
  610. def _get_start_plate_id(archive_id: int | None) -> int | None:
  611. """Resolve plate_id for print start without consuming stored direct-Print state.
  612. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  613. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  614. read it back at print-start without popping (the entry is popped on print
  615. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  616. """
  617. if archive_id is None:
  618. return None
  619. return _print_plate_ids.get(archive_id)
  620. def _partial_progress_scale(progress: int | float | None) -> float:
  621. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  622. Used by every site that multiplies a "would-have-used" slicer estimate
  623. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  624. so the three sites in ``_background_notifications`` (and the per-plate
  625. override helper) can't drift apart on the coercion shape.
  626. """
  627. return max(0.0, min((progress or 0) / 100.0, 1.0))
  628. def _scope_notification_archive_data_to_plate(
  629. archive_data: dict,
  630. archive_file_path: str | None,
  631. plate_id: int | None,
  632. print_status: str,
  633. progress: int | float | None,
  634. base_dir: Path,
  635. ) -> dict:
  636. """Override summed-across-plates totals in ``archive_data`` with the values
  637. for ``plate_id`` so the completion notification reports what was actually
  638. printed, not the whole project (#1785).
  639. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  640. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  641. the archive card's "whole project" headline, wrong for the completion
  642. notification of a single-plate print. The queue UI already re-reads the
  643. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  644. notification payload (filament grams, time estimate, per-slot breakdown).
  645. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  646. no per-plate values — in every fail case the original ``archive_data`` is
  647. returned unchanged so the notification still sends.
  648. """
  649. if plate_id is None or not archive_file_path:
  650. return archive_data
  651. from backend.app.utils.threemf_tools import (
  652. extract_filament_usage_from_3mf,
  653. extract_print_time_from_3mf,
  654. )
  655. archive_path = base_dir / archive_file_path
  656. if not archive_path.exists():
  657. return archive_data
  658. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  659. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  660. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  661. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  662. if plate_time:
  663. archive_data["print_time_seconds"] = plate_time
  664. # Gate both the grams headline AND the per-slot breakdown on the same
  665. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  666. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  667. # to the project-level grams the archive columns already provide rather
  668. # than ship a project-level headline next to an all-zero per-plate
  669. # breakdown.
  670. if plate_grams > 0:
  671. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  672. archive_data["filament_slots"] = [
  673. {
  674. "slot_id": s.get("slot_id"),
  675. "used_g": round((s.get("used_g") or 0) * scale, 1),
  676. "type": s.get("type", ""),
  677. "color": s.get("color", ""),
  678. }
  679. for s in plate_slots
  680. ]
  681. return archive_data
  682. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  683. """Best-effort filament metadata from the MQTT print-start snapshot.
  684. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  685. file during print, see #1533) so the fallback PrintArchive still has
  686. enough filament info to support the inventory views and AMS-expansion
  687. planning the operator opens it for. Returns a dict with optional
  688. ``filament_type`` and ``filament_color`` keys in the same
  689. comma-separated format the 3MF extractor produces, so the rest of the
  690. codebase treats the fallback archive identically to a normal one.
  691. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  692. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  693. entries). When supplied, only the slots actually consumed by this
  694. print contribute. Without it the function falls back to every loaded
  695. AMS slot — less accurate but still useful.
  696. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  697. that the unit tests pass directly, AND the on_print_start callback
  698. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  699. bambu_mqtt service hands to main.py at runtime. The original
  700. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  701. handled the inner shape and silently returned ``{}`` for every real
  702. print start, leaving fallback archives' filament fields NULL — the
  703. exact regression the fix was meant to close. Reported with a log
  704. proving the AMS state was right there at
  705. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  706. """
  707. result: dict[str, str] = {}
  708. # Look at the on_print_start wrapper first, then the inner shape.
  709. raw_data = (data or {}).get("raw_data")
  710. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  711. if not isinstance(ams_root, dict):
  712. ams_root = (data or {}).get("ams") or {}
  713. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  714. if not isinstance(ams_units, list) or not ams_units:
  715. return result
  716. # Map global tray id (unit * 4 + tray) → (type, color).
  717. loaded: dict[int, tuple[str, str]] = {}
  718. for unit in ams_units:
  719. if not isinstance(unit, dict):
  720. continue
  721. try:
  722. unit_id = int(unit.get("id", 0))
  723. except (TypeError, ValueError):
  724. continue
  725. for tray in unit.get("tray") or []:
  726. if not isinstance(tray, dict):
  727. continue
  728. try:
  729. tray_id = int(tray.get("id", 0))
  730. except (TypeError, ValueError):
  731. continue
  732. ttype = (tray.get("tray_type") or "").strip()
  733. tcolor = (tray.get("tray_color") or "").strip().upper()
  734. if not ttype:
  735. continue # Empty / unloaded slot.
  736. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  737. if not loaded:
  738. return result
  739. if ams_mapping:
  740. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  741. filaments = [loaded[g] for g in used_ids if g in loaded]
  742. if not filaments:
  743. return result # Mapping points entirely at slots we have no data for.
  744. else:
  745. filaments = [loaded[g] for g in sorted(loaded.keys())]
  746. types_joined = ",".join(f[0] for f in filaments)
  747. colors_joined = ",".join(f[1] for f in filaments if f[1])
  748. # Column limits per backend/app/models/archive.py: filament_type=50,
  749. # filament_color=200.
  750. if types_joined:
  751. result["filament_type"] = types_joined[:50]
  752. if colors_joined:
  753. result["filament_color"] = colors_joined[:200]
  754. return result
  755. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  756. """Start a layer-timelapse session for *archive_id* when the printer has
  757. an external camera configured. Returns True if a session was started.
  758. Three call sites in on_print_start (expected-archive promotion, fallback
  759. archive creation, fresh-archive creation) used to inline this same
  760. if-block; the inline copies kept drifting (#1353 fixed only one of them
  761. on the first pass). Centralising the conditional + call here makes the
  762. contract testable in isolation and keeps the three sites locked in step.
  763. """
  764. if not (printer.external_camera_enabled and printer.external_camera_url):
  765. return False
  766. from backend.app.services.layer_timelapse import start_session
  767. start_session(
  768. printer_id,
  769. archive_id,
  770. printer.external_camera_url,
  771. printer.external_camera_type or "mjpeg",
  772. snapshot_url=printer.external_camera_snapshot_url,
  773. )
  774. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  775. return True
  776. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  777. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  778. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity.
  779. The short code used for the hms_errors.py lookup table is 'MMMM_EEEE' — module
  780. from attr bits 16-31, error from the numeric part of code. Falls back to the raw
  781. short code when no description is on file. Returns None for an empty list so
  782. callers can leave error_message unset.
  783. """
  784. if not hms_errors:
  785. return None
  786. from backend.app.services.hms_errors import get_error_description
  787. parts: list[str] = []
  788. for err in hms_errors:
  789. try:
  790. code_str = str(err.get("code", "")).replace("0x", "")
  791. error_num = int(code_str, 16) if code_str else 0
  792. module_num = (int(err.get("attr", 0)) >> 16) & 0xFFFF
  793. short_code = f"{module_num:04X}_{error_num:04X}"
  794. except (TypeError, ValueError):
  795. continue
  796. description = get_error_description(short_code)
  797. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  798. return "; ".join(parts) if parts else None
  799. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  800. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  801. print completes successfully. Gated to status=='completed': failed, cancelled
  802. and aborted prints do not count as usage. Caller is responsible for committing
  803. the session. No-op when the queue item has no linked library file (e.g. reprints
  804. from an archive). See #1008."""
  805. if queue_status != "completed" or item.library_file_id is None:
  806. return
  807. from backend.app.models.library import LibraryFile
  808. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  809. if lib_file is None:
  810. return
  811. lib_file.print_count = (lib_file.print_count or 0) + 1
  812. lib_file.last_printed_at = datetime.now(timezone.utc)
  813. def mark_printer_stopped_by_user(printer_id: int) -> None:
  814. """Mark that the active print on this printer was stopped by the user from the queue UI.
  815. When on_print_complete fires with status 'failed' for a printer in this set we
  816. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  817. rather than a 'print failed' notification.
  818. """
  819. _user_stopped_printers.add(printer_id)
  820. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  821. _last_status_broadcast: dict[int, str] = {}
  822. # Track printers where we've updated nozzle_count
  823. _nozzle_count_updated: set[int] = set()
  824. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  825. """Wait the debounce window then fire `on_printer_offline` if the printer
  826. is still offline.
  827. Scheduled by `on_printer_status_change` on the connected → disconnected
  828. edge (#1752). Cancelled by the same handler if the printer reconnects
  829. before the window elapses, so a single MQTT blip + recovery doesn't
  830. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  831. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  832. route through the same status-change callback, so this covers both.
  833. """
  834. logger = logging.getLogger(__name__)
  835. try:
  836. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  837. still_offline = not printer_manager.is_connected(printer_id)
  838. logger.info(
  839. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  840. printer_id,
  841. still_offline,
  842. )
  843. if not still_offline:
  844. return
  845. async with async_session() as db:
  846. from backend.app.models.printer import Printer
  847. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  848. printer = result.scalar_one_or_none()
  849. if not printer:
  850. logger.warning(
  851. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  852. printer_id,
  853. )
  854. return
  855. logger.info(
  856. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  857. printer_id,
  858. printer.name,
  859. )
  860. await notification_service.on_printer_offline(printer_id, printer.name, db)
  861. except asyncio.CancelledError:
  862. raise
  863. except Exception as e:
  864. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  865. finally:
  866. _printer_offline_notify_tasks.pop(printer_id, None)
  867. async def on_printer_status_change(printer_id: int, state: PrinterState):
  868. """Handle printer status changes - broadcast via WebSocket."""
  869. # Connected-edge reconciliation (#1542 follow-up). When the printer
  870. # transitions disconnected → connected — which covers both Bambuddy
  871. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  872. # `reconcile_stale_active_prints` exactly once for this connection so
  873. # any archive still in `status="printing"` that can't actually be
  874. # running anymore (printer IDLE / different subtask / empty subtask)
  875. # gets a synthesised PRINT COMPLETE. Without this, a print that
  876. # finished during a disconnect window + a smart-plug power cycle
  877. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  878. # next boot. Reconciliation runs concurrently — it must not block the
  879. # WebSocket dedup / broadcast logic below, and the connected edge is
  880. # marked True BEFORE the await so concurrent status updates inside
  881. # the same connection don't re-trigger reconciliation.
  882. #
  883. # Wait for a real push_status before reconciling (#1679): MQTT
  884. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  885. # the connection, BEFORE `_request_push_all` round-trips. At that
  886. # instant the `PrinterState` is still on construction defaults — most
  887. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  888. # If reconcile spawns here, every in-flight archive falls through to
  889. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  890. # creates a duplicate archive on the real PRINT COMPLETE and
  891. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  892. # keeps the #1542 mechanism intact: once the first real push_status
  893. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  894. # fires again with the flag still False — reconcile then runs against
  895. # actual evidence.
  896. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  897. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  898. _printer_reconciled_since_connect[printer_id] = True
  899. spawn_background_task(
  900. reconcile_stale_active_prints(printer_id),
  901. name=f"reconcile-stale-prints-{printer_id}",
  902. )
  903. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  904. # Re-arm so the next reconnect triggers reconciliation again.
  905. _printer_reconciled_since_connect[printer_id] = False
  906. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  907. # connected → disconnected. The "back online" channel is already covered
  908. # by the print-failure notification (firmware reports gcode_state=FAILED
  909. # on reconnect of an interrupted print), so we don't add a symmetric
  910. # online event here.
  911. prev_connected = _printer_last_connected.get(printer_id)
  912. _printer_last_connected[printer_id] = state.connected
  913. if prev_connected is True and not state.connected:
  914. existing = _printer_offline_notify_tasks.get(printer_id)
  915. if existing is None or existing.done():
  916. logging.getLogger(__name__).info(
  917. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  918. printer_id,
  919. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  920. )
  921. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  922. _maybe_notify_printer_offline(printer_id),
  923. name=f"printer-offline-notify-{printer_id}",
  924. )
  925. elif state.connected:
  926. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  927. if pending is not None and not pending.done():
  928. logging.getLogger(__name__).info(
  929. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  930. printer_id,
  931. )
  932. pending.cancel()
  933. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  934. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  935. temps = state.temperatures or {}
  936. nozzle_temp = round(temps.get("nozzle", 0))
  937. bed_temp = round(temps.get("bed", 0))
  938. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  939. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  940. # Auto-detect dual-nozzle printers from MQTT temperature data
  941. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  942. _nozzle_count_updated.add(printer_id)
  943. # Update nozzle_count in database
  944. async with async_session() as db:
  945. from backend.app.models.printer import Printer
  946. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  947. printer = result.scalar_one_or_none()
  948. if printer and printer.nozzle_count != 2:
  949. printer.nozzle_count = 2
  950. await db.commit()
  951. logging.getLogger(__name__).info(
  952. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  953. )
  954. # Include target temps for heating phase detection
  955. bed_target = round(temps.get("bed_target", 0))
  956. nozzle_target = round(temps.get("nozzle_target", 0))
  957. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  958. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  959. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  960. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  961. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  962. ams_tray_key = (
  963. tuple(
  964. (t.get("id"), t.get("tray_type", ""), t.get("state"))
  965. for a in (state.raw_data.get("ams") or [])
  966. for t in a.get("tray", [])
  967. )
  968. if state.raw_data
  969. else ()
  970. )
  971. status_key = (
  972. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  973. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  974. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  975. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  976. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  977. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}"
  978. )
  979. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  980. try:
  981. printer_info = printer_manager.get_printer(printer_id)
  982. if printer_info:
  983. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  984. except Exception:
  985. pass # Don't fail status callback if MQTT fails
  986. if _last_status_broadcast.get(printer_id) == status_key:
  987. return # No change, skip WebSocket broadcast
  988. _last_status_broadcast[printer_id] = status_key
  989. # Check for progress milestone notifications (25%, 50%, 75%)
  990. progress = state.progress or 0
  991. is_printing = state.state in ("RUNNING", "PRINTING")
  992. if is_printing and progress > 0:
  993. # Determine which milestone we've reached
  994. current_milestone = 0
  995. if progress >= 75:
  996. current_milestone = 75
  997. elif progress >= 50:
  998. current_milestone = 50
  999. elif progress >= 25:
  1000. current_milestone = 25
  1001. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1002. # If we've crossed a new milestone, send notification
  1003. if current_milestone > last_milestone:
  1004. _last_progress_milestone[printer_id] = current_milestone
  1005. try:
  1006. async with async_session() as db:
  1007. from backend.app.models.printer import Printer
  1008. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1009. printer = result.scalar_one_or_none()
  1010. printer_name = printer.name if printer else f"Printer {printer_id}"
  1011. filename = state.subtask_name or state.gcode_file or "Unknown"
  1012. # remaining_time is in minutes, convert to seconds for notification
  1013. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1014. # Capture camera snapshot for notification image attachment
  1015. image_data = await _capture_snapshot_for_notification(
  1016. printer_id, printer, logging.getLogger(__name__)
  1017. )
  1018. await notification_service.on_print_progress(
  1019. printer_id,
  1020. printer_name,
  1021. filename,
  1022. current_milestone,
  1023. db,
  1024. remaining_time_seconds,
  1025. image_data=image_data,
  1026. )
  1027. except Exception as e:
  1028. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1029. elif progress < 5:
  1030. # Reset milestone tracking when print restarts or new print begins
  1031. _last_progress_milestone[printer_id] = 0
  1032. _first_layer_notified[printer_id] = False
  1033. # HMS error codes that should not trigger notifications even though they
  1034. # have known descriptions (e.g. user-initiated actions, not real errors).
  1035. _HMS_NOTIFICATION_SUPPRESS = {
  1036. "0500_400E", # Printing was cancelled (user action, not an error)
  1037. }
  1038. # Check for new HMS errors and send notifications
  1039. current_hms_errors = getattr(state, "hms_errors", []) or []
  1040. if current_hms_errors:
  1041. # Build set of current error codes (using attr for uniqueness)
  1042. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1043. previously_notified = _notified_hms_errors.get(printer_id, set())
  1044. # Find new errors that haven't been notified yet
  1045. new_error_codes = current_error_codes - previously_notified
  1046. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1047. _notified_hms_errors[printer_id] = current_error_codes
  1048. _hms_last_seen[printer_id] = time.time()
  1049. if new_error_codes:
  1050. # Get the actual new errors for the notification
  1051. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1052. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1053. try:
  1054. async with async_session() as db:
  1055. from backend.app.models.printer import Printer
  1056. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1057. printer = result.scalar_one_or_none()
  1058. printer_name = printer.name if printer else f"Printer {printer_id}"
  1059. # Format error details for notification
  1060. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1061. module_names = {
  1062. 0x03: "Print/Task",
  1063. 0x05: "Nozzle/Extruder",
  1064. 0x07: "AMS/Filament",
  1065. 0x0C: "Motion Controller",
  1066. 0x12: "Chamber",
  1067. }
  1068. from backend.app.services.hms_errors import get_error_description
  1069. # Capture camera snapshot once for all error notifications
  1070. error_image_data = await _capture_snapshot_for_notification(
  1071. printer_id, printer, logging.getLogger(__name__)
  1072. )
  1073. sent_count = 0
  1074. for error in new_errors:
  1075. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1076. # Build short code like "0700_8010"
  1077. # Mask to 16 bits to handle printers that send larger values
  1078. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1079. error_code_masked = error_code_int & 0xFFFF
  1080. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1081. # Only notify for errors with known descriptions — printers
  1082. # send many undocumented/phantom codes that aren't real errors.
  1083. description = get_error_description(short_code)
  1084. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1085. continue
  1086. error_type = f"{module_name} Error"
  1087. error_detail = description
  1088. await notification_service.on_printer_error(
  1089. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1090. )
  1091. sent_count += 1
  1092. if sent_count:
  1093. logging.getLogger(__name__).info(
  1094. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1095. )
  1096. # Also publish to MQTT relay
  1097. printer_info = printer_manager.get_printer(printer_id)
  1098. if printer_info:
  1099. errors_data = [
  1100. {
  1101. "code": e.code,
  1102. "attr": e.attr,
  1103. "module": e.module,
  1104. "severity": e.severity,
  1105. }
  1106. for e in new_errors
  1107. ]
  1108. await mqtt_relay.on_printer_error(
  1109. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1110. )
  1111. except Exception as e:
  1112. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1113. else:
  1114. # No HMS errors — only clear tracking after a grace period to prevent
  1115. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1116. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1117. # on/off every few seconds as conditions fluctuate around thresholds.
  1118. if printer_id in _notified_hms_errors:
  1119. last_seen = _hms_last_seen.get(printer_id, 0)
  1120. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1121. _notified_hms_errors.pop(printer_id, None)
  1122. _hms_last_seen.pop(printer_id, None)
  1123. await ws_manager.send_printer_status(
  1124. printer_id,
  1125. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  1126. )
  1127. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1128. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1129. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1130. async def on_ams_change(printer_id: int, ams_data: list):
  1131. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1132. logger = logging.getLogger(__name__)
  1133. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1134. # on_print_complete may pop _active_sessions during our awaits (#880).
  1135. from backend.app.services.usage_tracker import _active_sessions
  1136. _print_active = printer_id in _active_sessions
  1137. # MQTT relay - publish AMS change
  1138. try:
  1139. printer_info = printer_manager.get_printer(printer_id)
  1140. if printer_info:
  1141. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1142. except Exception:
  1143. pass # Don't fail AMS callback if MQTT fails
  1144. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1145. # This ensures frontend gets immediate updates when AMS slots are configured
  1146. try:
  1147. state = printer_manager.get_status(printer_id)
  1148. if state:
  1149. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1150. await ws_manager.send_printer_status(
  1151. printer_id,
  1152. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  1153. )
  1154. except Exception as e:
  1155. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1156. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1157. # Auto-unlink spool assignments with stale fingerprints
  1158. try:
  1159. async with async_session() as db:
  1160. from sqlalchemy.orm import selectinload
  1161. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1162. from backend.app.models.spool import Spool as _Spool
  1163. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1164. result = await db.execute(
  1165. select(SA)
  1166. .where(SA.printer_id == printer_id)
  1167. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1168. )
  1169. stale = []
  1170. for assignment in result.scalars().all():
  1171. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1172. if assignment.ams_id == 255:
  1173. ps = printer_manager.get_status(printer_id)
  1174. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1175. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1176. current_tray = None
  1177. for vt in vt_tray_raw:
  1178. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1179. current_tray = vt
  1180. break
  1181. if not current_tray:
  1182. # vt_tray data may not have arrived yet — keep assignment
  1183. continue
  1184. else:
  1185. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1186. if not current_tray:
  1187. logger.info(
  1188. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1189. assignment.spool_id,
  1190. assignment.ams_id,
  1191. assignment.tray_id,
  1192. )
  1193. stale.append(assignment) # Slot empty
  1194. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1195. # A Bambu Lab spool is in this slot — check if it's the same spool
  1196. # that's currently assigned. If yes, keep the assignment (avoids
  1197. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1198. # the printer's filament preset on every startup).
  1199. tray_uuid = current_tray.get("tray_uuid", "")
  1200. tag_uid = current_tray.get("tag_uid", "")
  1201. spool = assignment.spool
  1202. spool_matches = False
  1203. if spool:
  1204. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1205. spool.tag_uid
  1206. and tag_uid
  1207. and tag_uid != "0000000000000000"
  1208. and spool.tag_uid.upper() == tag_uid.upper()
  1209. ):
  1210. spool_matches = True
  1211. if spool_matches:
  1212. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1213. cur_color = current_tray.get("tray_color", "")
  1214. cur_type = current_tray.get("tray_type", "")
  1215. fp_color = assignment.fingerprint_color or ""
  1216. fp_type = assignment.fingerprint_type or ""
  1217. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1218. assignment.fingerprint_color = cur_color
  1219. assignment.fingerprint_type = cur_type
  1220. logger.debug(
  1221. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1222. assignment.spool_id,
  1223. assignment.ams_id,
  1224. assignment.tray_id,
  1225. )
  1226. continue
  1227. # Different BL spool or unrecognized — unlink so auto-assign can match
  1228. logger.info(
  1229. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1230. assignment.spool_id,
  1231. assignment.ams_id,
  1232. assignment.tray_id,
  1233. tray_uuid,
  1234. )
  1235. stale.append(assignment)
  1236. else:
  1237. cur_color = current_tray.get("tray_color", "")
  1238. cur_type = current_tray.get("tray_type", "")
  1239. cur_state = current_tray.get("state")
  1240. fp_color = assignment.fingerprint_color or ""
  1241. fp_type = assignment.fingerprint_type or ""
  1242. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1243. # the slot was empty when the user pre-assigned via SpoolBuddy
  1244. # (the firmware drops ams_filament_setting on empty slots, so
  1245. # MQTT was deferred). The moment any filament gets inserted
  1246. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1247. # reconfigured spool — fire the deferred configuration.
  1248. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1249. # extruder" code) OR, on firmwares that don't use the state
  1250. # enum meaningfully, a non-empty tray_type when state is
  1251. # NOT one of the firmware's explicit empty signals (9, 10).
  1252. # state-only was wrong for firmwares that never set 11 — A1
  1253. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1254. # always report state=3 — so the replay never fired for them
  1255. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1256. # explicit "empty" signals authoritative over any stale
  1257. # tray_type that might survive the relay's auto-clearing.
  1258. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1259. if not fp_type.strip() and loaded and assignment.spool:
  1260. try:
  1261. from backend.app.api.routes.inventory import (
  1262. apply_spool_to_slot_via_mqtt,
  1263. )
  1264. await apply_spool_to_slot_via_mqtt(
  1265. db=db,
  1266. current_user=None,
  1267. spool=assignment.spool,
  1268. printer_id=printer_id,
  1269. ams_id=assignment.ams_id,
  1270. tray_id=assignment.tray_id,
  1271. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1272. current_tray_type=cur_type,
  1273. )
  1274. logger.info(
  1275. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1276. assignment.spool_id,
  1277. printer_id,
  1278. assignment.ams_id,
  1279. assignment.tray_id,
  1280. )
  1281. except Exception:
  1282. logger.exception(
  1283. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1284. assignment.spool_id,
  1285. printer_id,
  1286. assignment.ams_id,
  1287. assignment.tray_id,
  1288. )
  1289. assignment.fingerprint_color = cur_color
  1290. assignment.fingerprint_type = cur_type
  1291. continue
  1292. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1293. # Fingerprint mismatch — but check if tray now matches the
  1294. # assigned spool (e.g. auto-configure changed the tray).
  1295. spool = assignment.spool
  1296. if spool:
  1297. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1298. spool_type = (spool.material or "").upper()
  1299. if _colors_similar(cur_color, spool_color) and cur_type.upper() == spool_type:
  1300. logger.info(
  1301. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1302. assignment.spool_id,
  1303. assignment.ams_id,
  1304. assignment.tray_id,
  1305. )
  1306. assignment.fingerprint_color = cur_color
  1307. assignment.fingerprint_type = cur_type
  1308. continue
  1309. logger.info(
  1310. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1311. assignment.spool_id,
  1312. assignment.ams_id,
  1313. assignment.tray_id,
  1314. cur_color,
  1315. cur_type,
  1316. fp_color,
  1317. fp_type,
  1318. spool.rgba if spool else "?",
  1319. spool.material if spool else "?",
  1320. )
  1321. stale.append(assignment) # Spool changed
  1322. for a in stale:
  1323. await db.delete(a)
  1324. if stale:
  1325. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  1326. # Commit any changes (stale deletions and/or fingerprint updates)
  1327. await db.commit()
  1328. except Exception as e:
  1329. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  1330. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  1331. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  1332. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  1333. # "no existing assignment" for the same (printer, ams, tray) and race to
  1334. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  1335. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  1336. # bug stayed latent there. See _ams_assignment_locks comment for details.
  1337. try:
  1338. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1339. from backend.app.api.routes.settings import get_setting
  1340. from backend.app.models.spool import Spool
  1341. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1342. from backend.app.services.spool_tag_matcher import (
  1343. auto_assign_spool,
  1344. create_spool_from_tray,
  1345. find_matching_untagged_spool,
  1346. get_spool_by_tag,
  1347. is_bambu_tag,
  1348. is_valid_tag,
  1349. link_tag_to_inventory_spool,
  1350. )
  1351. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1352. if not _spoolman_on or _spoolman_on.lower() != "true":
  1353. for ams_unit in ams_data:
  1354. if not isinstance(ams_unit, dict):
  1355. continue
  1356. ams_id = int(ams_unit.get("id", 0))
  1357. for tray in ams_unit.get("tray", []):
  1358. if not isinstance(tray, dict):
  1359. continue
  1360. tray_id = int(tray.get("id", 0))
  1361. tag_uid = tray.get("tag_uid", "")
  1362. tray_uuid = tray.get("tray_uuid", "")
  1363. tray_info_idx = tray.get("tray_info_idx", "")
  1364. if not tray.get("tray_type"):
  1365. continue # Empty slot
  1366. # Check if assignment already exists for this slot
  1367. existing = await db.execute(
  1368. select(SA)
  1369. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  1370. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  1371. )
  1372. existing_assignment = existing.scalar_one_or_none()
  1373. if existing_assignment:
  1374. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  1375. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  1376. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  1377. # Skip during active prints: the usage tracker handles deduction
  1378. # precisely via 3MF data on print completion. Without this guard the
  1379. # AMS remain% SET and the usage tracker ADD both fire from the same
  1380. # MQTT message, doubling the deduction (#880).
  1381. if _print_active:
  1382. continue
  1383. remain_raw = tray.get("remain")
  1384. if (
  1385. remain_raw is not None
  1386. and existing_assignment.spool
  1387. and not existing_assignment.spool.weight_locked
  1388. ):
  1389. try:
  1390. remain_val = int(remain_raw)
  1391. except (TypeError, ValueError):
  1392. remain_val = -1
  1393. if 1 <= remain_val <= 100:
  1394. lw = existing_assignment.spool.label_weight or 1000
  1395. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  1396. current_used = existing_assignment.spool.weight_used or 0
  1397. if new_used > current_used + 1:
  1398. logger.info(
  1399. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  1400. existing_assignment.spool_id,
  1401. current_used,
  1402. new_used,
  1403. remain_val,
  1404. )
  1405. existing_assignment.spool.weight_used = new_used
  1406. await db.commit()
  1407. # Re-apply stored K-profile when the live tray's
  1408. # cali_idx drifted from the spool's stored profile.
  1409. # This catches "reset slot → re-read" and any other
  1410. # path where the firmware loses the user's K-profile
  1411. # selection while the SpoolAssignment row persists.
  1412. # Per the maintainer's rule: any time a spool tag is
  1413. # identified and matches inventory, the slot must be
  1414. # configured with the spool's stored settings. Without
  1415. # this block the existing-assignment branch only ran
  1416. # weight-sync and let the firmware-default cali_idx win.
  1417. try:
  1418. spool = existing_assignment.spool
  1419. if (
  1420. spool is not None
  1421. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  1422. and spool.k_profiles
  1423. ):
  1424. state = printer_manager.get_status(printer_id)
  1425. nozzle_diameter = "0.4"
  1426. if state and state.nozzles:
  1427. nd = state.nozzles[0].nozzle_diameter
  1428. if nd:
  1429. nozzle_diameter = nd
  1430. slot_extruder: int | None = None
  1431. if state and state.ams_extruder_map:
  1432. if ams_id == 255:
  1433. slot_extruder = 1 - tray_id
  1434. else:
  1435. slot_extruder = state.ams_extruder_map.get(str(ams_id))
  1436. # Prefer exact extruder match, fall back to
  1437. # extruder-agnostic kp for the same printer +
  1438. # nozzle. Avoids hard-skipping when the AMS is
  1439. # mapped differently than at calibration time.
  1440. matching_kp = None
  1441. fallback_kp = None
  1442. for kp in spool.k_profiles:
  1443. if (
  1444. kp.printer_id != printer_id
  1445. or kp.nozzle_diameter != nozzle_diameter
  1446. or kp.cali_idx is None
  1447. ):
  1448. continue
  1449. if (
  1450. slot_extruder is not None
  1451. and kp.extruder is not None
  1452. and kp.extruder == slot_extruder
  1453. ):
  1454. matching_kp = kp
  1455. break
  1456. if fallback_kp is None:
  1457. fallback_kp = kp
  1458. chosen_kp = matching_kp or fallback_kp
  1459. if chosen_kp is not None:
  1460. live_cali_idx = tray.get("cali_idx")
  1461. # Only fire MQTT when the printer's live
  1462. # cali_idx differs from the stored value.
  1463. # Avoids spamming the broker on every
  1464. # MQTT push during steady-state operation.
  1465. if live_cali_idx != chosen_kp.cali_idx:
  1466. client = printer_manager.get_client(printer_id)
  1467. if client:
  1468. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  1469. client.extrusion_cali_sel(
  1470. ams_id=ams_id,
  1471. tray_id=tray_id,
  1472. cali_idx=chosen_kp.cali_idx,
  1473. filament_id=cali_filament_id,
  1474. nozzle_diameter=nozzle_diameter,
  1475. )
  1476. logger.info(
  1477. "Re-applied K-profile cali_idx=%d for spool %d "
  1478. "on printer %d AMS%d-T%d (live=%s drift detected)",
  1479. chosen_kp.cali_idx,
  1480. spool.id,
  1481. printer_id,
  1482. ams_id,
  1483. tray_id,
  1484. live_cali_idx,
  1485. )
  1486. except Exception:
  1487. logger.exception(
  1488. "K-profile re-apply failed for printer %d AMS%d-T%d",
  1489. printer_id,
  1490. ams_id,
  1491. tray_id,
  1492. )
  1493. continue
  1494. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  1495. # BL spool with RFID tag: auto-match → inventory match → auto-create
  1496. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  1497. if not spool:
  1498. # Try matching an untagged inventory spool (same material/color)
  1499. spool = await find_matching_untagged_spool(db, tray)
  1500. if spool:
  1501. await link_tag_to_inventory_spool(db, spool, tray)
  1502. else:
  1503. spool = await create_spool_from_tray(db, tray)
  1504. await auto_assign_spool(
  1505. printer_id,
  1506. ams_id,
  1507. tray_id,
  1508. spool,
  1509. printer_manager,
  1510. db,
  1511. tray_info_idx=tray_info_idx,
  1512. )
  1513. await db.commit()
  1514. await ws_manager.broadcast(
  1515. {
  1516. "type": "spool_auto_assigned",
  1517. "printer_id": printer_id,
  1518. "ams_id": ams_id,
  1519. "tray_id": tray_id,
  1520. "spool_id": spool.id,
  1521. }
  1522. )
  1523. logger.info(
  1524. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  1525. spool.id,
  1526. printer_id,
  1527. ams_id,
  1528. tray_id,
  1529. )
  1530. elif is_valid_tag(tag_uid, tray_uuid):
  1531. # Non-BL spool with some tag — let user choose
  1532. await ws_manager.broadcast(
  1533. {
  1534. "type": "unknown_tag",
  1535. "printer_id": printer_id,
  1536. "ams_id": ams_id,
  1537. "tray_id": tray_id,
  1538. "tag_uid": tag_uid,
  1539. "tray_uuid": tray_uuid,
  1540. }
  1541. )
  1542. else:
  1543. # No tag at all — let user choose from inventory
  1544. await ws_manager.broadcast(
  1545. {
  1546. "type": "unknown_tag",
  1547. "printer_id": printer_id,
  1548. "ams_id": ams_id,
  1549. "tray_id": tray_id,
  1550. "tag_uid": "",
  1551. "tray_uuid": "",
  1552. }
  1553. )
  1554. except Exception as e:
  1555. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  1556. try:
  1557. async with async_session() as db:
  1558. from backend.app.api.routes.settings import get_setting
  1559. from backend.app.models.printer import Printer
  1560. # Check if Spoolman is enabled
  1561. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1562. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  1563. return
  1564. # Check sync mode
  1565. sync_mode = await get_setting(db, "spoolman_sync_mode")
  1566. if sync_mode and sync_mode != "auto":
  1567. return # Only sync on auto mode
  1568. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  1569. # always owned by per-print tracking, never by AMS auto-sync. The
  1570. # setting is still read by the settings UI for backwards compat but
  1571. # has no effect on the sync path here.
  1572. # Get Spoolman URL
  1573. spoolman_url = await get_setting(db, "spoolman_url")
  1574. if not spoolman_url:
  1575. return
  1576. # Get or create Spoolman client
  1577. client = await get_spoolman_client()
  1578. if not client:
  1579. try:
  1580. client = await init_spoolman_client(spoolman_url)
  1581. except ValueError as exc:
  1582. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  1583. return
  1584. # Check if Spoolman is reachable
  1585. if not await client.health_check():
  1586. logger.warning("Spoolman not reachable at %s", spoolman_url)
  1587. return
  1588. # Get printer name for location
  1589. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1590. printer = result.scalar_one_or_none()
  1591. printer_name = printer.name if printer else f"Printer {printer_id}"
  1592. # OPTIMIZATION: Fetch all spools once before processing trays
  1593. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  1594. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  1595. try:
  1596. cached_spools = await client.get_spools()
  1597. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  1598. except Exception as e:
  1599. logger.error(
  1600. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  1601. printer_id,
  1602. e,
  1603. )
  1604. return
  1605. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  1606. from sqlalchemy.orm import selectinload
  1607. from backend.app.models.spool_assignment import SpoolAssignment
  1608. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  1609. inventory_weights: dict[tuple[int, int], float] = {}
  1610. try:
  1611. assign_result = await db.execute(
  1612. select(SpoolAssignment)
  1613. .options(selectinload(SpoolAssignment.spool))
  1614. .where(SpoolAssignment.printer_id == printer_id)
  1615. )
  1616. for assignment in assign_result.scalars().all():
  1617. spool = assignment.spool
  1618. if spool and spool.label_weight > 0:
  1619. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  1620. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  1621. except Exception as e:
  1622. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  1623. # Load existing Spoolman slot assignments for the no-RFID fallback path
  1624. spoolman_slot_map: dict[tuple[int, int], int] = {}
  1625. try:
  1626. slot_result = await db.execute(
  1627. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  1628. )
  1629. for slot in slot_result.scalars().all():
  1630. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  1631. except Exception as e:
  1632. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  1633. # Sync each AMS tray and collect slot changes for DB persistence
  1634. synced = 0
  1635. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  1636. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  1637. for ams_unit in ams_data:
  1638. if not isinstance(ams_unit, dict):
  1639. continue
  1640. ams_id = int(ams_unit.get("id", 0))
  1641. trays = ams_unit.get("tray", [])
  1642. for tray_data in trays:
  1643. if not isinstance(tray_data, dict):
  1644. continue
  1645. tray_id_raw = int(tray_data.get("id", 0))
  1646. tray = client.parse_ams_tray(ams_id, tray_data)
  1647. if not tray:
  1648. # Empty tray slot — record for local assignment cleanup
  1649. empty_slots.append((ams_id, tray_id_raw))
  1650. continue
  1651. spool_tag = (
  1652. tray.tray_uuid
  1653. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  1654. else tray.tag_uid
  1655. )
  1656. # Provide the hint only when no RFID is available
  1657. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  1658. try:
  1659. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  1660. result = await client.sync_ams_tray(
  1661. tray,
  1662. printer_name,
  1663. # Per-print tracking is the only weight writer (#1119).
  1664. # AMS auto-sync still maintains spool metadata / slot
  1665. # assignments but no longer touches remaining_weight.
  1666. disable_weight_sync=True,
  1667. cached_spools=cached_spools,
  1668. inventory_remaining=inv_remaining,
  1669. spoolman_spool_id_hint=hint,
  1670. )
  1671. if result:
  1672. synced += 1
  1673. if result.get("id"):
  1674. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  1675. # If a new spool was created, add it to the cache
  1676. # so subsequent trays can find it if they reference the same tag
  1677. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  1678. if not spool_exists:
  1679. cached_spools.append(result)
  1680. logger.debug(
  1681. "[Printer %s] Added newly created spool %s to cache",
  1682. printer_id,
  1683. result["id"],
  1684. )
  1685. # Reconcile slot_preset_mappings (the same row internal
  1686. # mode keeps in sync via inventory + spool_tag_matcher).
  1687. # Without this the slot card surfaces the previous spool's
  1688. # preset name — same bug shape, different inventory mode.
  1689. from backend.app.services.slot_preset_writer import (
  1690. upsert_slot_preset_for_spoolman_spool,
  1691. )
  1692. await upsert_slot_preset_for_spoolman_spool(
  1693. db=db,
  1694. spoolman_spool=result,
  1695. tray_info_idx=tray.tray_info_idx or "",
  1696. tray_sub_brands=tray.tray_sub_brands or "",
  1697. tray_type=tray.tray_type or "",
  1698. printer_id=printer_id,
  1699. ams_id=ams_id,
  1700. tray_id=tray.tray_id,
  1701. )
  1702. except Exception as e:
  1703. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  1704. if synced > 0:
  1705. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  1706. # Persist slot assignment changes to the local table
  1707. if slot_changes or empty_slots:
  1708. try:
  1709. for ams_id, tray_id, spool_id in slot_changes:
  1710. await db.execute(
  1711. text(
  1712. "INSERT INTO spoolman_slot_assignments"
  1713. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  1714. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  1715. " ON CONFLICT(printer_id, ams_id, tray_id)"
  1716. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  1717. ),
  1718. {
  1719. "printer_id": printer_id,
  1720. "ams_id": ams_id,
  1721. "tray_id": tray_id,
  1722. "spool_id": spool_id,
  1723. },
  1724. )
  1725. for ams_id, tray_id in empty_slots:
  1726. await db.execute(
  1727. delete(SpoolmanSlotAssignment).where(
  1728. SpoolmanSlotAssignment.printer_id == printer_id,
  1729. SpoolmanSlotAssignment.ams_id == ams_id,
  1730. SpoolmanSlotAssignment.tray_id == tray_id,
  1731. )
  1732. )
  1733. await db.commit()
  1734. except Exception as e:
  1735. await db.rollback()
  1736. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  1737. except Exception as e:
  1738. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  1739. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  1740. """Capture a camera snapshot for notification image attachment.
  1741. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  1742. Uses: external camera > buffered frame > fresh capture.
  1743. """
  1744. if not printer:
  1745. return None
  1746. try:
  1747. from backend.app.api.routes.settings import get_setting
  1748. async with async_session() as db:
  1749. capture_enabled = await get_setting(db, "capture_finish_photo")
  1750. if capture_enabled is not None and capture_enabled.lower() != "true":
  1751. return None
  1752. # Try external camera first
  1753. if printer.external_camera_enabled and printer.external_camera_url:
  1754. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  1755. from backend.app.services.external_camera import capture_frame
  1756. frame_data = await capture_frame(
  1757. printer.external_camera_url,
  1758. printer.external_camera_type or "mjpeg",
  1759. snapshot_url=printer.external_camera_snapshot_url,
  1760. )
  1761. if frame_data and len(frame_data) <= 2_500_000:
  1762. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  1763. return _apply_camera_rotation(frame_data, printer, logger)
  1764. # Try buffered frame from active stream
  1765. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1766. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1767. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  1768. buffered_frame = get_buffered_frame(printer_id)
  1769. if (active_for_printer or active_chamber) and buffered_frame:
  1770. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  1771. if len(buffered_frame) <= 2_500_000:
  1772. return _apply_camera_rotation(buffered_frame, printer, logger)
  1773. # Fresh capture from printer camera
  1774. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  1775. from backend.app.services.camera import capture_camera_frame_bytes
  1776. frame_data = await capture_camera_frame_bytes(
  1777. printer.ip_address, printer.access_code, printer.model, timeout=15
  1778. )
  1779. if frame_data and len(frame_data) <= 2_500_000:
  1780. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  1781. return _apply_camera_rotation(frame_data, printer, logger)
  1782. except Exception as e:
  1783. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  1784. return None
  1785. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  1786. """Apply camera rotation to snapshot image if configured."""
  1787. rotation = getattr(printer, "camera_rotation", 0)
  1788. if not rotation or rotation == 0:
  1789. return image_data
  1790. try:
  1791. from io import BytesIO
  1792. from PIL import Image
  1793. img = Image.open(BytesIO(image_data))
  1794. # PIL rotate is counter-clockwise, so negate for clockwise rotation
  1795. img = img.rotate(-rotation, expand=True)
  1796. buf = BytesIO()
  1797. img.save(buf, format="JPEG", quality=90)
  1798. rotated = buf.getvalue()
  1799. logger.info("[SNAPSHOT] Applied %d° rotation: %s → %s bytes", rotation, len(image_data), len(rotated))
  1800. return rotated
  1801. except Exception as e:
  1802. logger.warning("[SNAPSHOT] Failed to apply rotation: %s", e)
  1803. return image_data
  1804. async def _send_print_start_notification(
  1805. printer_id: int,
  1806. data: dict,
  1807. archive_data: dict | None = None,
  1808. logger=None,
  1809. ):
  1810. """Helper to send print start notification with optional archive data."""
  1811. if logger is None:
  1812. logger = logging.getLogger(__name__)
  1813. try:
  1814. async with async_session() as db:
  1815. from backend.app.models.printer import Printer
  1816. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1817. printer = result.scalar_one_or_none()
  1818. printer_name = printer.name if printer else f"Printer {printer_id}"
  1819. # Capture camera snapshot for notification image attachment
  1820. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  1821. if image_data:
  1822. if archive_data is None:
  1823. archive_data = {}
  1824. archive_data["image_data"] = image_data
  1825. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  1826. # Send user-specific email notification for print start
  1827. if archive_data and archive_data.get("created_by_id"):
  1828. await notification_service.send_user_print_email(
  1829. event_type="user_print_start",
  1830. created_by_id=archive_data["created_by_id"],
  1831. printer_name=printer_name,
  1832. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  1833. db=db,
  1834. )
  1835. except Exception as e:
  1836. logger.warning("Notification on_print_start failed: %s", e)
  1837. async def _dispatch_user_print_email(
  1838. status: str,
  1839. created_by_id: int | None,
  1840. printer_name: str,
  1841. filename: str,
  1842. db,
  1843. ) -> None:
  1844. """Send a user-specific print-completion email based on print status.
  1845. Maps the normalised print status to the correct event type and delegates
  1846. to :meth:`NotificationService.send_user_print_email`. A single helper
  1847. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  1848. "stopped"`` dispatch block at every call site.
  1849. Does nothing if *created_by_id* is ``None``.
  1850. """
  1851. if created_by_id is None:
  1852. return
  1853. if status == "completed":
  1854. event_type = "user_print_complete"
  1855. elif status == "failed":
  1856. event_type = "user_print_failed"
  1857. elif status in ("stopped", "aborted", "cancelled"):
  1858. event_type = "user_print_stopped"
  1859. else:
  1860. return
  1861. await notification_service.send_user_print_email(
  1862. event_type=event_type,
  1863. created_by_id=created_by_id,
  1864. printer_name=printer_name,
  1865. filename=filename,
  1866. db=db,
  1867. )
  1868. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  1869. """Extract printable objects from an archive's 3MF file and store in printer state."""
  1870. try:
  1871. from backend.app.services.archive import extract_printable_objects_from_3mf
  1872. file_path = app_settings.base_dir / archive.file_path
  1873. if file_path.is_file() and str(file_path).endswith(".3mf"):
  1874. with open(file_path, "rb") as f:
  1875. threemf_data = f.read()
  1876. # Extract with positions for UI overlay
  1877. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  1878. if printable_objects:
  1879. client = printer_manager.get_client(printer_id)
  1880. if client:
  1881. client.state.printable_objects = printable_objects
  1882. client.state.printable_objects_bbox_all = bbox_all
  1883. client.state.skipped_objects = []
  1884. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  1885. except Exception as e:
  1886. logger.debug("Failed to extract printable objects from archive: %s", e)
  1887. async def on_print_start(printer_id: int, data: dict):
  1888. """Handle print start - archive the 3MF file immediately."""
  1889. logger = logging.getLogger(__name__)
  1890. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  1891. # Clear any stale user-stopped flag from previous print cycles
  1892. _user_stopped_printers.discard(printer_id)
  1893. # #1721: drop any leftover pre-captured finish frame from a prior print
  1894. # so a never-consumed cache entry can't bleed into the new print's photo.
  1895. _stage22_finish_frames.pop(printer_id, None)
  1896. # Cancel any active bed cooldown waiter for this printer
  1897. if _bed_cool_waiters.pop(printer_id, None):
  1898. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  1899. # Clear cached cover images so the new print's thumbnail is fetched fresh
  1900. from backend.app.api.routes.printers import clear_cover_cache
  1901. clear_cover_cache(printer_id)
  1902. await ws_manager.send_print_start(printer_id, data)
  1903. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  1904. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  1905. # MQTT relay - publish print start
  1906. try:
  1907. printer_info = printer_manager.get_printer(printer_id)
  1908. if printer_info:
  1909. await mqtt_relay.on_print_start(
  1910. printer_id,
  1911. printer_info.name,
  1912. printer_info.serial_number,
  1913. data.get("filename", ""),
  1914. data.get("subtask_name", ""),
  1915. )
  1916. except Exception:
  1917. pass # Don't fail print start callback if MQTT fails
  1918. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  1919. try:
  1920. async with async_session() as db:
  1921. from backend.app.api.routes.settings import get_setting
  1922. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1923. if not _spoolman_on or _spoolman_on.lower() != "true":
  1924. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  1925. await usage_on_print_start(printer_id, data, printer_manager, db=db)
  1926. except Exception as e:
  1927. logger.warning("Usage tracker on_print_start failed: %s", e)
  1928. # Track if notification was sent (to avoid sending twice)
  1929. notification_sent = False
  1930. # Smart plug automation: turn on plug when print starts
  1931. try:
  1932. async with async_session() as db:
  1933. await smart_plug_manager.on_print_start(printer_id, db)
  1934. except Exception as e:
  1935. logger.warning("Smart plug on_print_start failed: %s", e)
  1936. async with async_session() as db:
  1937. from backend.app.models.printer import Printer
  1938. from backend.app.services.bambu_ftp import list_files_async
  1939. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1940. printer = result.scalar_one_or_none()
  1941. # Plate detection check - pause if objects detected on build plate
  1942. logger.info(
  1943. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  1944. )
  1945. if printer and printer.plate_detection_enabled:
  1946. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  1947. try:
  1948. from backend.app.services.plate_detection import check_plate_empty
  1949. # Build ROI tuple from printer settings if available
  1950. roi = None
  1951. if all(
  1952. [
  1953. printer.plate_detection_roi_x is not None,
  1954. printer.plate_detection_roi_y is not None,
  1955. printer.plate_detection_roi_w is not None,
  1956. printer.plate_detection_roi_h is not None,
  1957. ]
  1958. ):
  1959. roi = (
  1960. printer.plate_detection_roi_x,
  1961. printer.plate_detection_roi_y,
  1962. printer.plate_detection_roi_w,
  1963. printer.plate_detection_roi_h,
  1964. )
  1965. # Auto-turn on chamber light if it's off for better detection
  1966. light_was_off = False
  1967. client = printer_manager.get_client(printer_id)
  1968. if client and client.state:
  1969. light_was_off = not client.state.chamber_light
  1970. if light_was_off:
  1971. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  1972. client.set_chamber_light(True)
  1973. # Wait for light to physically turn on and camera to adjust exposure
  1974. await asyncio.sleep(2.5)
  1975. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  1976. plate_result = await check_plate_empty(
  1977. printer_id=printer_id,
  1978. ip_address=printer.ip_address,
  1979. access_code=printer.access_code,
  1980. model=printer.model,
  1981. include_debug_image=False,
  1982. external_camera_url=printer.external_camera_url,
  1983. external_camera_type=printer.external_camera_type,
  1984. use_external=printer.external_camera_enabled,
  1985. roi=roi,
  1986. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  1987. )
  1988. # Restore chamber light to original state
  1989. if light_was_off and client:
  1990. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  1991. client.set_chamber_light(False)
  1992. if not plate_result.needs_calibration and not plate_result.is_empty:
  1993. # Objects detected - pause the print!
  1994. logger.warning(
  1995. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  1996. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  1997. )
  1998. client = printer_manager.get_client(printer_id)
  1999. if client:
  2000. client.pause_print()
  2001. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  2002. # Send notification about plate not empty
  2003. await ws_manager.broadcast(
  2004. {
  2005. "type": "plate_not_empty",
  2006. "printer_id": printer_id,
  2007. "printer_name": printer.name,
  2008. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  2009. }
  2010. )
  2011. # Also send push notification
  2012. try:
  2013. await notification_service.on_plate_not_empty(
  2014. printer_id=printer_id,
  2015. printer_name=printer.name,
  2016. db=db,
  2017. difference_percent=plate_result.difference_percent,
  2018. )
  2019. except Exception as notif_err:
  2020. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  2021. else:
  2022. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  2023. except Exception as plate_err:
  2024. # Don't block print on plate detection errors
  2025. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  2026. if not printer:
  2027. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  2028. if not notification_sent:
  2029. await _send_print_start_notification(printer_id, data, logger=logger)
  2030. return
  2031. if not printer.auto_archive:
  2032. # auto-archive disabled — check if there's an expected print (dispatched
  2033. # by BamBuddy via queue/reprint) that already has an archive to promote.
  2034. # If so, fall through to the expected-print handling below so the archive
  2035. # is tracked in _active_prints and usage tracking works at completion.
  2036. _fn = data.get("filename", "")
  2037. _sn = data.get("subtask_name", "")
  2038. _check_keys: list[tuple[int, str]] = []
  2039. if _sn:
  2040. _check_keys += [
  2041. (printer_id, _sn),
  2042. (printer_id, f"{_sn}.3mf"),
  2043. (printer_id, f"{_sn}.gcode.3mf"),
  2044. ]
  2045. if _fn:
  2046. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  2047. _check_keys.append((printer_id, _base_fn))
  2048. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  2049. _check_keys += [
  2050. (printer_id, _no_archive_base),
  2051. (printer_id, f"{_no_archive_base}.3mf"),
  2052. ]
  2053. _has_expected = any(k in _expected_prints for k in _check_keys)
  2054. if not _has_expected:
  2055. # No expected print — truly external print (started from slicer/touchscreen)
  2056. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  2057. if not notification_sent:
  2058. _no_archive_creator: int | None = None
  2059. for _key in _check_keys:
  2060. _expected_prints.pop(_key, None)
  2061. _expected_print_registered_at.pop(_key, None)
  2062. popped_creator = _expected_print_creators.pop(_key, None)
  2063. if _no_archive_creator is None:
  2064. _no_archive_creator = popped_creator
  2065. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  2066. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  2067. return
  2068. else:
  2069. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  2070. # Get the filename and subtask_name
  2071. filename = data.get("filename", "")
  2072. subtask_name = data.get("subtask_name", "")
  2073. # MQTT subtask_id uniquely identifies a print job on the printer. When
  2074. # present, it lets us match an archive across a backend restart (#972):
  2075. # same id → same print → resume the existing row instead of cancelling
  2076. # it and recreating from scratch (which loses started_at). Treat "0"
  2077. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  2078. raw_mqtt = data.get("raw_data") or {}
  2079. subtask_id = raw_mqtt.get("subtask_id")
  2080. if subtask_id is not None:
  2081. subtask_id = str(subtask_id).strip()
  2082. if subtask_id in ("", "0"):
  2083. subtask_id = None
  2084. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  2085. # Skip calibration prints — internal printer files should not be archived
  2086. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  2087. if filename and filename.startswith("/usr/"):
  2088. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  2089. if not notification_sent:
  2090. await _send_print_start_notification(printer_id, data, logger=logger)
  2091. return
  2092. if not filename and not subtask_name:
  2093. # Send notification without archive data (no filename)
  2094. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  2095. if not notification_sent:
  2096. await _send_print_start_notification(printer_id, data, logger=logger)
  2097. return
  2098. # Check if this is an expected print from reprint/scheduled
  2099. # Build list of possible keys to check
  2100. expected_keys = []
  2101. if subtask_name:
  2102. expected_keys.append((printer_id, subtask_name))
  2103. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  2104. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  2105. if filename:
  2106. fname = filename.split("/")[-1] if "/" in filename else filename
  2107. expected_keys.append((printer_id, fname))
  2108. # Strip extensions to match
  2109. base = fname.replace(".gcode", "").replace(".3mf", "")
  2110. expected_keys.append((printer_id, base))
  2111. expected_keys.append((printer_id, f"{base}.3mf"))
  2112. expected_archive_id = None
  2113. for key in expected_keys:
  2114. expected_archive_id = _expected_prints.pop(key, None)
  2115. _expected_print_registered_at.pop(key, None)
  2116. if expected_archive_id:
  2117. # Clean up other possible keys for this print
  2118. for other_key in expected_keys:
  2119. _expected_prints.pop(other_key, None)
  2120. _expected_print_registered_at.pop(other_key, None)
  2121. break
  2122. if expected_archive_id:
  2123. # This is a reprint/scheduled print - use existing archive, don't create new one
  2124. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  2125. from backend.app.models.archive import PrintArchive
  2126. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  2127. archive = result.scalar_one_or_none()
  2128. if archive:
  2129. # Update archive status to printing
  2130. archive.status = "printing"
  2131. archive.started_at = datetime.now(timezone.utc)
  2132. # Reprint of an archive reuses the source row. Without resetting
  2133. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  2134. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  2135. # extracts the *original* print's last frame, which then ships in
  2136. # the completion notification (#1707). Clear the path so the
  2137. # scanner runs fresh; also unlink the old video file so reprints
  2138. # don't accumulate orphans in the archive directory. Photos list
  2139. # is left alone — accumulating one finish photo per run is fine.
  2140. stale_timelapse_relpath = archive.timelapse_path
  2141. if stale_timelapse_relpath:
  2142. archive.timelapse_path = None
  2143. try:
  2144. stale_path = app_settings.base_dir / stale_timelapse_relpath
  2145. if stale_path.is_file():
  2146. stale_path.unlink()
  2147. logger.info(
  2148. "Deleted stale timelapse %s on reprint of archive %s",
  2149. stale_timelapse_relpath,
  2150. expected_archive_id,
  2151. )
  2152. except OSError as e:
  2153. logger.warning(
  2154. "Failed to delete stale timelapse %s on reprint: %s",
  2155. stale_timelapse_relpath,
  2156. e,
  2157. )
  2158. # Persist a restart-stable id so a later restart resumes this
  2159. # archive by subtask_id instead of name-matching + duplicating
  2160. # it (#1485). The printer often hasn't echoed subtask_id back
  2161. # this soon after dispatch, so fall back to the id Bambuddy
  2162. # minted when it sent the print command. Scoped to this
  2163. # expected-print branch on purpose: an expected match means
  2164. # Bambuddy dispatched this exact print in this process, so the
  2165. # client's last-dispatch id genuinely belongs to it — using it
  2166. # for an externally-started print could mis-tag the archive.
  2167. effective_subtask_id = subtask_id
  2168. if not effective_subtask_id:
  2169. _client = printer_manager.get_client(printer_id)
  2170. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  2171. if _dispatched:
  2172. effective_subtask_id = str(_dispatched).strip() or None
  2173. if effective_subtask_id and not archive.subtask_id:
  2174. archive.subtask_id = effective_subtask_id
  2175. # #1403 follow-up: VP-queue archives are created with
  2176. # printer_id=None at queue-add time (we don't know which
  2177. # printer will run the job yet). When the print actually
  2178. # starts on a specific printer the expected-archive lookup
  2179. # used to skip this assignment, leaving printer_id=None
  2180. # forever — which then disables the "Scan for timelapse"
  2181. # button in ArchivesPage (gated on !archive.printer_id).
  2182. if archive.printer_id != printer_id:
  2183. archive.printer_id = printer_id
  2184. await db.commit()
  2185. # Track as active print
  2186. _active_prints[(printer_id, archive.filename)] = archive.id
  2187. if subtask_name:
  2188. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2189. # Start timelapse session if external camera is enabled (#1353).
  2190. # Queue / VP-dispatched prints land here in the expected-archive
  2191. # branch and used to skip start_session entirely — frames were
  2192. # never captured and the post-print stitch silently returned None.
  2193. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  2194. # Inject ams_mapping into usage tracker session — the session was created
  2195. # before expected-print promotion, so it may have ams_mapping=None when
  2196. # the MQTT request topic subscription failed (common on P1S/A1).
  2197. _stored_map = _print_ams_mappings.get(expected_archive_id)
  2198. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  2199. if _stored_map or _stored_plate_id is not None:
  2200. try:
  2201. from backend.app.services.usage_tracker import _active_sessions
  2202. _ut_session = _active_sessions.get(printer_id)
  2203. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  2204. _ut_session.ams_mapping = _stored_map
  2205. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  2206. # plate_id injection covers direct-Print of plate N of a multi-plate
  2207. # 3MF — queue prints already capture it via the on_print_start queue
  2208. # lookup, but direct-Print never goes through the queue (#1697).
  2209. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  2210. _ut_session.plate_id = _stored_plate_id
  2211. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  2212. except Exception:
  2213. pass
  2214. # Set up energy tracking (#941: persist start on archive row)
  2215. await _record_energy_start(archive, printer_id, db, context="expected-print")
  2216. await ws_manager.send_archive_updated(
  2217. {
  2218. "id": archive.id,
  2219. "status": "printing",
  2220. }
  2221. )
  2222. # Send notification with archive data (reprint/scheduled)
  2223. if not notification_sent:
  2224. # Use archive's created_by_id; fall back to the creator registered via
  2225. # register_expected_print (handles library-file-based queue items where
  2226. # the freshly-created archive has no created_by_id yet).
  2227. # Pop ALL matching keys so no stale entries remain in the dict.
  2228. fallback_creator = None
  2229. for key in expected_keys:
  2230. popped = _expected_print_creators.pop(key, None)
  2231. if fallback_creator is None:
  2232. fallback_creator = popped
  2233. archive_data = {
  2234. "print_time_seconds": archive.print_time_seconds,
  2235. "created_by_id": archive.created_by_id or fallback_creator,
  2236. }
  2237. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2238. # Extract printable objects from the archived 3MF file
  2239. _load_objects_from_archive(archive, printer_id, logger)
  2240. # Store Spoolman tracking data for per-filament usage reporting
  2241. try:
  2242. await _store_spoolman_print_data(
  2243. printer_id,
  2244. archive.id,
  2245. archive.file_path,
  2246. db,
  2247. printer_manager,
  2248. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2249. plate_id=_get_start_plate_id(archive.id),
  2250. )
  2251. except Exception as e:
  2252. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2253. # Capture timelapse file baseline for snapshot-diff on completion
  2254. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  2255. # hit this branch — without the baseline the completion-time scan
  2256. # falls into its "take baseline now" fallback, which snapshots
  2257. # AFTER the new MP4 already exists and never matches a diff
  2258. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  2259. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  2260. return # Skip creating a new archive
  2261. # Check if there's already a "printing" archive for this printer/file
  2262. # This prevents duplicates when backend restarts during an active print
  2263. from backend.app.models.archive import PrintArchive
  2264. existing_archive: PrintArchive | None = None
  2265. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  2266. # across a backend restart for the same print, so this is the most
  2267. # reliable way to reattach. We also accept a previously stale-cancelled
  2268. # archive here so users upgrading mid-print get revived when the row
  2269. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  2270. if subtask_id:
  2271. by_id = await db.execute(
  2272. select(PrintArchive)
  2273. .where(PrintArchive.printer_id == printer_id)
  2274. .where(PrintArchive.subtask_id == subtask_id)
  2275. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  2276. .order_by(PrintArchive.created_at.desc())
  2277. .limit(1)
  2278. )
  2279. candidate = by_id.scalar_one_or_none()
  2280. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  2281. existing_archive = candidate
  2282. # Fallback match: name-based lookup. Kept as-is for prints whose
  2283. # subtask_id is missing ("0" / local / non-cloud prints).
  2284. if existing_archive is None:
  2285. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  2286. existing = await db.execute(
  2287. select(PrintArchive)
  2288. .where(PrintArchive.printer_id == printer_id)
  2289. .where(PrintArchive.status == "printing")
  2290. .where(
  2291. or_(
  2292. PrintArchive.print_name == check_name,
  2293. PrintArchive.filename.in_(
  2294. [
  2295. f"{check_name}.3mf",
  2296. f"{check_name}.gcode.3mf",
  2297. ]
  2298. ),
  2299. )
  2300. )
  2301. .order_by(PrintArchive.created_at.desc())
  2302. .limit(1)
  2303. )
  2304. existing_archive = existing.scalar_one_or_none()
  2305. if existing_archive:
  2306. # subtask_id match → always resume, regardless of age. Same print,
  2307. # just a backend restart. Revive if it was previously stale-cancelled.
  2308. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  2309. if subtask_match:
  2310. if existing_archive.status == "cancelled":
  2311. logger.warning(
  2312. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  2313. existing_archive.id,
  2314. subtask_id,
  2315. )
  2316. existing_archive.status = "printing"
  2317. existing_archive.failure_reason = None
  2318. await db.commit()
  2319. else:
  2320. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  2321. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  2322. if existing_archive.energy_start_kwh is None:
  2323. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  2324. if not notification_sent:
  2325. archive_data = {
  2326. "print_time_seconds": existing_archive.print_time_seconds,
  2327. "created_by_id": existing_archive.created_by_id,
  2328. }
  2329. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2330. _load_objects_from_archive(existing_archive, printer_id, logger)
  2331. return
  2332. # Name-match only (no subtask_id to anchor on): decide resume vs.
  2333. # stale from the printer's *current* progress, not wall-clock age.
  2334. # A genuinely long print used to trip a blind 4h cutoff and have its
  2335. # live archive cancelled + duplicated on every backend restart
  2336. # (#1485). If the printer reports real progress, this name-matched
  2337. # 'printing' archive IS that ongoing print — resume it whatever its
  2338. # age. Only treat it as a stale leftover when the printer clearly
  2339. # shows a different, freshly-started print: near-0% progress on an
  2340. # archive far too old to still be at 0%. Unknown progress (printer
  2341. # not connected) never cancels — resuming is the safe default.
  2342. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  2343. live_status = printer_manager.get_status(printer_id)
  2344. live_progress = getattr(live_status, "progress", None) if live_status else None
  2345. looks_stale = (
  2346. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  2347. )
  2348. if looks_stale:
  2349. logger.warning(
  2350. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  2351. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  2352. )
  2353. existing_archive.status = "cancelled"
  2354. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  2355. await db.commit()
  2356. # Fall through to create new archive (don't return)
  2357. else:
  2358. logger.info(
  2359. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  2360. )
  2361. # Track this as the active print
  2362. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  2363. # Attach subtask_id retroactively so future restarts can resume
  2364. if subtask_id and not existing_archive.subtask_id:
  2365. existing_archive.subtask_id = subtask_id
  2366. await db.commit()
  2367. # Also set up energy tracking if not already tracked (#941: persisted column)
  2368. if existing_archive.energy_start_kwh is None:
  2369. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  2370. # Send notification with archive data (existing archive)
  2371. if not notification_sent:
  2372. archive_data = {
  2373. "print_time_seconds": existing_archive.print_time_seconds,
  2374. "created_by_id": existing_archive.created_by_id,
  2375. }
  2376. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2377. # Extract printable objects from the archived 3MF file
  2378. _load_objects_from_archive(existing_archive, printer_id, logger)
  2379. return
  2380. # Build list of possible 3MF filenames to try
  2381. possible_names = []
  2382. # Bambu printers typically store files as "Name.gcode.3mf"
  2383. # The subtask_name is usually the best source for the filename
  2384. if subtask_name:
  2385. # Try common Bambu naming patterns
  2386. possible_names.append(f"{subtask_name}.gcode.3mf")
  2387. possible_names.append(f"{subtask_name}.3mf")
  2388. # Try original filename with .3mf extension
  2389. if filename:
  2390. # Extract just the filename part, not the full path
  2391. fname = filename.split("/")[-1] if "/" in filename else filename
  2392. if fname.endswith(".3mf"):
  2393. possible_names.append(fname)
  2394. elif fname.endswith(".gcode"):
  2395. base = fname.rsplit(".", 1)[0]
  2396. possible_names.append(f"{base}.gcode.3mf")
  2397. possible_names.append(f"{base}.3mf")
  2398. else:
  2399. possible_names.append(f"{fname}.gcode.3mf")
  2400. possible_names.append(f"{fname}.3mf")
  2401. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  2402. space_variants = []
  2403. for name in possible_names:
  2404. if " " in name:
  2405. space_variants.append(name.replace(" ", "_"))
  2406. possible_names.extend(space_variants)
  2407. # Remove duplicates while preserving order
  2408. seen = set()
  2409. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  2410. logger.info("Trying filenames: %s", possible_names)
  2411. # Try to find and download the 3MF file
  2412. temp_path = None
  2413. downloaded_filename = None
  2414. # Cache check: cover endpoint may have already pulled this 3MF during
  2415. # the print (frontend opens the card and shows the thumbnail) — reuse
  2416. # that file instead of re-downloading 36MB over the same FTP link that
  2417. # just served it (#972). The cache keys on a normalized filename so
  2418. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  2419. for try_filename in possible_names:
  2420. if not try_filename.endswith(".3mf"):
  2421. continue
  2422. cached = get_cached_3mf(printer_id, try_filename)
  2423. if cached:
  2424. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  2425. temp_path = cached
  2426. downloaded_filename = try_filename
  2427. break
  2428. # Get FTP retry settings
  2429. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  2430. for try_filename in possible_names if not downloaded_filename else []:
  2431. if not try_filename.endswith(".3mf"):
  2432. continue
  2433. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  2434. # printers, so try it first — deferring it to last cost #972's reporter
  2435. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  2436. # landing on the path that actually had the file.
  2437. remote_paths = [
  2438. f"/{try_filename}",
  2439. f"/cache/{try_filename}",
  2440. f"/model/{try_filename}",
  2441. f"/data/{try_filename}",
  2442. f"/data/Metadata/{try_filename}",
  2443. ]
  2444. temp_path = app_settings.archive_dir / "temp" / try_filename
  2445. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2446. for remote_path in remote_paths:
  2447. logger.debug("Trying FTP download: %s", remote_path)
  2448. try:
  2449. if ftp_retry_enabled:
  2450. downloaded = await with_ftp_retry(
  2451. download_file_async,
  2452. printer.ip_address,
  2453. printer.access_code,
  2454. remote_path,
  2455. temp_path,
  2456. timeout=ftp_timeout,
  2457. socket_timeout=ftp_timeout,
  2458. printer_model=printer.model,
  2459. max_retries=ftp_retry_count,
  2460. retry_delay=ftp_retry_delay,
  2461. operation_name=f"Download 3MF from {remote_path}",
  2462. non_retry_exceptions=(FileNotOnPrinterError,),
  2463. )
  2464. else:
  2465. downloaded = await download_file_async(
  2466. printer.ip_address,
  2467. printer.access_code,
  2468. remote_path,
  2469. temp_path,
  2470. timeout=ftp_timeout,
  2471. socket_timeout=ftp_timeout,
  2472. printer_model=printer.model,
  2473. )
  2474. if downloaded:
  2475. downloaded_filename = try_filename
  2476. logger.info("Downloaded: %s", remote_path)
  2477. # Populate shared cache so the cover endpoint (if it
  2478. # runs next) doesn't refetch the same 36MB over FTP.
  2479. cache_3mf_download(printer_id, try_filename, temp_path)
  2480. break
  2481. except FileNotOnPrinterError:
  2482. # 550 — file isn't at this path. Advance to next candidate
  2483. # without burning the retry budget.
  2484. logger.debug("3MF not at %s (550), trying next path", remote_path)
  2485. except Exception as e:
  2486. logger.debug("FTP download failed for %s: %s", remote_path, e)
  2487. if downloaded_filename:
  2488. break
  2489. # If still not found, try listing directories to find matching file
  2490. # Different printer models use different directory structures
  2491. if not downloaded_filename and (filename or subtask_name):
  2492. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  2493. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  2494. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  2495. for search_dir in search_dirs:
  2496. if downloaded_filename:
  2497. break
  2498. try:
  2499. dir_files = await list_files_async(
  2500. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  2501. )
  2502. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  2503. if threemf_files:
  2504. logger.info(
  2505. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  2506. )
  2507. for f in dir_files:
  2508. if f.get("is_directory"):
  2509. continue
  2510. fname = f.get("name", "")
  2511. # Normalize both for comparison (spaces and underscores are equivalent)
  2512. fname_normalized = fname.lower().replace(" ", "_")
  2513. search_normalized = search_term.replace(" ", "_")
  2514. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  2515. logger.info("Found matching file in %s: %s", search_dir, fname)
  2516. temp_path = app_settings.archive_dir / "temp" / fname
  2517. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2518. remote_full_path = posixpath.join(search_dir, fname)
  2519. if ftp_retry_enabled:
  2520. downloaded = await with_ftp_retry(
  2521. download_file_async,
  2522. printer.ip_address,
  2523. printer.access_code,
  2524. remote_full_path,
  2525. temp_path,
  2526. timeout=ftp_timeout,
  2527. socket_timeout=ftp_timeout,
  2528. printer_model=printer.model,
  2529. max_retries=ftp_retry_count,
  2530. retry_delay=ftp_retry_delay,
  2531. operation_name=f"Download 3MF from {remote_full_path}",
  2532. )
  2533. else:
  2534. downloaded = await download_file_async(
  2535. printer.ip_address,
  2536. printer.access_code,
  2537. remote_full_path,
  2538. temp_path,
  2539. timeout=ftp_timeout,
  2540. socket_timeout=ftp_timeout,
  2541. printer_model=printer.model,
  2542. )
  2543. if downloaded:
  2544. downloaded_filename = fname
  2545. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  2546. cache_3mf_download(printer_id, fname, temp_path)
  2547. break
  2548. except Exception as e:
  2549. logger.debug("Failed to list %s: %s", search_dir, e)
  2550. # Validate the downloaded 3MF actually matches the plate that's running
  2551. # (#1204): subtask_name lags across consecutive plates of the same model,
  2552. # so the first FTP candidate (built from subtask_name) can land on the
  2553. # previous plate's still-resident upload. Cross-check the slice_info
  2554. # plate index against the plate parsed from gcode_file (always fresh —
  2555. # it's the field whose change triggered this callback).
  2556. if downloaded_filename and temp_path:
  2557. expected_plate = parse_plate_id(filename)
  2558. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  2559. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  2560. logger.warning(
  2561. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  2562. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  2563. downloaded_filename,
  2564. actual_plate,
  2565. expected_plate,
  2566. subtask_name,
  2567. )
  2568. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  2569. retry_succeeded = False
  2570. if corrected_subtask and corrected_subtask != subtask_name:
  2571. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  2572. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  2573. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  2574. for remote_path in (
  2575. f"/{try_filename}",
  2576. f"/cache/{try_filename}",
  2577. f"/model/{try_filename}",
  2578. f"/data/{try_filename}",
  2579. f"/data/Metadata/{try_filename}",
  2580. ):
  2581. try:
  2582. if ftp_retry_enabled:
  2583. downloaded = await with_ftp_retry(
  2584. download_file_async,
  2585. printer.ip_address,
  2586. printer.access_code,
  2587. remote_path,
  2588. retry_temp_path,
  2589. timeout=ftp_timeout,
  2590. socket_timeout=ftp_timeout,
  2591. printer_model=printer.model,
  2592. max_retries=ftp_retry_count,
  2593. retry_delay=ftp_retry_delay,
  2594. operation_name=f"Re-download 3MF from {remote_path}",
  2595. non_retry_exceptions=(FileNotOnPrinterError,),
  2596. )
  2597. else:
  2598. downloaded = await download_file_async(
  2599. printer.ip_address,
  2600. printer.access_code,
  2601. remote_path,
  2602. retry_temp_path,
  2603. timeout=ftp_timeout,
  2604. socket_timeout=ftp_timeout,
  2605. printer_model=printer.model,
  2606. )
  2607. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  2608. logger.info(
  2609. "[CALLBACK] Re-download succeeded with corrected name %s "
  2610. "(plate %s) — replacing wrong file",
  2611. try_filename,
  2612. expected_plate,
  2613. )
  2614. try:
  2615. temp_path.unlink(missing_ok=True)
  2616. except OSError:
  2617. pass
  2618. temp_path = retry_temp_path
  2619. downloaded_filename = try_filename
  2620. subtask_name = corrected_subtask
  2621. cache_3mf_download(printer_id, try_filename, temp_path)
  2622. retry_succeeded = True
  2623. break
  2624. elif downloaded:
  2625. # Wrong plate again — discard and keep trying
  2626. try:
  2627. retry_temp_path.unlink(missing_ok=True)
  2628. except OSError:
  2629. pass
  2630. except FileNotOnPrinterError:
  2631. continue
  2632. except Exception as e:
  2633. logger.debug("Re-download failed for %s: %s", remote_path, e)
  2634. if retry_succeeded:
  2635. break
  2636. # If the retry didn't find a matching file, drop the wrong 3MF
  2637. # so the no-3MF fallback below creates an archive whose name
  2638. # at least reflects the right plate.
  2639. if not retry_succeeded:
  2640. logger.warning(
  2641. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  2642. expected_plate,
  2643. )
  2644. try:
  2645. temp_path.unlink(missing_ok=True)
  2646. except OSError:
  2647. pass
  2648. temp_path = None
  2649. downloaded_filename = None
  2650. # Override the stale subtask_name so the fallback archive's
  2651. # print_name reflects the correct plate. Prefer the swapped
  2652. # name when we have one; otherwise let filename win.
  2653. if corrected_subtask:
  2654. subtask_name = corrected_subtask
  2655. else:
  2656. subtask_name = ""
  2657. if not downloaded_filename or not temp_path:
  2658. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  2659. # Create a fallback archive without 3MF data so the print is still tracked
  2660. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  2661. try:
  2662. from backend.app.models.archive import PrintArchive
  2663. # Derive print name from subtask_name or filename
  2664. print_name = subtask_name or filename
  2665. if print_name:
  2666. # Clean up the name (remove extensions, path parts)
  2667. print_name = print_name.split("/")[-1]
  2668. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  2669. else:
  2670. print_name = "Unknown Print"
  2671. # Recover estimated print time from MQTT (best-effort for notifications)
  2672. fallback_print_time = None
  2673. mqtt_remaining = data.get("remaining_time")
  2674. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  2675. fallback_print_time = int(mqtt_remaining)
  2676. if fallback_print_time is None:
  2677. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  2678. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  2679. fallback_print_time = int(mc_remaining * 60)
  2680. # Best-effort filament metadata from MQTT — see
  2681. # _extract_filament_data_from_mqtt. Without this the fallback
  2682. # archive's filament fields stayed NULL even though the AMS
  2683. # state at print start was sitting right there in `data`.
  2684. # The slicer's ams_mapping (when present) narrows the result
  2685. # to slots actually used by the print (#1533).
  2686. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  2687. # Create minimal archive entry
  2688. fallback_archive = PrintArchive(
  2689. printer_id=printer_id,
  2690. filename=filename or f"{print_name}.3mf",
  2691. file_path="", # Empty - no 3MF file available
  2692. file_size=0,
  2693. print_name=print_name,
  2694. print_time_seconds=fallback_print_time,
  2695. status="printing",
  2696. started_at=datetime.now(timezone.utc),
  2697. subtask_id=subtask_id,
  2698. filament_type=mqtt_filament_meta.get("filament_type"),
  2699. filament_color=mqtt_filament_meta.get("filament_color"),
  2700. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  2701. )
  2702. db.add(fallback_archive)
  2703. await db.commit()
  2704. await db.refresh(fallback_archive)
  2705. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  2706. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  2707. # Track as active print
  2708. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  2709. if filename:
  2710. _active_prints[(printer_id, filename)] = fallback_archive.id
  2711. if subtask_name:
  2712. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  2713. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  2714. # Record starting energy if smart plug available (#941: persisted column)
  2715. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  2716. # Send WebSocket notification
  2717. await ws_manager.send_archive_created(
  2718. {
  2719. "id": fallback_archive.id,
  2720. "printer_id": fallback_archive.printer_id,
  2721. "filename": fallback_archive.filename,
  2722. "print_name": fallback_archive.print_name,
  2723. "status": fallback_archive.status,
  2724. }
  2725. )
  2726. # MQTT relay - publish archive created
  2727. try:
  2728. await mqtt_relay.on_archive_created(
  2729. archive_id=fallback_archive.id,
  2730. print_name=fallback_archive.print_name,
  2731. printer_name=printer.name,
  2732. status=fallback_archive.status,
  2733. )
  2734. except Exception:
  2735. pass # Don't fail if MQTT fails
  2736. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  2737. try:
  2738. await _store_spoolman_print_data(
  2739. printer_id,
  2740. fallback_archive.id,
  2741. fallback_archive.file_path,
  2742. db,
  2743. printer_manager,
  2744. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  2745. plate_id=_get_start_plate_id(fallback_archive.id),
  2746. )
  2747. except Exception as e:
  2748. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  2749. # Send notification without archive data (file not found)
  2750. if not notification_sent:
  2751. await _send_print_start_notification(printer_id, data, logger=logger)
  2752. return
  2753. except Exception as e:
  2754. logger.error("Failed to create fallback archive: %s", e)
  2755. # Send notification without archive data (file not found)
  2756. if not notification_sent:
  2757. await _send_print_start_notification(printer_id, data, logger=logger)
  2758. return
  2759. try:
  2760. # Archive the file with status "printing"
  2761. service = ArchiveService(db)
  2762. archive = await service.archive_print(
  2763. printer_id=printer_id,
  2764. source_file=temp_path,
  2765. print_data={**data, "status": "printing"},
  2766. subtask_id=subtask_id,
  2767. )
  2768. if archive:
  2769. # Track this active print (use both original filename and downloaded filename)
  2770. _active_prints[(printer_id, downloaded_filename)] = archive.id
  2771. if filename and filename != downloaded_filename:
  2772. _active_prints[(printer_id, filename)] = archive.id
  2773. if subtask_name:
  2774. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  2775. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  2776. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  2777. # Record starting energy from smart plug if available (#941: persisted column)
  2778. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  2779. await ws_manager.send_archive_created(
  2780. {
  2781. "id": archive.id,
  2782. "printer_id": archive.printer_id,
  2783. "filename": archive.filename,
  2784. "print_name": archive.print_name,
  2785. "status": archive.status,
  2786. }
  2787. )
  2788. # MQTT relay - publish archive created
  2789. try:
  2790. await mqtt_relay.on_archive_created(
  2791. archive_id=archive.id,
  2792. print_name=archive.print_name,
  2793. printer_name=printer.name,
  2794. status=archive.status,
  2795. )
  2796. except Exception:
  2797. pass # Don't fail if MQTT fails
  2798. # Send notification with archive data (new archive created)
  2799. if not notification_sent:
  2800. archive_data = {
  2801. "print_time_seconds": archive.print_time_seconds,
  2802. "created_by_id": archive.created_by_id,
  2803. }
  2804. await _send_print_start_notification(printer_id, data, archive_data, logger)
  2805. # Extract printable objects for skip object functionality
  2806. try:
  2807. from backend.app.services.archive import extract_printable_objects_from_3mf
  2808. with open(temp_path, "rb") as f:
  2809. threemf_data = f.read()
  2810. # Extract with positions for UI overlay
  2811. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  2812. threemf_data, include_positions=True
  2813. )
  2814. if printable_objects:
  2815. # Store objects in printer state
  2816. client = printer_manager.get_client(printer_id)
  2817. if client:
  2818. client.state.printable_objects = printable_objects
  2819. client.state.printable_objects_bbox_all = bbox_all
  2820. client.state.skipped_objects = [] # Reset skipped objects for new print
  2821. logger.info(
  2822. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  2823. )
  2824. except Exception as e:
  2825. logger.debug("Failed to extract printable objects: %s", e)
  2826. # Store Spoolman tracking data for per-filament usage reporting
  2827. try:
  2828. await _store_spoolman_print_data(
  2829. printer_id,
  2830. archive.id,
  2831. archive.file_path,
  2832. db,
  2833. printer_manager,
  2834. ams_mapping=_get_start_ams_mapping(data, archive.id),
  2835. plate_id=_get_start_plate_id(archive.id),
  2836. )
  2837. except Exception as e:
  2838. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  2839. # Capture timelapse file baseline for snapshot-diff on completion
  2840. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  2841. finally:
  2842. # Keep temp_path around until print completes so the cover endpoint
  2843. # can reuse it (#972). Cache eviction in on_print_complete deletes
  2844. # the file. If the cache entry was evicted early (file vanished),
  2845. # clean up any stragglers here to avoid leaking disk on retries.
  2846. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  2847. if temp_path and temp_path.exists() and cached_now != temp_path:
  2848. temp_path.unlink()
  2849. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  2850. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  2851. """List video files from printer's timelapse directory.
  2852. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  2853. Returns (video_files, found_path) where video_files is a list of file dicts
  2854. and found_path is the directory where they were found, or ([], None).
  2855. """
  2856. from backend.app.services.bambu_ftp import list_files_async
  2857. logger = logging.getLogger(__name__)
  2858. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  2859. try:
  2860. found_files = await list_files_async(
  2861. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  2862. )
  2863. if found_files:
  2864. video_files = [
  2865. f
  2866. for f in found_files
  2867. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  2868. ]
  2869. if video_files:
  2870. return video_files, timelapse_path
  2871. except Exception as e:
  2872. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  2873. continue
  2874. return [], None
  2875. async def _capture_timelapse_baseline_at_start(printer, printer_id: int, logger: logging.Logger) -> None:
  2876. """Snapshot the printer's timelapse directory at print start so the
  2877. completion-time scan can pick the new file by set-difference.
  2878. Must be called from every on_print_start path that proceeds to a real
  2879. print — both the new-archive branch and the expected-archive branch (which
  2880. queue / VP-dispatched prints take). Without a baseline,
  2881. _scan_for_timelapse_with_retries falls into its "take baseline now"
  2882. fallback that runs AFTER the new MP4 has already landed on the SD card,
  2883. so the new file ends up in the "baseline" set and no diff ever matches.
  2884. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  2885. unreliable — the snapshot-diff approach sidesteps that entirely.
  2886. """
  2887. try:
  2888. baseline_files, _ = await _list_timelapse_videos(printer)
  2889. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  2890. logger.info(
  2891. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  2892. len(_timelapse_baselines[printer_id]),
  2893. printer_id,
  2894. )
  2895. except Exception as e:
  2896. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  2897. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  2898. """
  2899. Scan for timelapse with retries using a snapshot-diff approach.
  2900. Instead of picking the "most recent by mtime" (unreliable when the printer
  2901. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  2902. waiting, then look for any NEW filename that appears after each delay.
  2903. If baseline_names is provided (captured at print start), it is used directly.
  2904. Otherwise falls back to taking a baseline at completion time (best-effort
  2905. for prints started before app restart).
  2906. Falls back to name-matching (print name contained in MP4 filename) if no
  2907. new file appears after all retries.
  2908. """
  2909. from pathlib import Path
  2910. logger = logging.getLogger(__name__)
  2911. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  2912. try:
  2913. async with async_session() as db:
  2914. from backend.app.models.printer import Printer
  2915. service = ArchiveService(db)
  2916. archive = await service.get_archive(archive_id)
  2917. if not archive:
  2918. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  2919. return
  2920. if archive.timelapse_path:
  2921. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  2922. return
  2923. if not archive.printer_id:
  2924. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  2925. return
  2926. if baseline_names is not None:
  2927. # Use pre-captured baseline from print start (no race condition)
  2928. logger.info(
  2929. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  2930. len(baseline_names),
  2931. archive_id,
  2932. )
  2933. else:
  2934. # Fallback: take baseline now (e.g. app restarted mid-print)
  2935. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2936. printer = result.scalar_one_or_none()
  2937. if not printer:
  2938. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  2939. return
  2940. baseline_files, _ = await _list_timelapse_videos(printer)
  2941. baseline_names = {f.get("name", "") for f in baseline_files}
  2942. logger.info(
  2943. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  2944. len(baseline_names),
  2945. archive_id,
  2946. )
  2947. # Derive base_name for name-matching fallback
  2948. base_name = Path(archive.filename).stem if archive.filename else ""
  2949. if base_name.endswith(".gcode"):
  2950. base_name = base_name[:-6]
  2951. except Exception as e:
  2952. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  2953. return
  2954. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  2955. retry_delays = [5, 10, 20, 30]
  2956. for attempt, delay in enumerate(retry_delays, 1):
  2957. logger.info(
  2958. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  2959. attempt,
  2960. len(retry_delays),
  2961. delay,
  2962. archive_id,
  2963. )
  2964. await asyncio.sleep(delay)
  2965. try:
  2966. async with async_session() as db:
  2967. from backend.app.models.printer import Printer
  2968. from backend.app.services.bambu_ftp import download_file_bytes_async
  2969. service = ArchiveService(db)
  2970. archive = await service.get_archive(archive_id)
  2971. if not archive:
  2972. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  2973. return
  2974. if archive.timelapse_path:
  2975. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  2976. return
  2977. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  2978. printer = result.scalar_one_or_none()
  2979. if not printer:
  2980. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  2981. return
  2982. video_files, found_path = await _list_timelapse_videos(printer)
  2983. if not video_files:
  2984. logger.info("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  2985. continue
  2986. logger.info("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  2987. for f in video_files[:5]:
  2988. logger.info("[TIMELAPSE] - %s", f.get("name"))
  2989. # Find files that are NEW (not in baseline snapshot)
  2990. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  2991. if new_files:
  2992. # Pick the first new file (there should typically be exactly one)
  2993. target = new_files[0]
  2994. file_name = target.get("name")
  2995. remote_path = target.get("path") or f"/timelapse/{file_name}"
  2996. logger.info(
  2997. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  2998. attempt,
  2999. file_name,
  3000. archive_id,
  3001. )
  3002. timelapse_data = await download_file_bytes_async(
  3003. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  3004. )
  3005. if timelapse_data:
  3006. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  3007. if success:
  3008. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  3009. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  3010. return
  3011. else:
  3012. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  3013. else:
  3014. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  3015. else:
  3016. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  3017. except Exception as e:
  3018. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  3019. # --- Phase 3: Fallback — try name matching against all files ---
  3020. if base_name:
  3021. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  3022. try:
  3023. async with async_session() as db:
  3024. from backend.app.models.printer import Printer
  3025. from backend.app.services.bambu_ftp import download_file_bytes_async
  3026. service = ArchiveService(db)
  3027. archive = await service.get_archive(archive_id)
  3028. if not archive or archive.timelapse_path:
  3029. return
  3030. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  3031. printer = result.scalar_one_or_none()
  3032. if not printer:
  3033. return
  3034. video_files, found_path = await _list_timelapse_videos(printer)
  3035. for f in video_files:
  3036. fname = f.get("name", "")
  3037. if base_name.lower() in fname.lower():
  3038. remote_path = f.get("path") or f"/timelapse/{fname}"
  3039. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  3040. timelapse_data = await download_file_bytes_async(
  3041. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  3042. )
  3043. if timelapse_data:
  3044. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  3045. if success:
  3046. logger.info(
  3047. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  3048. )
  3049. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  3050. return
  3051. break # Only try the first name match
  3052. except Exception as e:
  3053. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  3054. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  3055. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  3056. # module-level so tests can monkeypatch them down to ~0 without timing out.
  3057. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  3058. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  3059. async def _capture_finish_photo_from_timelapse(
  3060. archive_id: int,
  3061. archive_dir: Path,
  3062. ) -> str | None:
  3063. """Wait for the per-print timelapse to land on the archive and extract its
  3064. last frame as the finish photo (#1397).
  3065. Bambu firmware stops timelapse recording after the toolhead parks but
  3066. before the bed-drop end-gcode runs, so the last frame frames the finished
  3067. print correctly. A live camera grab at gcode_state=FINISH captures the
  3068. bed already lowered.
  3069. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  3070. ``archive.timelapse_path`` when the file lands. This function polls for
  3071. that field. Returns the saved photo filename on success, or None if the
  3072. timelapse never arrives within the timeout / extraction fails / no
  3073. timelapse path was set — in which case the caller falls back to the
  3074. existing live-camera capture chain.
  3075. """
  3076. import uuid
  3077. from backend.app.models.archive import PrintArchive
  3078. from backend.app.services.camera import extract_video_last_frame
  3079. logger = logging.getLogger(__name__)
  3080. deadline = asyncio.get_event_loop().time() + _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS
  3081. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  3082. while True:
  3083. async with async_session() as db:
  3084. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3085. archive = result.scalar_one_or_none()
  3086. timelapse_relpath = archive.timelapse_path if archive else None
  3087. if timelapse_relpath:
  3088. video_path = app_settings.base_dir / timelapse_relpath
  3089. if video_path.exists() and video_path.stat().st_size > 0:
  3090. photos_dir = archive_dir / "photos"
  3091. photos_dir.mkdir(parents=True, exist_ok=True)
  3092. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  3093. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  3094. output_path = photos_dir / filename
  3095. if await extract_video_last_frame(video_path, output_path):
  3096. logger.info(
  3097. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  3098. video_path.name,
  3099. archive_id,
  3100. )
  3101. return filename
  3102. logger.warning(
  3103. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  3104. video_path.name,
  3105. archive_id,
  3106. )
  3107. return None
  3108. if asyncio.get_event_loop().time() >= deadline:
  3109. logger.info(
  3110. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  3111. archive_id,
  3112. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS,
  3113. )
  3114. return None
  3115. await asyncio.sleep(poll_interval)
  3116. async def on_print_running_observed(printer_id: int, data: dict):
  3117. """Restart-recovery: capture a fresh timelapse baseline for a print that
  3118. started before Bambuddy came up.
  3119. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  3120. after Bambuddy startup (#1304 guard, prevents duplicate archive
  3121. creation). Without that path, ``_capture_timelapse_baseline_at_start``
  3122. never runs and ``_scan_for_timelapse_with_retries`` falls into its
  3123. "take baseline now" fallback at completion time — but by then the
  3124. printer has already uploaded the in-flight MP4, so the baseline
  3125. includes it and no diff ever matches (#1485 follow-up).
  3126. Fires once per session, in lieu of on_print_start when restart-recovery
  3127. kicks in. The printer doesn't upload the timelapse until after PRINT
  3128. COMPLETE, so a baseline captured any time during the print is still
  3129. pre-upload.
  3130. """
  3131. logger = logging.getLogger(__name__)
  3132. # Avoid double-capture: on_print_start may have run earlier in this
  3133. # Bambuddy process if the print started AFTER startup and we crashed
  3134. # later in the same session. (Realistically this can't happen — the
  3135. # MQTT client object would have been recreated — but the cheap guard
  3136. # is correct regardless.)
  3137. if printer_id in _timelapse_baselines:
  3138. logger.debug(
  3139. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  3140. printer_id,
  3141. )
  3142. return
  3143. async with async_session() as db:
  3144. from backend.app.models.printer import Printer
  3145. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3146. printer = result.scalar_one_or_none()
  3147. if not printer:
  3148. logger.warning(
  3149. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  3150. printer_id,
  3151. )
  3152. return
  3153. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  3154. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  3155. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  3156. against the printer's current MQTT state.
  3157. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  3158. COMPLETE events, typically a print finishing during an MQTT disconnect
  3159. window followed by a smart-plug power cycle):
  3160. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  3161. provably not running anymore — only branch that should fire under
  3162. normal disconnect-then-reconnect timing.
  3163. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  3164. firmware mints a fresh ``subtask_id`` for each print, including the
  3165. ghost replay it runs after a power cycle from a leftover SD file —
  3166. so a mismatch unambiguously means the in-DB archive is no longer
  3167. the print on the printer.
  3168. 3. Printer is running but ``subtask_name`` is empty. The printer
  3169. doesn't know what it's running; the archive's reference to it is
  3170. already broken.
  3171. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  3172. with matching subtask_id+subtask_name is left alone. The cost of a false
  3173. positive is a duplicate archive on the next real PRINT COMPLETE — the
  3174. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  3175. clears on synthesis, so the real completion creates a fresh row instead
  3176. of overwriting the synthesised one (#1679). The cost of a false negative
  3177. is the ghost-print loop in #1542.
  3178. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  3179. MQTT has connected but the first ``push_status`` response hasn't been
  3180. applied yet — ``PrinterState`` is sitting on its construction defaults.
  3181. The reconcile caller in ``on_printer_status_change`` is already gated
  3182. on a real ``state.state``, so in normal operation this branch is
  3183. unreachable; it's kept as belt-and-braces for future callers and for
  3184. the narrow window where a partial state update could arrive
  3185. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  3186. ``not stale`` on degenerate input is strictly conservative: a real
  3187. stale archive will still be caught by the next push_status arriving
  3188. with terminal state.
  3189. """
  3190. current_state = (state.state or "").upper()
  3191. if current_state in ("", "UNKNOWN"):
  3192. # No real push_status yet — PrinterState defaults are not evidence.
  3193. return False, ""
  3194. if current_state in ("IDLE", "FINISH", "FAILED"):
  3195. return True, f"printer state {current_state}"
  3196. # Below here the printer is in a running / pre-running state (RUNNING /
  3197. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  3198. current_subtask_id = (state.subtask_id or "").strip()
  3199. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  3200. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  3201. current_subtask_name = (state.subtask_name or "").strip()
  3202. if not current_subtask_name:
  3203. return True, "printer subtask_name empty"
  3204. return False, ""
  3205. async def reconcile_stale_active_prints(printer_id: int) -> int:
  3206. """Synthesise ``on_print_complete`` for archives whose print can't be
  3207. running on the printer anymore.
  3208. Called once per MQTT (re)connection (from on_printer_status_change when
  3209. the connected edge flips False → True) and at Bambuddy startup (from
  3210. the FastAPI lifespan). Without this, a print that completes during a
  3211. disconnect window — followed by a smart-plug-driven power cycle — leaves
  3212. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  3213. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  3214. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  3215. power cycle until the operator notices (#1542 follow-up). Reconciliation
  3216. closes the loop by faking the missed PRINT COMPLETE — the existing
  3217. cleanup chain handles SD-file deletion, status updates, usage tracking,
  3218. and notifications.
  3219. Synthesised ``status="aborted"`` is the conservative label: we have no
  3220. proof the print finished successfully (and no progress evidence to
  3221. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  3222. fires later, overwrites the status with the correct value.
  3223. Returns the number of archives reconciled.
  3224. """
  3225. state = printer_manager.get_status(printer_id)
  3226. if not state:
  3227. return 0
  3228. # Don't reconcile while disconnected — we'd be making a decision against
  3229. # stale cached state. The connected → reconcile edge handles this.
  3230. if not state.connected:
  3231. return 0
  3232. from backend.app.models.archive import PrintArchive
  3233. reconciled = 0
  3234. async with async_session() as db:
  3235. result = await db.execute(
  3236. select(PrintArchive).where(
  3237. PrintArchive.printer_id == printer_id,
  3238. PrintArchive.status == "printing",
  3239. )
  3240. )
  3241. active = list(result.scalars().all())
  3242. if not active:
  3243. return 0
  3244. logger = logging.getLogger(__name__)
  3245. for archive in active:
  3246. is_stale, reason = _is_active_archive_stale(archive, state)
  3247. if not is_stale:
  3248. continue
  3249. logger.info(
  3250. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  3251. printer_id,
  3252. archive.id,
  3253. archive.filename,
  3254. reason,
  3255. )
  3256. # Synthesised payload: minimal fields the on_print_complete chain
  3257. # needs. `_reconciled` marker lets downstream code distinguish this
  3258. # from a real MQTT-driven completion if it ever needs to (e.g. for
  3259. # metrics / debug logging). raw_data is the live printer state so
  3260. # the usage tracker can compare end-of-print remain% against the
  3261. # captured start values.
  3262. try:
  3263. await on_print_complete(
  3264. printer_id,
  3265. {
  3266. "status": "aborted",
  3267. "filename": archive.filename,
  3268. "subtask_name": archive.print_name or "",
  3269. "subtask_id": archive.subtask_id or "",
  3270. "raw_data": state.raw_data or {},
  3271. "_reconciled": True,
  3272. },
  3273. )
  3274. reconciled += 1
  3275. except Exception as e:
  3276. # Catch-all: a reconciliation failure must not block the
  3277. # printer's normal status flow. The archive stays in
  3278. # ``status="printing"`` and the next reconnect retries.
  3279. logger.warning(
  3280. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  3281. archive.id,
  3282. e,
  3283. )
  3284. return reconciled
  3285. async def on_finish_photo_moment(printer_id: int, data: dict):
  3286. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  3287. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  3288. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  3289. fallback for prints that skip stage 22 (cancel, external-spool-only,
  3290. HMS halt, firmware variants). Grabs one frame via the same
  3291. external-camera / RTSP path the post-completion fallback uses, stores
  3292. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  3293. ``_background_finish_photo`` consume the cached bytes when it runs.
  3294. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  3295. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  3296. set to Smooth (#1721). No force-on now means the user's explicit
  3297. timelapse=off in the slicer send dialog is respected.
  3298. """
  3299. logger = logging.getLogger(__name__)
  3300. trigger = data.get("trigger", "unknown")
  3301. timelapse_was_active = bool(data.get("timelapse_was_active"))
  3302. logger.info(
  3303. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  3304. printer_id,
  3305. trigger,
  3306. timelapse_was_active,
  3307. )
  3308. # If a timelapse is actively recording, skip the pre-capture — the
  3309. # post-completion path will extract the last frame from the recorded
  3310. # video, which still provides the best framing (toolhead parked,
  3311. # before bed drop) without the per-layer parking side effects.
  3312. if timelapse_was_active:
  3313. logger.info(
  3314. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  3315. printer_id,
  3316. )
  3317. return
  3318. # #1790: register the producer-done event BEFORE the first await so the
  3319. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  3320. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  3321. # The `finally` below guarantees `set()` runs on every exit, including
  3322. # early returns and exceptions, so the consumer's bounded wait can't hang.
  3323. producer_done = asyncio.Event()
  3324. _stage22_finish_in_flight[printer_id] = producer_done
  3325. try:
  3326. async with async_session() as db:
  3327. from backend.app.api.routes.settings import get_setting
  3328. from backend.app.models.printer import Printer
  3329. capture_setting = await get_setting(db, "capture_finish_photo")
  3330. if capture_setting is not None and capture_setting.lower() != "true":
  3331. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  3332. return
  3333. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3334. printer = result.scalar_one_or_none()
  3335. if printer is None:
  3336. logger.warning(
  3337. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  3338. printer_id,
  3339. )
  3340. return
  3341. frame_bytes: bytes | None = None
  3342. if printer.external_camera_enabled and printer.external_camera_url:
  3343. from backend.app.services.external_camera import capture_frame
  3344. frame_bytes = await capture_frame(
  3345. printer.external_camera_url,
  3346. printer.external_camera_type or "mjpeg",
  3347. snapshot_url=printer.external_camera_snapshot_url,
  3348. )
  3349. if frame_bytes:
  3350. logger.info(
  3351. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  3352. len(frame_bytes),
  3353. )
  3354. else:
  3355. from backend.app.api.routes.camera import get_buffered_frame
  3356. buffered = get_buffered_frame(printer_id)
  3357. if buffered:
  3358. frame_bytes = buffered
  3359. logger.info(
  3360. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  3361. len(frame_bytes),
  3362. )
  3363. else:
  3364. from backend.app.services.camera import capture_camera_frame_bytes
  3365. frame_bytes = await capture_camera_frame_bytes(
  3366. ip_address=printer.ip_address,
  3367. access_code=printer.access_code,
  3368. model=printer.model,
  3369. timeout=15,
  3370. )
  3371. if frame_bytes:
  3372. logger.info(
  3373. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  3374. len(frame_bytes),
  3375. )
  3376. if frame_bytes:
  3377. _stage22_finish_frames[printer_id] = frame_bytes
  3378. else:
  3379. logger.warning(
  3380. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  3381. printer_id,
  3382. )
  3383. except Exception as e:
  3384. logger.warning(
  3385. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  3386. printer_id,
  3387. e,
  3388. )
  3389. finally:
  3390. # #1790: always unblock the consumer's bounded wait — whether we stored
  3391. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  3392. # dict entry by the consumer doesn't affect signalling.
  3393. producer_done.set()
  3394. async def on_print_complete(printer_id: int, data: dict):
  3395. """Handle print completion - update the archive status."""
  3396. import time
  3397. logger = logging.getLogger(__name__)
  3398. start_time = time.time()
  3399. def log_timing(section: str):
  3400. elapsed = time.time() - start_time
  3401. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  3402. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  3403. # Drop the 3MF download cache for this printer (#972). The print is over,
  3404. # nothing else legitimately needs the bytes; keeping them would only risk
  3405. # handing a stale file to the next print if it reuses the same name.
  3406. clear_3mf_cache(printer_id)
  3407. try:
  3408. ws_data = {
  3409. "status": data.get("status"),
  3410. "filename": data.get("filename"),
  3411. "subtask_name": data.get("subtask_name"),
  3412. "timelapse_was_active": data.get("timelapse_was_active"),
  3413. }
  3414. await ws_manager.send_print_complete(printer_id, ws_data)
  3415. log_timing("WebSocket send_print_complete")
  3416. except Exception as e:
  3417. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  3418. # Capture user info before clearing (needed for print log entry)
  3419. _print_user_info = printer_manager.get_current_print_user(printer_id)
  3420. # Clear current print user tracking (Issue #206)
  3421. printer_manager.clear_current_print_user(printer_id)
  3422. # If the user explicitly stopped this print from the queue UI the printer will
  3423. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  3424. # correct "print stopped" notification/email is sent instead of a failure alert.
  3425. _raw_status = data.get("status", "completed")
  3426. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  3427. logger.info(
  3428. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  3429. _raw_status,
  3430. printer_id,
  3431. )
  3432. data = {**data, "status": "cancelled"}
  3433. _user_stopped_printers.discard(printer_id)
  3434. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  3435. # may have left material on the bed: a user can cancel ten hours into a
  3436. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  3437. # touchscreen-stop reports `aborted` rather than `cancelled` because
  3438. # `_user_stopped_printers` is only populated when the user stops via the
  3439. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  3440. # which auto-dispatched the next queued print onto a fouled bed two seconds
  3441. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  3442. # Auto Off power cycles and Bambuddy restarts.
  3443. _final_status = data.get("status", "completed")
  3444. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  3445. printer_manager.set_awaiting_plate_clear(printer_id, True)
  3446. # MQTT relay - publish print complete
  3447. try:
  3448. printer_info = printer_manager.get_printer(printer_id)
  3449. if printer_info:
  3450. await mqtt_relay.on_print_complete(
  3451. printer_id,
  3452. printer_info.name,
  3453. printer_info.serial_number,
  3454. data.get("filename", ""),
  3455. data.get("subtask_name", ""),
  3456. data.get("status", "completed"),
  3457. )
  3458. except Exception:
  3459. pass # Don't fail print complete callback if MQTT fails
  3460. filename = data.get("filename", "")
  3461. subtask_name = data.get("subtask_name", "")
  3462. if not filename and not subtask_name:
  3463. logger.warning("Print complete without filename or subtask_name")
  3464. return
  3465. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  3466. # Build list of possible keys to try (matching how they were registered in on_print_start)
  3467. possible_keys = []
  3468. # Try subtask_name variations first (most reliable for matching)
  3469. if subtask_name:
  3470. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  3471. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3472. possible_keys.append((printer_id, subtask_name))
  3473. # Try filename variations
  3474. if filename:
  3475. # Extract just the filename if it's a path
  3476. fname = filename.split("/")[-1] if "/" in filename else filename
  3477. if fname.endswith(".3mf"):
  3478. possible_keys.append((printer_id, fname))
  3479. elif fname.endswith(".gcode"):
  3480. base_name = fname.rsplit(".", 1)[0]
  3481. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  3482. possible_keys.append((printer_id, f"{base_name}.3mf"))
  3483. possible_keys.append((printer_id, fname))
  3484. else:
  3485. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  3486. possible_keys.append((printer_id, f"{fname}.3mf"))
  3487. possible_keys.append((printer_id, fname))
  3488. # Also try full path versions
  3489. if filename.endswith(".3mf"):
  3490. possible_keys.append((printer_id, filename))
  3491. elif filename.endswith(".gcode"):
  3492. base_name = filename.rsplit(".", 1)[0]
  3493. possible_keys.append((printer_id, f"{base_name}.3mf"))
  3494. possible_keys.append((printer_id, filename))
  3495. else:
  3496. possible_keys.append((printer_id, f"{filename}.3mf"))
  3497. possible_keys.append((printer_id, filename))
  3498. # Find the archive for this print
  3499. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  3500. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  3501. archive_id = None
  3502. for key in possible_keys:
  3503. archive_id = _active_prints.pop(key, None)
  3504. if archive_id:
  3505. logger.info("Found archive %s with key %s", archive_id, key)
  3506. # Also clean up any other keys pointing to this archive
  3507. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  3508. for k in keys_to_remove:
  3509. _active_prints.pop(k, None)
  3510. break
  3511. if not archive_id:
  3512. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  3513. async with async_session() as db:
  3514. from backend.app.models.archive import PrintArchive
  3515. # Try matching by subtask_name (stored as print_name) first
  3516. if subtask_name:
  3517. result = await db.execute(
  3518. select(PrintArchive)
  3519. .where(PrintArchive.printer_id == printer_id)
  3520. .where(PrintArchive.status == "printing")
  3521. .where(
  3522. or_(
  3523. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  3524. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  3525. )
  3526. )
  3527. .order_by(PrintArchive.created_at.desc())
  3528. .limit(1)
  3529. )
  3530. archive = result.scalar_one_or_none()
  3531. if archive:
  3532. archive_id = archive.id
  3533. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  3534. # Also try by filename
  3535. if not archive_id and filename:
  3536. result = await db.execute(
  3537. select(PrintArchive)
  3538. .where(PrintArchive.printer_id == printer_id)
  3539. .where(PrintArchive.filename == filename)
  3540. .where(PrintArchive.status == "printing")
  3541. .order_by(PrintArchive.created_at.desc())
  3542. .limit(1)
  3543. )
  3544. archive = result.scalar_one_or_none()
  3545. if archive:
  3546. archive_id = archive.id
  3547. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  3548. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  3549. # auto-start files found in root on power cycle, causing ghost prints.
  3550. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  3551. try:
  3552. if subtask_name:
  3553. archive_filename: str | None = None
  3554. async with async_session() as db:
  3555. from backend.app.models.archive import PrintArchive
  3556. from backend.app.models.printer import Printer
  3557. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3558. printer = result.scalar_one_or_none()
  3559. if archive_id:
  3560. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  3561. archive_filename = archive_row.scalar_one_or_none()
  3562. if printer:
  3563. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  3564. from backend.app.utils.filename import derive_remote_filename
  3565. # Primary candidate: the exact path the dispatcher uploaded to
  3566. # (derived from archive.filename via the same rule as upload).
  3567. # Without it, a library row that ended up with a doubled
  3568. # .gcode.3mf (#1542) leaves the real file behind because the
  3569. # subtask_name + ext fallbacks below don't match what's on the
  3570. # SD card. Fallbacks remain for archive-less prints (subtask
  3571. # never resolved to an archive) and for older naming variants.
  3572. candidate_paths: list[str] = []
  3573. if archive_filename:
  3574. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  3575. for ext in (".3mf", ".gcode"):
  3576. fallback = f"/{subtask_name}{ext}"
  3577. if fallback not in candidate_paths:
  3578. candidate_paths.append(fallback)
  3579. # Three outcomes track across all candidates so the final log
  3580. # line reflects what actually happened. The A1 in #1721 always
  3581. # ends here with ``any_not_found=True`` and the others False
  3582. # — its firmware auto-cleans the SD card before our cleanup
  3583. # runs, every candidate FTP-DELE returns 550, and the old
  3584. # code burned 3 retries × 2 s × 3 candidates per print
  3585. # logging a misleading "may linger" WARNING on a successful
  3586. # print.
  3587. any_deleted = False
  3588. any_real_failure = False
  3589. any_not_found = False
  3590. for remote_path in candidate_paths:
  3591. # Retry only the FAILED case — 550 NOT_FOUND will never
  3592. # recover by waiting, so a "file isn't here" answer
  3593. # advances immediately to the next candidate without
  3594. # consuming the retry budget.
  3595. for attempt in range(1, 4):
  3596. try:
  3597. delete_result = await delete_file_async(
  3598. printer.ip_address,
  3599. printer.access_code,
  3600. remote_path,
  3601. printer_model=printer.model,
  3602. )
  3603. except Exception as e:
  3604. delete_result = DeleteResult.FAILED
  3605. logger.warning(
  3606. "SD card cleanup attempt %d/3 raised for %s: %s",
  3607. attempt,
  3608. remote_path,
  3609. e,
  3610. )
  3611. if delete_result == DeleteResult.DELETED:
  3612. any_deleted = True
  3613. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  3614. break
  3615. if delete_result == DeleteResult.NOT_FOUND:
  3616. any_not_found = True
  3617. break # 550 will not recover; try next candidate
  3618. # FAILED: real error — retry with backoff, then give up
  3619. if attempt < 3:
  3620. await asyncio.sleep(2)
  3621. else:
  3622. any_real_failure = True
  3623. logger.warning(
  3624. "SD card cleanup failed after 3 attempts for %s "
  3625. "(network/auth/transient error — file may linger on SD card)",
  3626. remote_path,
  3627. )
  3628. if not any_deleted and not any_real_failure and any_not_found:
  3629. # Every candidate said "not here." Either the printer
  3630. # firmware swept the SD card itself (common on A1) or the
  3631. # dispatcher's upload path doesn't match our candidate
  3632. # rule. Either way: nothing to clean up, no warning.
  3633. logger.debug(
  3634. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  3635. "(printer likely self-cleaned)",
  3636. printer.name,
  3637. )
  3638. except Exception as e:
  3639. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  3640. log_timing("SD card cleanup")
  3641. # Update queue item status early — must run before the archive_id early-return
  3642. # so queue items don't get stuck in "printing" when archive lookup fails.
  3643. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  3644. queue_item_id = None
  3645. queue_status = None
  3646. queue_auto_off = False
  3647. try:
  3648. from backend.app.core.database import run_with_retry
  3649. from backend.app.models.print_queue import PrintQueueItem
  3650. async def _update_queue_status(db):
  3651. nonlocal queue_item_id, queue_status, queue_auto_off
  3652. result = await db.execute(
  3653. select(PrintQueueItem)
  3654. .where(PrintQueueItem.printer_id == printer_id)
  3655. .where(PrintQueueItem.status == "printing")
  3656. )
  3657. printing_items = list(result.scalars().all())
  3658. if len(printing_items) > 1:
  3659. logger.warning(
  3660. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  3661. printer_id,
  3662. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  3663. )
  3664. item = printing_items[0] if printing_items else None
  3665. if item:
  3666. queue_status = data.get("status", "completed")
  3667. # MQTT sends "aborted" for cancelled prints; normalise to
  3668. # "cancelled" so it matches the queue schema Literal.
  3669. if queue_status == "aborted":
  3670. queue_status = "cancelled"
  3671. item.status = queue_status
  3672. item.completed_at = datetime.now(timezone.utc)
  3673. if queue_status == "failed" and not item.error_message:
  3674. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  3675. # Bump usage counters on the source library file so admins can
  3676. # sort by "last printed" and (eventually) auto-purge stale
  3677. # files — #1008.
  3678. await _bump_library_file_usage_if_completed(db, item, queue_status)
  3679. await db.commit()
  3680. queue_item_id = item.id
  3681. queue_auto_off = item.auto_off_after
  3682. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  3683. await run_with_retry(_update_queue_status, label="queue status update")
  3684. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  3685. # their own sessions and have their own error handling — no retry needed.
  3686. if queue_item_id is not None:
  3687. # MQTT relay - publish queue job completed
  3688. try:
  3689. printer_info = printer_manager.get_printer(printer_id)
  3690. await mqtt_relay.on_queue_job_completed(
  3691. job_id=queue_item_id,
  3692. filename=filename or subtask_name,
  3693. printer_id=printer_id,
  3694. printer_name=printer_info.name if printer_info else "Unknown",
  3695. status=queue_status,
  3696. )
  3697. except Exception:
  3698. pass # Don't fail if MQTT fails
  3699. # Check if queue is now empty and send notification
  3700. try:
  3701. from sqlalchemy import func as sa_func
  3702. async with async_session() as db:
  3703. count_result = await db.execute(
  3704. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  3705. )
  3706. pending_count = count_result.scalar() or 0
  3707. if pending_count == 0:
  3708. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  3709. completed_result = await db.execute(
  3710. select(sa_func.count(PrintQueueItem.id)).where(
  3711. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  3712. PrintQueueItem.completed_at >= today_start,
  3713. )
  3714. )
  3715. completed_count = completed_result.scalar() or 1
  3716. await notification_service.on_queue_completed(
  3717. completed_count=completed_count,
  3718. db=db,
  3719. )
  3720. except Exception:
  3721. pass # Don't fail if notification fails
  3722. # Handle auto_off_after - power off printer if requested (after cooldown)
  3723. if queue_auto_off:
  3724. async with async_session() as db:
  3725. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3726. plugs = list(result.scalars().all())
  3727. enabled_plugs = [p for p in plugs if p.enabled]
  3728. if enabled_plugs:
  3729. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  3730. async def cooldown_and_poweroff(pid: int, plug_ids: list[int]):
  3731. # Wait for nozzle to cool down
  3732. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  3733. # Re-fetch plugs in new session and turn off each one
  3734. async with async_session() as new_db:
  3735. for plug_id in plug_ids:
  3736. try:
  3737. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  3738. p = result.scalar_one_or_none()
  3739. if p and p.enabled:
  3740. service = await smart_plug_manager.get_service_for_plug(p, new_db)
  3741. success = await service.turn_off(p)
  3742. if success:
  3743. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  3744. else:
  3745. logger.warning("Failed to power off plug '%s' for printer %s", p.name, pid)
  3746. except Exception as e:
  3747. logger.warning("Failed to power off plug %s for printer %s: %s", plug_id, pid, e)
  3748. spawn_background_task(
  3749. cooldown_and_poweroff(printer_id, [p.id for p in enabled_plugs]),
  3750. name=f"cooldown-poweroff-{printer_id}",
  3751. )
  3752. except Exception as e:
  3753. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  3754. log_timing("Queue item update")
  3755. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  3756. # Must run before archive_id early-return so it fires for all prints (including
  3757. # prints started from BambuStudio/touchscreen that have no archive).
  3758. if data.get("status") == "completed":
  3759. try:
  3760. from backend.app.api.routes.settings import get_setting
  3761. async with async_session() as db:
  3762. threshold_str = await get_setting(db, "bed_cooled_threshold")
  3763. threshold = float(threshold_str) if threshold_str else 35.0
  3764. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  3765. async with async_session() as db:
  3766. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  3767. if providers:
  3768. _bed_cool_waiters[printer_id] = {
  3769. "threshold": threshold,
  3770. "filename": filename or subtask_name or "",
  3771. "registered_at": time.time(),
  3772. }
  3773. logger.info(
  3774. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  3775. printer_id,
  3776. threshold,
  3777. )
  3778. else:
  3779. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  3780. except Exception as e:
  3781. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  3782. # --- Track filament consumption (must run before archive_id early-return so usage
  3783. # is recorded even when auto-archive is disabled) ---
  3784. usage_results: list[dict] = []
  3785. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  3786. stored_ams_mapping = data.get("ams_mapping")
  3787. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  3788. if not stored_ams_mapping and archive_id:
  3789. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  3790. # Always drain the plate_id register on completion — the session already
  3791. # consumed it at print-start injection; leaving it would leak into the next
  3792. # print on the same archive_id (rare but possible with reprints) (#1697).
  3793. # Capture the popped value so the completion notification can scope the
  3794. # archive-level (summed-across-plates per #1593) filament + time totals
  3795. # down to the single plate that was actually printed (#1785).
  3796. notify_plate_id: int | None = None
  3797. if archive_id:
  3798. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  3799. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  3800. try:
  3801. async with async_session() as db:
  3802. from backend.app.api.routes.settings import get_setting
  3803. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3804. if not _spoolman_on or _spoolman_on.lower() != "true":
  3805. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  3806. async with async_session() as db:
  3807. usage_results = await usage_on_print_complete(
  3808. printer_id,
  3809. data,
  3810. printer_manager,
  3811. db,
  3812. archive_id=archive_id,
  3813. ams_mapping=stored_ams_mapping,
  3814. )
  3815. if usage_results:
  3816. await ws_manager.broadcast(
  3817. {
  3818. "type": "spool_usage_logged",
  3819. "printer_id": printer_id,
  3820. "usage": usage_results,
  3821. }
  3822. )
  3823. log_timing("Usage tracker")
  3824. except Exception as e:
  3825. logger.warning("Usage tracker on_print_complete failed: %s", e)
  3826. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  3827. if archive_id:
  3828. if data.get("status") == "completed":
  3829. try:
  3830. await _report_spoolman_usage(printer_id, archive_id)
  3831. log_timing("Spoolman usage report")
  3832. except Exception as e:
  3833. logger.warning("Spoolman usage reporting failed: %s", e)
  3834. else:
  3835. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  3836. try:
  3837. async with async_session() as db:
  3838. await _cleanup_spoolman_tracking(
  3839. printer_id,
  3840. archive_id,
  3841. db,
  3842. last_layer_num=data.get("last_layer_num"),
  3843. last_progress=data.get("last_progress"),
  3844. )
  3845. except Exception as e:
  3846. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  3847. log_timing("Filament usage tracking")
  3848. if not archive_id:
  3849. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  3850. # Still send print-complete/failed/stopped notifications even without an archive.
  3851. # Try to enrich with queue/library-file data so user-specific emails work too.
  3852. async def _notify_no_archive():
  3853. try:
  3854. async with async_session() as db:
  3855. from backend.app.models.library import LibraryFile
  3856. from backend.app.models.print_queue import PrintQueueItem
  3857. from backend.app.models.printer import Printer
  3858. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3859. printer_obj = result.scalar_one_or_none()
  3860. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  3861. # Try to find the most-recent queue item for this printer so we can
  3862. # recover created_by_id and estimated print time.
  3863. # NOTE: By the time this task runs the queue item status has already
  3864. # been updated to a terminal state (completed/failed/cancelled), so
  3865. # we look for recently-completed items (within the last 5 minutes).
  3866. no_archive_data: dict | None = None
  3867. try:
  3868. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  3869. q_result = await db.execute(
  3870. select(PrintQueueItem)
  3871. .where(PrintQueueItem.printer_id == printer_id)
  3872. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  3873. .where(PrintQueueItem.completed_at >= cutoff)
  3874. .order_by(PrintQueueItem.completed_at.desc())
  3875. .limit(1)
  3876. )
  3877. queue_item = q_result.scalar_one_or_none()
  3878. if queue_item:
  3879. no_archive_data = {"created_by_id": queue_item.created_by_id}
  3880. # Pull estimated time from library file when available
  3881. if queue_item.library_file_id:
  3882. lib_result = await db.execute(
  3883. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  3884. )
  3885. lib_file = lib_result.scalar_one_or_none()
  3886. if lib_file and lib_file.print_time_seconds:
  3887. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  3888. except Exception as lookup_err:
  3889. logger.debug(
  3890. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  3891. )
  3892. # Enrich with usage tracker results (captured in enclosing scope)
  3893. if usage_results:
  3894. if no_archive_data is None:
  3895. no_archive_data = {}
  3896. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  3897. if total_from_usage > 0:
  3898. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  3899. no_archive_data["usage_results"] = usage_results
  3900. # Try MQTT remaining_time for print duration when no queue/library data
  3901. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  3902. mqtt_remaining = data.get("remaining_time")
  3903. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3904. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  3905. ps = data.get("status", "completed")
  3906. logger.info(
  3907. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  3908. )
  3909. await notification_service.on_print_complete(
  3910. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  3911. )
  3912. # Send user-specific email if we have a created_by_id
  3913. if no_archive_data and no_archive_data.get("created_by_id"):
  3914. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  3915. await _dispatch_user_print_email(
  3916. ps,
  3917. no_archive_data["created_by_id"],
  3918. p_name,
  3919. raw_filename,
  3920. db,
  3921. )
  3922. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  3923. except Exception as e:
  3924. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  3925. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  3926. return
  3927. log_timing("Archive lookup")
  3928. # Update archive status
  3929. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  3930. try:
  3931. async with async_session() as db:
  3932. service = ArchiveService(db)
  3933. status = data.get("status", "completed")
  3934. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  3935. if hms_errors:
  3936. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  3937. failure_reason = derive_failure_reason(status, hms_errors)
  3938. if failure_reason:
  3939. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  3940. elif status == "failed" and hms_errors:
  3941. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  3942. await service.update_archive_status(
  3943. archive_id,
  3944. status=status,
  3945. completed_at=(
  3946. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  3947. ),
  3948. failure_reason=failure_reason,
  3949. )
  3950. logger.info(
  3951. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  3952. )
  3953. await ws_manager.send_archive_updated(
  3954. {
  3955. "id": archive_id,
  3956. "status": status,
  3957. }
  3958. )
  3959. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  3960. # MQTT relay - publish archive updated
  3961. try:
  3962. await mqtt_relay.on_archive_updated(
  3963. archive_id=archive_id,
  3964. print_name=filename or subtask_name,
  3965. status=status,
  3966. )
  3967. except Exception:
  3968. pass # Don't fail if MQTT fails
  3969. except Exception as e:
  3970. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  3971. # Continue with other operations even if archive update fails
  3972. log_timing("Archive status update")
  3973. # Write independent print log entry (separate table, never touches archives)
  3974. try:
  3975. async with async_session() as db:
  3976. from backend.app.models.archive import PrintArchive
  3977. from backend.app.services.print_log import write_log_entry
  3978. archive = await db.get(PrintArchive, archive_id)
  3979. if archive:
  3980. # Back-fill created_by_id on reprint (#730): reprint reuses the
  3981. # source archive row rather than creating a new one, so an
  3982. # archive that was auto-created from a printer-initiated
  3983. # print (created_by_id=NULL) would otherwise stay unattributed
  3984. # forever. When we have a print-session user AND the archive
  3985. # has no attribution yet, credit the current user. Never
  3986. # overwrite an existing attribution — the original uploader
  3987. # keeps ownership.
  3988. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  3989. if archive.created_by_id is None and _print_user_id is not None:
  3990. archive.created_by_id = _print_user_id
  3991. p_info = printer_manager.get_printer(printer_id)
  3992. # Per-run actuals — written to PrintLogEntry so stats reflect
  3993. # what THIS print actually used, not the source archive's
  3994. # first-run values (#1378). Helper handles the partial-print
  3995. # math (failed / cancelled / stopped get scaled to progress
  3996. # or to tracked spool deltas).
  3997. _run_status = data.get("status", "completed")
  3998. _run_grams = _compute_run_filament_grams(
  3999. _run_status,
  4000. archive.filament_used_grams,
  4001. data.get("progress"),
  4002. usage_results,
  4003. )
  4004. # Per-run cost — prefer usage_results sum. For partial prints
  4005. # we deliberately skip the topup-to-estimate logic in
  4006. # usage_tracker (which assumes the print completed); the raw
  4007. # tracked-spool sum is closer to what THIS run actually cost.
  4008. _run_cost: float | None = None
  4009. if usage_results:
  4010. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  4011. if _run_cost is None and _run_status == "completed":
  4012. _run_cost = archive.cost
  4013. await write_log_entry(
  4014. db,
  4015. archive_id=archive.id,
  4016. status=_run_status,
  4017. print_name=archive.print_name,
  4018. printer_name=p_info.name if p_info else None,
  4019. printer_id=printer_id,
  4020. started_at=archive.started_at,
  4021. completed_at=archive.completed_at,
  4022. filament_type=archive.filament_type,
  4023. filament_color=archive.filament_color,
  4024. filament_used_grams=_run_grams,
  4025. cost=_run_cost,
  4026. failure_reason=archive.failure_reason,
  4027. thumbnail_path=archive.thumbnail_path,
  4028. created_by_id=archive.created_by_id,
  4029. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  4030. )
  4031. await db.commit()
  4032. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  4033. except Exception as e:
  4034. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  4035. log_timing("Print log entry")
  4036. # Run slow operations as background tasks to avoid blocking the event loop
  4037. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  4038. async def _background_energy_calculation():
  4039. """Calculate and save energy usage in background.
  4040. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  4041. backend restart no longer loses per-print energy data).
  4042. """
  4043. try:
  4044. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  4045. async with async_session() as db:
  4046. from backend.app.models.archive import PrintArchive
  4047. archive = await db.get(PrintArchive, archive_id)
  4048. if archive is None:
  4049. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  4050. return
  4051. starting_kwh = archive.energy_start_kwh
  4052. if starting_kwh is None:
  4053. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  4054. return
  4055. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  4056. plug = plug_result.scalar_one_or_none()
  4057. if plug is None:
  4058. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  4059. return
  4060. energy = await _get_plug_energy(plug, db)
  4061. logger.info("[ENERGY-BG] Energy response: %s", energy)
  4062. if not energy or energy.get("total") is None:
  4063. logger.warning("[ENERGY-BG] No 'total' in energy response")
  4064. return
  4065. energy_used = round(energy["total"] - starting_kwh, 4)
  4066. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  4067. if energy_used < 0:
  4068. logger.warning(
  4069. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  4070. archive_id,
  4071. starting_kwh,
  4072. energy["total"],
  4073. )
  4074. return
  4075. from backend.app.api.routes.settings import get_setting
  4076. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  4077. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  4078. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  4079. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  4080. # reprint doesn't visually clobber the source archive's energy data
  4081. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  4082. from sqlalchemy import func
  4083. from backend.app.models.print_log import PrintLogEntry
  4084. existing_runs = await db.scalar(
  4085. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  4086. )
  4087. if (existing_runs or 0) <= 1:
  4088. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  4089. # we just wrote for THIS print. Either way it's the first run.
  4090. archive.energy_kwh = energy_used
  4091. archive.energy_cost = energy_cost_value
  4092. # Backfill the latest PrintLogEntry for this archive with energy
  4093. # (write_log_entry above ran before this background task completed,
  4094. # so energy fields are still NULL on that row).
  4095. latest_run = await db.execute(
  4096. select(PrintLogEntry)
  4097. .where(PrintLogEntry.archive_id == archive_id)
  4098. .order_by(PrintLogEntry.id.desc())
  4099. .limit(1)
  4100. )
  4101. run_row = latest_run.scalar_one_or_none()
  4102. if run_row is not None:
  4103. run_row.energy_kwh = energy_used
  4104. run_row.energy_cost = energy_cost_value
  4105. await db.commit()
  4106. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  4107. except Exception as e:
  4108. logger.warning("[ENERGY-BG] Failed: %s", e)
  4109. async def _background_finish_photo() -> str | None:
  4110. """Capture finish photo in background. Returns photo filename if captured."""
  4111. try:
  4112. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  4113. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  4114. async with async_session() as db:
  4115. from backend.app.api.routes.settings import get_setting
  4116. capture_enabled = await get_setting(db, "capture_finish_photo")
  4117. if capture_enabled is None or capture_enabled.lower() == "true":
  4118. from backend.app.models.printer import Printer
  4119. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4120. printer = result.scalar_one_or_none()
  4121. if printer and archive_id:
  4122. from backend.app.models.archive import PrintArchive
  4123. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4124. archive = result.scalar_one_or_none()
  4125. if archive:
  4126. import uuid
  4127. from datetime import datetime
  4128. from pathlib import Path
  4129. if archive.file_path:
  4130. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  4131. else:
  4132. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  4133. archive_dir = app_settings.archive_dir / str(archive.id)
  4134. photo_filename = None
  4135. # Prefer the timelapse last-frame source when a timelapse was
  4136. # recording — it captures the moment after the toolhead parks
  4137. # but before the bed drops, which the live-camera grab below
  4138. # would miss (#1397). Skipped for external cameras (those have
  4139. # their own framing and don't see a Bambu timelapse). Only
  4140. # runs when the USER explicitly enabled timelapse for this
  4141. # print — #1721 removed Bambuddy's force-on at dispatch
  4142. # because it caused per-layer nozzle parking on Smooth-mode
  4143. # slicer profiles.
  4144. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  4145. printer.external_camera_enabled and printer.external_camera_url
  4146. )
  4147. if prefer_timelapse_source:
  4148. photo_filename = await _capture_finish_photo_from_timelapse(
  4149. archive_id=archive_id,
  4150. archive_dir=archive_dir,
  4151. )
  4152. # #1721: replacement framing path — on_finish_photo_moment
  4153. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  4154. # parked, bed not yet dropped) and cached the JPEG bytes in
  4155. # _stage22_finish_frames. Consume them now so the saved photo
  4156. # has the better framing instead of the post-bed-drop angle
  4157. # the live-camera fallback below would give.
  4158. if not photo_filename:
  4159. # #1790: on the FINISH-state fallback path the producer
  4160. # task is dispatched back-to-back with this consumer, so
  4161. # a bare pop would race past with an empty result and
  4162. # the RTSP fallback below would collide with the
  4163. # producer's still-in-flight grab (single-client RTSP
  4164. # on Bambu printers). Wait for the producer to finish
  4165. # or give up before touching the cache.
  4166. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  4167. if in_flight is not None:
  4168. try:
  4169. await asyncio.wait_for(in_flight.wait(), timeout=20.0)
  4170. except asyncio.TimeoutError:
  4171. logger.warning(
  4172. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  4173. printer_id,
  4174. )
  4175. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  4176. if cached_frame:
  4177. photos_dir = archive_dir / "photos"
  4178. photos_dir.mkdir(parents=True, exist_ok=True)
  4179. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4180. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4181. photo_path = photos_dir / photo_filename
  4182. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  4183. logger.info(
  4184. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  4185. photo_filename,
  4186. len(cached_frame),
  4187. )
  4188. # Fallback chain: external camera → buffered live frame →
  4189. # fresh RTSP capture. Only runs if the timelapse path above
  4190. # didn't already produce a photo.
  4191. if not photo_filename:
  4192. if printer.external_camera_enabled and printer.external_camera_url:
  4193. logger.info("[PHOTO-BG] Using external camera")
  4194. from backend.app.services.external_camera import capture_frame
  4195. frame_data = await capture_frame(
  4196. printer.external_camera_url,
  4197. printer.external_camera_type or "mjpeg",
  4198. snapshot_url=printer.external_camera_snapshot_url,
  4199. )
  4200. if frame_data:
  4201. photos_dir = archive_dir / "photos"
  4202. photos_dir.mkdir(parents=True, exist_ok=True)
  4203. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4204. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4205. photo_path = photos_dir / photo_filename
  4206. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  4207. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  4208. else:
  4209. # Check if camera stream is active - use buffered frame to avoid freeze
  4210. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  4211. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  4212. active_chamber_for_printer = [
  4213. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  4214. ]
  4215. buffered_frame = get_buffered_frame(printer_id)
  4216. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  4217. # Use frame from active stream
  4218. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  4219. photos_dir = archive_dir / "photos"
  4220. photos_dir.mkdir(parents=True, exist_ok=True)
  4221. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4222. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4223. photo_path = photos_dir / photo_filename
  4224. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  4225. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  4226. else:
  4227. # No active stream - capture new frame
  4228. from backend.app.services.camera import capture_finish_photo
  4229. photo_filename = await capture_finish_photo(
  4230. printer_id=printer_id,
  4231. ip_address=printer.ip_address,
  4232. access_code=printer.access_code,
  4233. model=printer.model,
  4234. archive_dir=archive_dir,
  4235. )
  4236. if photo_filename:
  4237. photos = archive.photos or []
  4238. photos.append(photo_filename)
  4239. archive.photos = photos
  4240. await db.commit()
  4241. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  4242. if photo_filename:
  4243. return photo_filename
  4244. return None
  4245. except Exception as e:
  4246. logger.warning("[PHOTO-BG] Failed: %s", e)
  4247. return None
  4248. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  4249. # Photo capture task - result will be used by notifications
  4250. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  4251. log_timing("Background tasks scheduled (energy, photo)")
  4252. # Also run smart plug, notifications, and maintenance as background tasks
  4253. print_status = data.get("status", "completed")
  4254. async def _background_smart_plug():
  4255. """Handle smart plug automation in background."""
  4256. try:
  4257. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  4258. async with async_session() as db:
  4259. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  4260. logger.info("[AUTO-OFF-BG] Completed")
  4261. except Exception as e:
  4262. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  4263. async def _background_notifications(finish_photo_filename: str | None = None):
  4264. """Send print complete notifications in background."""
  4265. try:
  4266. logger.info(
  4267. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  4268. )
  4269. async with async_session() as db:
  4270. from backend.app.models.archive import PrintArchive
  4271. from backend.app.models.printer import Printer
  4272. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4273. printer = result.scalar_one_or_none()
  4274. printer_name = printer.name if printer else f"Printer {printer_id}"
  4275. archive_data = None
  4276. if archive_id:
  4277. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4278. archive = archive_result.scalar_one_or_none()
  4279. if archive:
  4280. # Actual elapsed time from started_at/completed_at when both are
  4281. # populated (every terminal status sets completed_at after #1198).
  4282. # Falls back to None so the notification path can decide whether to
  4283. # render the slicer estimate as a last resort.
  4284. actual_time_seconds = None
  4285. if archive.started_at and archive.completed_at:
  4286. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  4287. if elapsed > 0:
  4288. actual_time_seconds = int(elapsed)
  4289. archive_data = {
  4290. "print_time_seconds": archive.print_time_seconds,
  4291. "actual_time_seconds": actual_time_seconds,
  4292. "actual_filament_grams": archive.filament_used_grams,
  4293. "failure_reason": archive.failure_reason,
  4294. "created_by_id": archive.created_by_id,
  4295. }
  4296. # Scale filament usage for partial prints
  4297. if print_status != "completed" and archive.filament_used_grams:
  4298. progress = data.get("progress") or 0
  4299. scale = _partial_progress_scale(progress)
  4300. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  4301. archive_data["progress"] = progress
  4302. # Pass per-slot data from archive.extra_data
  4303. if archive.extra_data and archive.extra_data.get("filament_slots"):
  4304. slots = archive.extra_data["filament_slots"]
  4305. if print_status != "completed":
  4306. scale = _partial_progress_scale(data.get("progress"))
  4307. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  4308. archive_data["filament_slots"] = slots
  4309. # Scope project-summed totals down to the plate that was
  4310. # actually printed — see _scope_notification_archive_data_to_plate
  4311. # for the why (#1785).
  4312. archive_data = _scope_notification_archive_data_to_plate(
  4313. archive_data,
  4314. archive.file_path,
  4315. notify_plate_id,
  4316. print_status,
  4317. data.get("progress"),
  4318. app_settings.base_dir,
  4319. )
  4320. # Enrich filament_grams from usage_results when archive has no 3MF data
  4321. if not archive_data.get("actual_filament_grams") and usage_results:
  4322. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  4323. if total_from_usage > 0:
  4324. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  4325. # Pass usage tracker results for AMS slot info in notifications
  4326. if usage_results:
  4327. archive_data["usage_results"] = usage_results
  4328. # Add finish photo URL and image bytes if available
  4329. if finish_photo_filename:
  4330. from backend.app.api.routes.settings import get_setting
  4331. external_url = await get_setting(db, "external_url")
  4332. if external_url:
  4333. external_url = external_url.rstrip("/")
  4334. archive_data["finish_photo_url"] = (
  4335. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  4336. )
  4337. else:
  4338. # Fallback to relative URL (won't work for external services)
  4339. archive_data["finish_photo_url"] = (
  4340. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  4341. )
  4342. # Read finish photo bytes for image attachment (e.g. Pushover)
  4343. try:
  4344. from pathlib import Path
  4345. photo_path = (
  4346. app_settings.base_dir
  4347. / Path(archive.file_path).parent
  4348. / "photos"
  4349. / finish_photo_filename
  4350. )
  4351. if photo_path.exists():
  4352. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  4353. if len(photo_bytes) <= 2_500_000:
  4354. archive_data["image_data"] = photo_bytes
  4355. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  4356. else:
  4357. logger.warning(
  4358. f"[NOTIFY-BG] Finish photo too large for attachment: "
  4359. f"{len(photo_bytes)} bytes"
  4360. )
  4361. except Exception as e:
  4362. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  4363. await notification_service.on_print_complete(
  4364. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  4365. )
  4366. # Send user-specific email notification
  4367. if archive_data:
  4368. created_by_id = archive_data.get("created_by_id")
  4369. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  4370. await _dispatch_user_print_email(
  4371. print_status,
  4372. created_by_id,
  4373. printer_name,
  4374. raw_filename,
  4375. db,
  4376. )
  4377. logger.info("[NOTIFY-BG] Completed")
  4378. except Exception as e:
  4379. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  4380. async def _background_maintenance_check():
  4381. """Check for maintenance due in background."""
  4382. if print_status != "completed":
  4383. return
  4384. try:
  4385. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  4386. async with async_session() as db:
  4387. from backend.app.models.printer import Printer
  4388. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4389. printer = result.scalar_one_or_none()
  4390. printer_name = printer.name if printer else f"Printer {printer_id}"
  4391. await ensure_default_types(db)
  4392. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  4393. items_needing_attention = [
  4394. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  4395. for item in overview.maintenance_items
  4396. if item.enabled and (item.is_due or item.is_warning)
  4397. ]
  4398. if items_needing_attention:
  4399. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  4400. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  4401. # MQTT relay - publish maintenance alerts
  4402. for item in items_needing_attention:
  4403. try:
  4404. await mqtt_relay.on_maintenance_alert(
  4405. printer_id=printer_id,
  4406. printer_name=printer_name,
  4407. maintenance_type=item["name"],
  4408. current_value=0, # Not easily available here
  4409. threshold=0, # Not easily available here
  4410. )
  4411. except Exception:
  4412. pass # Don't fail if MQTT fails
  4413. else:
  4414. logger.info("[MAINT-BG] Completed (no items need attention)")
  4415. except Exception as e:
  4416. logger.warning("[MAINT-BG] Failed: %s", e)
  4417. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  4418. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  4419. # Notification task waits for photo capture to complete first (with timeout).
  4420. # When a timelapse was recording, photo sourcing polls the per-print
  4421. # timelapse for up to 60s (#1397) — extend the budget so the notification
  4422. # carries the correct bed-up photo instead of falling through to the
  4423. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  4424. photo_wait_timeout = 75 if data.get("timelapse_was_active") else 45
  4425. async def _photo_then_notify():
  4426. """Wait for photo capture, then send notification with photo URL."""
  4427. finish_photo = None
  4428. try:
  4429. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  4430. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  4431. except TimeoutError:
  4432. logger.warning(
  4433. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  4434. photo_wait_timeout,
  4435. )
  4436. except Exception as e:
  4437. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  4438. try:
  4439. await _background_notifications(finish_photo)
  4440. except Exception as e:
  4441. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  4442. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  4443. # Stitch external camera layer timelapse if session was active
  4444. print_status = data.get("status", "completed")
  4445. async def _background_layer_timelapse():
  4446. """Stitch layer timelapse and attach to archive."""
  4447. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  4448. try:
  4449. if print_status == "completed":
  4450. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  4451. timelapse_path = await tl_complete(printer_id)
  4452. if timelapse_path and archive_id:
  4453. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  4454. async with async_session() as db:
  4455. service = ArchiveService(db)
  4456. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  4457. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  4458. # Clean up the temp file
  4459. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  4460. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  4461. elif timelapse_path:
  4462. # Timelapse created but no archive - just clean up
  4463. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  4464. else:
  4465. # Print failed or cancelled - cancel timelapse session
  4466. cancel_session(printer_id)
  4467. logger.info(
  4468. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  4469. )
  4470. except Exception as e:
  4471. logger.warning("[LAYER-TL] Failed: %s", e)
  4472. # Try to cancel session on error
  4473. try:
  4474. cancel_session(printer_id)
  4475. except Exception:
  4476. pass # Best-effort timelapse session cancellation on error
  4477. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  4478. log_timing("All background tasks scheduled")
  4479. # Auto-scan for timelapse if recording was active during the print
  4480. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  4481. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  4482. # Schedule timelapse scan as background task with retries
  4483. # The printer needs time to encode the video after print completion
  4484. baseline = _timelapse_baselines.pop(printer_id, None)
  4485. spawn_background_task(
  4486. _scan_for_timelapse_with_retries(archive_id, baseline),
  4487. name=f"scan-timelapse-{archive_id}",
  4488. )
  4489. log_timing("Timelapse scan scheduled")
  4490. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  4491. # AMS sensor history recording
  4492. _ams_history_task: asyncio.Task | None = None
  4493. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  4494. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  4495. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  4496. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  4497. _ams_alarm_cooldown: dict[str, datetime] = {}
  4498. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  4499. def _ams_has_filament(ams_data: dict) -> bool:
  4500. """True if this AMS unit has at least one tray slot holding filament.
  4501. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  4502. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  4503. still report sensor readings, but those readings are ambient and not
  4504. actionable: no filament to dry, no humidity to push down. #1619 — gate
  4505. humidity/temperature alarms on this check so empty units don't generate
  4506. hourly noise. Sensor history still records regardless so the UI charts
  4507. stay continuous.
  4508. Fallback path inspects the `tray` array's `tray_type` fields for setups
  4509. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  4510. """
  4511. bits = ams_data.get("tray_exist_bits")
  4512. if isinstance(bits, str) and bits.strip():
  4513. try:
  4514. return int(bits, 16) > 0
  4515. except ValueError:
  4516. pass
  4517. trays = ams_data.get("tray")
  4518. if isinstance(trays, list):
  4519. return any(
  4520. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  4521. )
  4522. return False
  4523. async def record_ams_history():
  4524. """Background task to record AMS humidity and temperature data."""
  4525. logger = logging.getLogger(__name__)
  4526. # Wait a short time for MQTT connections to establish on startup
  4527. await asyncio.sleep(10)
  4528. while True:
  4529. try:
  4530. from backend.app.models.ams_history import AMSSensorHistory
  4531. from backend.app.models.printer import Printer
  4532. from backend.app.models.settings import Settings
  4533. async with async_session() as db:
  4534. # Get all active printers
  4535. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  4536. printers = result.scalars().all()
  4537. # Get alarm thresholds from settings
  4538. humidity_threshold = 60.0 # Default: fair threshold
  4539. temp_threshold = 35.0 # Default: fair threshold
  4540. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  4541. setting = result.scalar_one_or_none()
  4542. if setting:
  4543. try:
  4544. humidity_threshold = float(setting.value)
  4545. except (ValueError, TypeError):
  4546. pass # Keep default threshold if stored value is invalid
  4547. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  4548. setting = result.scalar_one_or_none()
  4549. if setting:
  4550. try:
  4551. temp_threshold = float(setting.value)
  4552. except (ValueError, TypeError):
  4553. pass # Keep default threshold if stored value is invalid
  4554. # Per-filament humidity threshold overrides (#1605) — resolved
  4555. # per-AMS below from the loaded tray types. Reuses the same
  4556. # resolver as the auto-drying scheduler so behavior stays in
  4557. # lockstep across both consumers.
  4558. from backend.app.services.print_scheduler import PrintScheduler
  4559. per_type_humidity_thresholds: dict[str, int] = {}
  4560. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  4561. setting = result.scalar_one_or_none()
  4562. if setting and setting.value:
  4563. try:
  4564. raw = json.loads(setting.value)
  4565. if isinstance(raw, dict):
  4566. for k, v in raw.items():
  4567. try:
  4568. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  4569. v
  4570. )
  4571. except (TypeError, ValueError):
  4572. continue
  4573. except (ValueError, TypeError):
  4574. pass # Invalid JSON → no overrides, fall through to global threshold
  4575. recorded_count = 0
  4576. for printer in printers:
  4577. # Get current state from printer manager
  4578. state = printer_manager.get_status(printer.id)
  4579. if not state or not state.connected or not state.raw_data:
  4580. continue # Skip disconnected printers - don't use stale data
  4581. raw_data = state.raw_data
  4582. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  4583. continue
  4584. # Record data for each AMS unit
  4585. for ams_data in raw_data["ams"]:
  4586. ams_id = int(ams_data.get("id", 0))
  4587. # Get humidity (prefer humidity_raw)
  4588. humidity_raw = ams_data.get("humidity_raw")
  4589. humidity_idx = ams_data.get("humidity")
  4590. humidity = None
  4591. if humidity_raw is not None:
  4592. try:
  4593. humidity = float(humidity_raw)
  4594. except (ValueError, TypeError):
  4595. pass # Skip unparseable humidity; will try fallback
  4596. if humidity is None and humidity_idx is not None:
  4597. try:
  4598. humidity = float(humidity_idx)
  4599. except (ValueError, TypeError):
  4600. pass # Skip unparseable humidity index value
  4601. # Get temperature
  4602. temperature = None
  4603. temp_str = ams_data.get("temp")
  4604. if temp_str is not None:
  4605. try:
  4606. temperature = float(temp_str)
  4607. except (ValueError, TypeError):
  4608. pass # Skip unparseable temperature value
  4609. # Skip if no data
  4610. if humidity is None and temperature is None:
  4611. continue
  4612. # Record the data point
  4613. history = AMSSensorHistory(
  4614. printer_id=printer.id,
  4615. ams_id=ams_id,
  4616. humidity=humidity,
  4617. humidity_raw=float(humidity_raw) if humidity_raw else None,
  4618. temperature=temperature,
  4619. )
  4620. db.add(history)
  4621. recorded_count += 1
  4622. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  4623. is_ams_ht = ams_id >= 128
  4624. if is_ams_ht:
  4625. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  4626. else:
  4627. ams_label = f"AMS-{chr(65 + ams_id)}"
  4628. # Skip alarm dispatch for empty AMS units — humidity /
  4629. # temperature readings are ambient with no filament to
  4630. # protect, and the hourly notification just becomes
  4631. # noise. Sensor history was already recorded above so
  4632. # the UI charts stay continuous (#1619). Per-AMS check
  4633. # so a multi-AMS setup with one loaded + one empty
  4634. # still alarms on the loaded unit.
  4635. if not _ams_has_filament(ams_data):
  4636. continue
  4637. # Resolve per-filament humidity threshold for this AMS
  4638. # unit (#1605). Falls back to the global ams_humidity_fair
  4639. # when no per-type overrides are configured.
  4640. trays = ams_data.get("tray", []) or []
  4641. effective_humidity_threshold = float(
  4642. PrintScheduler.resolve_humidity_threshold(
  4643. trays, per_type_humidity_thresholds, int(humidity_threshold)
  4644. )
  4645. )
  4646. # Check humidity alarm (only if above threshold)
  4647. if humidity is not None and humidity > effective_humidity_threshold:
  4648. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  4649. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  4650. now = datetime.now(timezone.utc)
  4651. if (
  4652. last_alarm is None
  4653. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  4654. ):
  4655. _ams_alarm_cooldown[cooldown_key] = now
  4656. logger.info(
  4657. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  4658. )
  4659. try:
  4660. # Call different notification method based on AMS type
  4661. if is_ams_ht:
  4662. await notification_service.on_ams_ht_humidity_high(
  4663. printer.id,
  4664. printer.name,
  4665. ams_label,
  4666. humidity,
  4667. effective_humidity_threshold,
  4668. db,
  4669. )
  4670. else:
  4671. await notification_service.on_ams_humidity_high(
  4672. printer.id,
  4673. printer.name,
  4674. ams_label,
  4675. humidity,
  4676. effective_humidity_threshold,
  4677. db,
  4678. )
  4679. except Exception as e:
  4680. logger.warning("Failed to send humidity alarm: %s", e)
  4681. # Check temperature alarm (only if above threshold)
  4682. if temperature is not None and temperature > temp_threshold:
  4683. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  4684. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  4685. now = datetime.now(timezone.utc)
  4686. if (
  4687. last_alarm is None
  4688. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  4689. ):
  4690. _ams_alarm_cooldown[cooldown_key] = now
  4691. logger.info(
  4692. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  4693. )
  4694. try:
  4695. # Call different notification method based on AMS type
  4696. if is_ams_ht:
  4697. await notification_service.on_ams_ht_temperature_high(
  4698. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  4699. )
  4700. else:
  4701. await notification_service.on_ams_temperature_high(
  4702. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  4703. )
  4704. except Exception as e:
  4705. logger.warning("Failed to send temperature alarm: %s", e)
  4706. await db.commit()
  4707. if recorded_count > 0:
  4708. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  4709. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  4710. global _ams_cleanup_counter
  4711. _ams_cleanup_counter += 1
  4712. if _ams_cleanup_counter >= 288:
  4713. _ams_cleanup_counter = 0
  4714. # Get retention days from settings
  4715. from backend.app.models.settings import Settings
  4716. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  4717. setting = result.scalar_one_or_none()
  4718. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  4719. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  4720. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  4721. await db.commit()
  4722. if result.rowcount > 0:
  4723. logger.info(
  4724. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  4725. )
  4726. # Wait until next recording interval
  4727. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  4728. except asyncio.CancelledError:
  4729. break
  4730. except Exception as e:
  4731. logger.warning("AMS history recording failed: %s", e)
  4732. await asyncio.sleep(60) # Wait a bit before retrying
  4733. def start_ams_history_recording():
  4734. """Start the AMS history recording background task."""
  4735. global _ams_history_task
  4736. if _ams_history_task is None:
  4737. _ams_history_task = asyncio.create_task(record_ams_history())
  4738. logging.getLogger(__name__).info("AMS history recording started")
  4739. def stop_ams_history_recording():
  4740. """Stop the AMS history recording background task."""
  4741. global _ams_history_task
  4742. if _ams_history_task:
  4743. _ams_history_task.cancel()
  4744. _ams_history_task = None
  4745. logging.getLogger(__name__).info("AMS history recording stopped")
  4746. # Printer sensor history recording (nozzle / bed / chamber)
  4747. _printer_sensor_history_task: asyncio.Task | None = None
  4748. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  4749. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  4750. _printer_sensor_cleanup_counter = 0
  4751. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  4752. # MQTT parser writes, so we don't need to handle per-model field aliases here
  4753. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  4754. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  4755. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  4756. _SENSOR_TARGET_KEYS = {
  4757. "nozzle": "nozzle_target",
  4758. "nozzle_2": "nozzle_2_target",
  4759. "bed": "bed_target",
  4760. "chamber": "chamber_target",
  4761. }
  4762. async def record_printer_sensor_history():
  4763. """Background task to record nozzle / bed / chamber readings.
  4764. Pulls from `state.temperatures` (already normalised across all printer
  4765. models by the MQTT parser) rather than re-parsing raw_data, so we get
  4766. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  4767. """
  4768. logger = logging.getLogger(__name__)
  4769. await asyncio.sleep(10)
  4770. while True:
  4771. try:
  4772. from backend.app.models.printer import Printer
  4773. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  4774. from backend.app.models.settings import Settings
  4775. async with async_session() as db:
  4776. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  4777. printers = result.scalars().all()
  4778. recorded_count = 0
  4779. for printer in printers:
  4780. state = printer_manager.get_status(printer.id)
  4781. if not state or not state.connected:
  4782. continue
  4783. temps = getattr(state, "temperatures", None) or {}
  4784. if not isinstance(temps, dict):
  4785. continue
  4786. for kind in _SENSOR_KINDS:
  4787. if kind not in temps:
  4788. continue
  4789. try:
  4790. value = float(temps[kind])
  4791. except (ValueError, TypeError):
  4792. continue
  4793. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  4794. target_val: float | None = None
  4795. if target_raw is not None:
  4796. try:
  4797. target_val = float(target_raw)
  4798. except (ValueError, TypeError):
  4799. target_val = None
  4800. db.add(
  4801. PrinterSensorHistory(
  4802. printer_id=printer.id,
  4803. sensor_kind=kind,
  4804. value=value,
  4805. target=target_val,
  4806. )
  4807. )
  4808. recorded_count += 1
  4809. await db.commit()
  4810. if recorded_count > 0:
  4811. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  4812. # Periodic cleanup — once every ~24h at this interval.
  4813. global _printer_sensor_cleanup_counter
  4814. _printer_sensor_cleanup_counter += 1
  4815. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  4816. if _printer_sensor_cleanup_counter >= cleanup_every:
  4817. _printer_sensor_cleanup_counter = 0
  4818. result = await db.execute(
  4819. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  4820. )
  4821. setting = result.scalar_one_or_none()
  4822. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  4823. cutoff = datetime.utcnow() - timedelta(days=retention_days)
  4824. cleanup = await db.execute(
  4825. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  4826. )
  4827. await db.commit()
  4828. if cleanup.rowcount > 0:
  4829. logger.info(
  4830. "Cleaned up %s old printer sensor history entries (older than %s days)",
  4831. cleanup.rowcount,
  4832. retention_days,
  4833. )
  4834. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  4835. except asyncio.CancelledError:
  4836. break
  4837. except Exception as e:
  4838. logger.warning("Printer sensor history recording failed: %s", e)
  4839. await asyncio.sleep(60)
  4840. def start_printer_sensor_history_recording():
  4841. global _printer_sensor_history_task
  4842. if _printer_sensor_history_task is None:
  4843. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  4844. logging.getLogger(__name__).info("Printer sensor history recording started")
  4845. def stop_printer_sensor_history_recording():
  4846. global _printer_sensor_history_task
  4847. if _printer_sensor_history_task:
  4848. _printer_sensor_history_task.cancel()
  4849. _printer_sensor_history_task = None
  4850. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  4851. # Printer runtime tracking
  4852. _runtime_tracking_task: asyncio.Task | None = None
  4853. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  4854. async def track_printer_runtime():
  4855. """Background task to track printer active runtime (RUNNING state only).
  4856. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  4857. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  4858. which track mechanical wear. Pause time has no motion and no wear, so
  4859. counting it inflates maintenance warnings (#1521).
  4860. """
  4861. logger = logging.getLogger(__name__)
  4862. # Wait for MQTT connections to establish on startup
  4863. await asyncio.sleep(15)
  4864. while True:
  4865. try:
  4866. from backend.app.models.printer import Printer
  4867. # Fetch printer IDs in a short-lived read-only session
  4868. async with async_session() as db:
  4869. result = await db.execute(
  4870. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  4871. Printer.is_active.is_(True)
  4872. )
  4873. )
  4874. printer_rows = result.all()
  4875. now = datetime.now(timezone.utc)
  4876. updated_count = 0
  4877. # Update each printer in its own short session to minimise write-lock
  4878. # hold time and avoid blocking critical commits like queue status
  4879. # updates (#897).
  4880. for pid, pname, runtime_secs, last_update in printer_rows:
  4881. state = printer_manager.get_status(pid)
  4882. if not state:
  4883. logger.debug("[%s] Runtime tracking: no state available", pname)
  4884. continue
  4885. if not state.connected:
  4886. logger.debug("[%s] Runtime tracking: not connected", pname)
  4887. continue
  4888. needs_commit = False
  4889. new_runtime = runtime_secs
  4890. new_last_update = last_update
  4891. if state.state == "RUNNING":
  4892. if last_update:
  4893. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  4894. elapsed = (now - lu).total_seconds()
  4895. if elapsed > 0:
  4896. new_runtime = runtime_secs + int(elapsed)
  4897. updated_count += 1
  4898. needs_commit = True
  4899. logger.debug(
  4900. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  4901. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  4902. )
  4903. else:
  4904. needs_commit = True
  4905. logger.debug("[%s] Runtime tracking: first active detection", pname)
  4906. new_last_update = now
  4907. else:
  4908. if last_update is not None:
  4909. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  4910. new_last_update = None
  4911. needs_commit = True
  4912. if needs_commit:
  4913. try:
  4914. async with async_session() as db:
  4915. result = await db.execute(select(Printer).where(Printer.id == pid))
  4916. printer = result.scalar_one_or_none()
  4917. if printer:
  4918. printer.runtime_seconds = new_runtime
  4919. printer.last_runtime_update = new_last_update
  4920. await db.commit()
  4921. except Exception as e:
  4922. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  4923. if updated_count > 0:
  4924. logger.debug("Updated runtime for %s printer(s)", updated_count)
  4925. except asyncio.CancelledError:
  4926. logger.info("Runtime tracking cancelled")
  4927. break
  4928. except Exception as e:
  4929. logger.warning("Runtime tracking failed: %s", e)
  4930. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  4931. def start_runtime_tracking():
  4932. """Start the printer runtime tracking background task."""
  4933. global _runtime_tracking_task
  4934. if _runtime_tracking_task is None:
  4935. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  4936. logging.getLogger(__name__).info("Printer runtime tracking started")
  4937. def stop_runtime_tracking():
  4938. """Stop the printer runtime tracking background task."""
  4939. global _runtime_tracking_task
  4940. if _runtime_tracking_task:
  4941. _runtime_tracking_task.cancel()
  4942. _runtime_tracking_task = None
  4943. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  4944. # SpoolBuddy device watchdog
  4945. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  4946. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  4947. async def _spoolbuddy_watchdog_loop():
  4948. """Periodic check for SpoolBuddy devices that have gone offline."""
  4949. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  4950. while True:
  4951. try:
  4952. await spoolbuddy_watchdog()
  4953. except asyncio.CancelledError:
  4954. break
  4955. except Exception as e:
  4956. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  4957. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  4958. def start_spoolbuddy_watchdog():
  4959. global _spoolbuddy_watchdog_task
  4960. if _spoolbuddy_watchdog_task is None:
  4961. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  4962. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  4963. def stop_spoolbuddy_watchdog():
  4964. global _spoolbuddy_watchdog_task
  4965. if _spoolbuddy_watchdog_task:
  4966. _spoolbuddy_watchdog_task.cancel()
  4967. _spoolbuddy_watchdog_task = None
  4968. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  4969. # Camera stream orphan cleanup
  4970. _camera_cleanup_task: asyncio.Task | None = None
  4971. CAMERA_CLEANUP_INTERVAL = 60
  4972. async def _camera_cleanup_loop():
  4973. """Periodically clean up orphaned ffmpeg processes."""
  4974. from backend.app.api.routes.camera import cleanup_orphaned_streams
  4975. while True:
  4976. try:
  4977. await cleanup_orphaned_streams()
  4978. except asyncio.CancelledError:
  4979. break
  4980. except Exception as e:
  4981. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  4982. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  4983. def start_camera_cleanup():
  4984. global _camera_cleanup_task
  4985. if _camera_cleanup_task is None:
  4986. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  4987. logging.getLogger(__name__).info("Camera stream cleanup started")
  4988. def stop_camera_cleanup():
  4989. global _camera_cleanup_task
  4990. if _camera_cleanup_task:
  4991. _camera_cleanup_task.cancel()
  4992. _camera_cleanup_task = None
  4993. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  4994. # ---------------------------------------------------------------------------
  4995. # Expected-print TTL eviction
  4996. # ---------------------------------------------------------------------------
  4997. def _evict_stale_expected_prints() -> None:
  4998. """Remove entries from _expected_prints / _expected_print_creators that are
  4999. older than _EXPECTED_PRINT_TTL_SECONDS.
  5000. This prevents unbounded growth when a print is registered (via
  5001. register_expected_print) but on_print_start never fires — e.g. because the
  5002. printer disconnects, the app restarts, or the print is started directly from
  5003. the printer panel without going through the queue.
  5004. """
  5005. # Use monotonic time so the TTL is unaffected by system clock adjustments
  5006. # (e.g. NTP sync, DST changes).
  5007. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  5008. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  5009. if not stale_keys:
  5010. return
  5011. evicted_archive_ids: set[int] = set()
  5012. for key in stale_keys:
  5013. archive_id = _expected_prints.pop(key, None)
  5014. if archive_id is not None:
  5015. evicted_archive_ids.add(archive_id)
  5016. _expected_print_creators.pop(key, None)
  5017. _expected_print_registered_at.pop(key, None)
  5018. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  5019. # that have no remaining live keys in _expected_prints (all variants
  5020. # were just evicted).
  5021. live_archive_ids = set(_expected_prints.values())
  5022. for archive_id in evicted_archive_ids:
  5023. if archive_id not in live_archive_ids:
  5024. _print_ams_mappings.pop(archive_id, None)
  5025. _print_plate_ids.pop(archive_id, None)
  5026. logging.getLogger(__name__).info(
  5027. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  5028. )
  5029. async def _expected_prints_cleanup_loop() -> None:
  5030. """Background task: periodically evict stale expected-print entries."""
  5031. while True:
  5032. try:
  5033. _evict_stale_expected_prints()
  5034. except asyncio.CancelledError:
  5035. raise
  5036. except Exception as e:
  5037. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  5038. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  5039. def start_expected_prints_cleanup() -> None:
  5040. global _expected_prints_cleanup_task
  5041. if _expected_prints_cleanup_task is None:
  5042. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  5043. logging.getLogger(__name__).info("Expected prints cleanup started")
  5044. def stop_expected_prints_cleanup() -> None:
  5045. global _expected_prints_cleanup_task
  5046. if _expected_prints_cleanup_task:
  5047. _expected_prints_cleanup_task.cancel()
  5048. _expected_prints_cleanup_task = None
  5049. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  5050. # ---------------------------------------------------------------------------
  5051. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  5052. # ---------------------------------------------------------------------------
  5053. _auth_cleanup_task: asyncio.Task | None = None
  5054. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  5055. async def _run_auth_cleanup() -> None:
  5056. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  5057. from backend.app.core.database import async_session
  5058. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  5059. from backend.app.models.user_totp import UserTOTP
  5060. now = datetime.now(timezone.utc)
  5061. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  5062. try:
  5063. async with async_session() as db:
  5064. stale_cutoff = now - timedelta(hours=1)
  5065. result = await db.execute(
  5066. select(UserTOTP).where(
  5067. UserTOTP.is_enabled.is_(False),
  5068. UserTOTP.created_at < stale_cutoff,
  5069. )
  5070. )
  5071. stale_records = result.scalars().all()
  5072. if stale_records:
  5073. for rec in stale_records:
  5074. await db.delete(rec)
  5075. await db.commit()
  5076. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  5077. except Exception as e:
  5078. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  5079. # Remove expired revoked-JTI entries (they are no longer needed once the
  5080. # original token's exp has passed — the token would be rejected by JWT
  5081. # signature verification regardless).
  5082. try:
  5083. async with async_session() as db:
  5084. await db.execute(
  5085. delete(AuthEphemeralToken).where(
  5086. AuthEphemeralToken.token_type == "revoked_jti",
  5087. AuthEphemeralToken.expires_at < now,
  5088. )
  5089. )
  5090. await db.commit()
  5091. except Exception as e:
  5092. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  5093. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  5094. # Events outside this window can never affect rate-limit decisions — they only
  5095. # consume DB space. Use the same window constant as the rate limiter so the
  5096. # two are always in sync.
  5097. try:
  5098. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  5099. async with async_session() as db:
  5100. await db.execute(
  5101. delete(AuthRateLimitEvent).where(
  5102. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  5103. )
  5104. )
  5105. await db.commit()
  5106. except Exception as e:
  5107. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  5108. async def _auth_cleanup_loop() -> None:
  5109. """Periodic background task: run auth cleanup every hour."""
  5110. while True:
  5111. try:
  5112. await _run_auth_cleanup()
  5113. except asyncio.CancelledError:
  5114. break
  5115. except Exception as e:
  5116. logging.warning("Auth cleanup loop error: %s", e)
  5117. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  5118. def start_auth_cleanup() -> None:
  5119. global _auth_cleanup_task
  5120. if _auth_cleanup_task is None:
  5121. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  5122. logging.getLogger(__name__).info("Auth periodic cleanup started")
  5123. def stop_auth_cleanup() -> None:
  5124. global _auth_cleanup_task
  5125. if _auth_cleanup_task:
  5126. _auth_cleanup_task.cancel()
  5127. _auth_cleanup_task = None
  5128. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  5129. @asynccontextmanager
  5130. async def lifespan(app: FastAPI):
  5131. # Startup
  5132. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  5133. # anything else can spawn tasks that might trip it.
  5134. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  5135. install_proactor_reset_filter()
  5136. await init_db()
  5137. # Register an app-scoped httpx client for Bambu Cloud services so
  5138. # per-request BambuCloudService instances reuse the same connection pool
  5139. # (important for routes like /cloud/filament-info that chain many
  5140. # get_setting_detail calls). The shared client stores no region/token
  5141. # state, so the per-request ownership pattern that fixed the region-bleed
  5142. # bug is preserved.
  5143. import httpx as _httpx
  5144. from backend.app.services.bambu_cloud import set_shared_http_client
  5145. from backend.app.services.makerworld import (
  5146. set_shared_http_client as set_shared_makerworld_http_client,
  5147. )
  5148. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  5149. set_shared_http_client(_shared_cloud_http_client)
  5150. # Reuse the same connection pool for MakerWorld — different host, same
  5151. # keep-alive pool saves a TLS handshake per request.
  5152. set_shared_makerworld_http_client(_shared_cloud_http_client)
  5153. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  5154. # This can happen when a print was cancelled mid-print on versions before this fix.
  5155. try:
  5156. async with async_session() as db:
  5157. from backend.app.models.print_queue import PrintQueueItem
  5158. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  5159. aborted_items = result.scalars().all()
  5160. if aborted_items:
  5161. for item in aborted_items:
  5162. item.status = "cancelled"
  5163. await db.commit()
  5164. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  5165. except Exception as e:
  5166. logging.warning("Failed to fix aborted queue items: %s", e)
  5167. # Restore debug logging state from previous session
  5168. await init_debug_logging()
  5169. # Set up printer manager callbacks
  5170. loop = asyncio.get_event_loop()
  5171. printer_manager.set_event_loop(loop)
  5172. printer_manager.set_status_change_callback(on_printer_status_change)
  5173. printer_manager.set_print_start_callback(on_print_start)
  5174. printer_manager.set_print_complete_callback(on_print_complete)
  5175. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  5176. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  5177. printer_manager.set_ams_change_callback(on_ams_change)
  5178. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  5179. await printer_manager.load_awaiting_plate_clear_from_db()
  5180. # Layer change callback for external camera timelapse
  5181. async def on_layer_change(printer_id: int, layer_num: int):
  5182. """Capture timelapse frame on layer change + first layer notification."""
  5183. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  5184. await tl_layer_change(printer_id, layer_num)
  5185. # First layer complete notification (layer_num >= 2 means layer 1 is done)
  5186. if 2 <= layer_num <= 5 and not _first_layer_notified.get(printer_id, False):
  5187. _first_layer_notified[printer_id] = True
  5188. try:
  5189. async with async_session() as db:
  5190. from backend.app.models.printer import Printer
  5191. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5192. printer = result.scalar_one_or_none()
  5193. if not printer:
  5194. return
  5195. printer_name = printer.name
  5196. client = printer_manager.get_client(printer_id)
  5197. state = client.state if client else None
  5198. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  5199. total_layers = state.total_layers if state else 0
  5200. image_data = await _capture_snapshot_for_notification(
  5201. printer_id, printer, logging.getLogger(__name__)
  5202. )
  5203. await notification_service.on_first_layer_complete(
  5204. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  5205. )
  5206. except Exception as e:
  5207. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  5208. printer_manager.set_layer_change_callback(on_layer_change)
  5209. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  5210. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  5211. waiter = _bed_cool_waiters.get(printer_id)
  5212. if not waiter:
  5213. return
  5214. threshold = waiter["threshold"]
  5215. if bed_temp > threshold:
  5216. return
  5217. # Bed is at or below threshold — fire notification and remove waiter
  5218. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  5219. if not waiter_info:
  5220. return # Another callback already handled it
  5221. bed_cool_logger = logging.getLogger(__name__)
  5222. bed_cool_logger.info(
  5223. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  5224. bed_temp,
  5225. printer_id,
  5226. threshold,
  5227. )
  5228. try:
  5229. printer_info = printer_manager.get_printer(printer_id)
  5230. p_name = printer_info.name if printer_info else "Unknown"
  5231. async with async_session() as db:
  5232. await notification_service.on_bed_cooled(
  5233. printer_id=printer_id,
  5234. printer_name=p_name,
  5235. bed_temp=bed_temp,
  5236. threshold=threshold,
  5237. filename=waiter_info["filename"],
  5238. db=db,
  5239. )
  5240. except Exception as e:
  5241. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  5242. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  5243. async def on_drying_complete(printer_id: int, ams_id: int):
  5244. """Smart-plug auto-off-after-drying trigger (#1349).
  5245. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  5246. manager walks all plugs linked to this printer and turns off only
  5247. the ones with ``auto_off_after_drying`` enabled, after their
  5248. per-plug delay. Multiple AMS units finishing close together (e.g. a
  5249. dual-AMS dry that ends within the same MQTT push) call this once
  5250. per unit — the manager's ``_cancel_pending_off`` collapses
  5251. repeated scheduling on the same plug to one timer, so duplicate
  5252. fires are safe.
  5253. """
  5254. try:
  5255. async with async_session() as db:
  5256. await smart_plug_manager.on_drying_complete(printer_id, db)
  5257. except Exception as e:
  5258. logging.getLogger(__name__).warning(
  5259. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  5260. printer_id,
  5261. ams_id,
  5262. e,
  5263. )
  5264. printer_manager.set_drying_complete_callback(on_drying_complete)
  5265. # Initialize MQTT relay from settings
  5266. async with async_session() as db:
  5267. from backend.app.api.routes.settings import get_setting
  5268. mqtt_settings = {
  5269. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  5270. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  5271. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  5272. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  5273. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  5274. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  5275. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  5276. }
  5277. await mqtt_relay.configure(mqtt_settings)
  5278. # Restore MQTT smart plug subscriptions
  5279. if mqtt_settings.get("mqtt_enabled"):
  5280. from backend.app.models.smart_plug import SmartPlug
  5281. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  5282. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  5283. mqtt_plugs = result.scalars().all()
  5284. restored = 0
  5285. for plug in mqtt_plugs:
  5286. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  5287. restored += 1
  5288. if restored:
  5289. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  5290. # Connect to all active printers
  5291. async with async_session() as db:
  5292. await init_printer_connections(db)
  5293. # Auto-connect to Spoolman if enabled
  5294. async with async_session() as db:
  5295. from backend.app.api.routes.settings import get_setting
  5296. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  5297. spoolman_url = await get_setting(db, "spoolman_url")
  5298. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  5299. try:
  5300. client = await init_spoolman_client(spoolman_url)
  5301. if await client.health_check():
  5302. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  5303. # Ensure the 'tag' extra field exists for RFID/UUID storage
  5304. field_ok = await client.ensure_tag_extra_field()
  5305. if not field_ok:
  5306. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  5307. # Register the BambuStudio slicer-preset fields used by the
  5308. # spool-edit / assign flow. Spoolman rejects PATCHes with
  5309. # unknown extra keys, so these must exist before any update
  5310. # that touches them.
  5311. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  5312. if not await client.ensure_extra_field(field_name):
  5313. logging.warning(
  5314. "Spoolman extra field %r registration failed — "
  5315. "spool slicer-preset edits will return 502",
  5316. field_name,
  5317. )
  5318. else:
  5319. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  5320. except Exception as e:
  5321. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  5322. # Start the print scheduler
  5323. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  5324. # Start background dispatch worker for send/start operations
  5325. await background_dispatch.start()
  5326. # Start the smart plug scheduler for time-based on/off
  5327. smart_plug_manager.start_scheduler()
  5328. # Resume any pending auto-offs that were interrupted by restart
  5329. await smart_plug_manager.resume_pending_auto_offs()
  5330. # Start the notification digest scheduler
  5331. notification_service.start_digest_scheduler()
  5332. # Start the GitHub backup scheduler
  5333. await github_backup_service.start_scheduler()
  5334. # Start the local backup scheduler
  5335. await local_backup_service.start_scheduler()
  5336. await obico_detection_service.start()
  5337. # Start the library trash sweeper (#1008)
  5338. await library_trash_service.start_scheduler()
  5339. # Start the archive auto-purge sweeper (#1008 follow-up)
  5340. await archive_purge_service.start_scheduler()
  5341. # Start AMS history recording
  5342. start_ams_history_recording()
  5343. # Start printer sensor (nozzle / bed / chamber) history recording
  5344. start_printer_sensor_history_recording()
  5345. # Start printer runtime tracking
  5346. start_runtime_tracking()
  5347. # Start SpoolBuddy device watchdog
  5348. start_spoolbuddy_watchdog()
  5349. # Start camera stream orphan cleanup
  5350. start_camera_cleanup()
  5351. # Start expected-print TTL eviction (prevents memory leak when prints are
  5352. # registered but on_print_start never fires)
  5353. start_expected_prints_cleanup()
  5354. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  5355. start_auth_cleanup()
  5356. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  5357. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  5358. from backend.app.services.loop_watchdog import start_loop_watchdog
  5359. start_loop_watchdog()
  5360. # Initialize virtual printer manager and sync from DB
  5361. from backend.app.services.virtual_printer import virtual_printer_manager
  5362. virtual_printer_manager.set_session_factory(async_session)
  5363. virtual_printer_manager.set_printer_manager(printer_manager)
  5364. try:
  5365. await virtual_printer_manager.sync_from_db()
  5366. logging.info("Virtual printer manager synced from database")
  5367. except Exception as e:
  5368. logging.warning("Failed to sync virtual printers: %s", e)
  5369. yield
  5370. # Shutdown
  5371. print_scheduler.stop()
  5372. await background_dispatch.stop()
  5373. smart_plug_manager.stop_scheduler()
  5374. notification_service.stop_digest_scheduler()
  5375. github_backup_service.stop_scheduler()
  5376. local_backup_service.stop_scheduler()
  5377. library_trash_service.stop_scheduler()
  5378. archive_purge_service.stop_scheduler()
  5379. obico_detection_service.stop()
  5380. stop_ams_history_recording()
  5381. stop_printer_sensor_history_recording()
  5382. stop_runtime_tracking()
  5383. stop_spoolbuddy_watchdog()
  5384. stop_camera_cleanup()
  5385. from backend.app.services.loop_watchdog import stop_loop_watchdog
  5386. stop_loop_watchdog()
  5387. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  5388. # cleanly rather than waiting on a queue that nothing will ever fill.
  5389. try:
  5390. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  5391. await shutdown_all_broadcasters()
  5392. except Exception as e:
  5393. logging.warning("Failed to shut down camera broadcasters: %s", e)
  5394. stop_expected_prints_cleanup()
  5395. stop_auth_cleanup()
  5396. printer_manager.disconnect_all()
  5397. await close_spoolman_client()
  5398. # Stop all virtual printer services
  5399. await virtual_printer_manager.stop_all()
  5400. await mqtt_smart_plug_service.disconnect(timeout=2)
  5401. await mqtt_relay.disconnect(timeout=2)
  5402. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  5403. set_shared_http_client(None)
  5404. set_shared_makerworld_http_client(None)
  5405. await _shared_cloud_http_client.aclose()
  5406. # Checkpoint WAL (SQLite only) and close all database connections
  5407. from backend.app.core.db_dialect import is_sqlite
  5408. if is_sqlite():
  5409. try:
  5410. async with engine.begin() as conn:
  5411. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  5412. logging.info("WAL checkpoint completed")
  5413. except Exception as e:
  5414. logging.warning("WAL checkpoint failed: %s", e)
  5415. await engine.dispose()
  5416. app = FastAPI(
  5417. title=app_settings.app_name,
  5418. description="Archive and manage Bambu Lab 3MF files",
  5419. version=APP_VERSION,
  5420. lifespan=lifespan,
  5421. )
  5422. # =============================================================================
  5423. # Authentication Middleware - Secures ALL API routes by default
  5424. # =============================================================================
  5425. # Public routes that don't require authentication even when auth is enabled
  5426. PUBLIC_API_ROUTES = {
  5427. # Auth routes needed before/during login
  5428. "/api/v1/auth/status",
  5429. "/api/v1/auth/login",
  5430. "/api/v1/auth/setup", # Needed for initial setup and recovery
  5431. # Advanced auth status needed for login page
  5432. "/api/v1/auth/advanced-auth/status",
  5433. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  5434. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  5435. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  5436. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  5437. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  5438. # OIDC routes that must be reachable without a JWT
  5439. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  5440. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  5441. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  5442. # Version check for updates (no sensitive data)
  5443. "/api/v1/updates/version",
  5444. # Metrics endpoint handles its own prometheus_token authentication
  5445. "/api/v1/metrics",
  5446. }
  5447. # Route prefixes that are public (for routes with dynamic segments)
  5448. PUBLIC_API_PREFIXES = [
  5449. # WebSocket connections handle their own auth
  5450. "/api/v1/ws",
  5451. # OIDC authorize redirects — include provider_id in path
  5452. "/api/v1/auth/oidc/authorize/",
  5453. ]
  5454. # Route patterns that are public (read-only display data)
  5455. # These are checked with "in path" - needed because browsers load images/videos
  5456. # via <img src> and <video src> which don't include Authorization headers
  5457. PUBLIC_API_PATTERNS = [
  5458. # Thumbnails
  5459. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  5460. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  5461. # Images and media
  5462. "/photos/", # /archives/{id}/photos/{filename}
  5463. "/project-image/", # /archives/{id}/project-image/{path}
  5464. "/qrcode", # /archives/{id}/qrcode
  5465. "/timelapse", # /archives/{id}/timelapse (video)
  5466. "/cover", # /printers/{id}/cover
  5467. "/icon", # /external-links/{id}/icon
  5468. # Camera (streams loaded via <img> tag)
  5469. "/camera/stream", # /printers/{id}/camera/stream
  5470. "/camera/snapshot", # /printers/{id}/camera/snapshot
  5471. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  5472. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  5473. # download token in the URL path instead.
  5474. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  5475. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  5476. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  5477. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  5478. ]
  5479. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  5480. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  5481. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  5482. Format: comma-separated list of ``scheme://host[:port]`` origins.
  5483. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  5484. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  5485. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  5486. Invalid entries are dropped with a warning rather than failing startup, so
  5487. a typo in one origin doesn't take the whole deployment down.
  5488. """
  5489. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  5490. if not raw:
  5491. return ()
  5492. valid: list[str] = []
  5493. for item in raw.split(","):
  5494. candidate = item.strip()
  5495. if not candidate:
  5496. continue
  5497. try:
  5498. parsed = urlparse(candidate)
  5499. except ValueError as e:
  5500. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  5501. continue
  5502. if parsed.scheme not in ("http", "https"):
  5503. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  5504. continue
  5505. if not parsed.netloc:
  5506. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  5507. continue
  5508. if parsed.path and parsed.path != "/":
  5509. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  5510. continue
  5511. if parsed.query or parsed.fragment:
  5512. _security_headers_logger.warning(
  5513. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  5514. )
  5515. continue
  5516. if "*" in parsed.netloc:
  5517. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  5518. continue
  5519. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  5520. if valid:
  5521. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  5522. return tuple(valid)
  5523. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  5524. def _frame_ancestors(default_value: str) -> str:
  5525. """Compose the ``frame-ancestors`` CSP directive (#1191).
  5526. ``default_value`` is the strict directive used when the operator has not
  5527. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  5528. docs) or ``'self'`` (gcode-viewer, served same-origin). When trusted origins
  5529. are configured, ``'self'`` is always included so same-origin embedding never
  5530. breaks even if an operator forgets to add their own origin to the list.
  5531. """
  5532. if _TRUSTED_FRAME_ORIGINS:
  5533. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  5534. return f"frame-ancestors {default_value};"
  5535. @app.middleware("http")
  5536. async def security_headers_middleware(request, call_next):
  5537. """Add standard HTTP security headers to every response."""
  5538. # Per-request nonce stamped into `script-src` (#1460). On its own this
  5539. # changes nothing for Bambuddy's own pages — index.html has no inline
  5540. # scripts since the SW registration moved to /sw-register.js. The reason
  5541. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  5542. # script injected into the HTML on the edge, with a fresh hash on every
  5543. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  5544. # it clones the same nonce onto its injected <script>, and the inline
  5545. # script passes the policy without us needing 'unsafe-inline'. See
  5546. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  5547. csp_nonce = secrets.token_urlsafe(16)
  5548. response = await call_next(request)
  5549. response.headers["X-Content-Type-Options"] = "nosniff"
  5550. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  5551. # browsers honour CSP frame-ancestors instead, and the legacy
  5552. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  5553. # When operators have explicitly allowlisted trusted frame origins (#1191
  5554. # — typically Home Assistant on a different port), drop X-Frame-Options
  5555. # and let the CSP-side frame-ancestors directive govern embedding.
  5556. if not _TRUSTED_FRAME_ORIGINS:
  5557. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  5558. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  5559. # Content-Security-Policy for the React SPA.
  5560. # Notes:
  5561. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  5562. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  5563. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  5564. # - media-src blob:: timelapse video player uses Blob URLs.
  5565. # - font-src data:: some icon fonts are embedded as data URIs.
  5566. if request.url.path.startswith("/gcode-viewer"):
  5567. # The gcode viewer is embedded in an iframe served by this same origin,
  5568. # so frame-ancestors must allow 'self'. prettygcode.js also uses eval()
  5569. # internally, so script-src needs 'unsafe-eval'.
  5570. response.headers["Content-Security-Policy"] = (
  5571. "default-src 'self'; "
  5572. "script-src 'self' 'unsafe-eval'; "
  5573. "style-src 'self' 'unsafe-inline'; "
  5574. "img-src 'self' data: blob:; "
  5575. "media-src 'self' blob:; "
  5576. "connect-src 'self' ws: wss:; "
  5577. "font-src 'self' data:; "
  5578. "object-src 'none'; "
  5579. "base-uri 'self'; "
  5580. "frame-src 'self' http: https:; " + _frame_ancestors("'self'")
  5581. )
  5582. elif request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  5583. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  5584. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  5585. # default CSP would render a blank page.
  5586. response.headers["Content-Security-Policy"] = (
  5587. "default-src 'self'; "
  5588. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  5589. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  5590. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  5591. "connect-src 'self'; "
  5592. "font-src 'self' data: https://fonts.gstatic.com; "
  5593. "worker-src 'self' blob:; "
  5594. "object-src 'none'; "
  5595. "base-uri 'self'; " + _frame_ancestors("'none'")
  5596. )
  5597. else:
  5598. response.headers["Content-Security-Policy"] = (
  5599. "default-src 'self'; "
  5600. f"script-src 'self' 'nonce-{csp_nonce}'; "
  5601. "style-src 'self' 'unsafe-inline'; "
  5602. "img-src 'self' data: blob:; "
  5603. "media-src 'self' blob:; "
  5604. "connect-src 'self' ws: wss:; "
  5605. "font-src 'self' data:; "
  5606. "object-src 'none'; "
  5607. "base-uri 'self'; "
  5608. "frame-src 'self' http: https:; " + _frame_ancestors("'none'")
  5609. )
  5610. if request.url.scheme == "https":
  5611. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  5612. return response
  5613. @app.middleware("http")
  5614. async def auth_middleware(request, call_next):
  5615. """Enforce authentication on all API routes when auth is enabled.
  5616. This middleware provides defense-in-depth by checking auth at the API gateway level,
  5617. regardless of whether individual routes have auth dependencies.
  5618. """
  5619. from starlette.responses import JSONResponse
  5620. path = request.url.path
  5621. # Only apply to API routes
  5622. if not path.startswith("/api/"):
  5623. return await call_next(request)
  5624. # Allow public routes
  5625. if path in PUBLIC_API_ROUTES:
  5626. return await call_next(request)
  5627. # Allow public prefixes
  5628. for prefix in PUBLIC_API_PREFIXES:
  5629. if path.startswith(prefix):
  5630. return await call_next(request)
  5631. # Allow public patterns (read-only display data like thumbnails)
  5632. for pattern in PUBLIC_API_PATTERNS:
  5633. if pattern in path:
  5634. return await call_next(request)
  5635. # Check if auth is enabled. Fail CLOSED on any exception during the
  5636. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  5637. # an attacker who could force a DB exception (e.g. file-descriptor
  5638. # exhaustion via login flood) bypass auth on every protected endpoint.
  5639. try:
  5640. async with async_session() as db:
  5641. from backend.app.core.auth import is_auth_enabled
  5642. auth_enabled = await is_auth_enabled(db)
  5643. if not auth_enabled:
  5644. # Auth disabled, allow all requests
  5645. return await call_next(request)
  5646. except Exception:
  5647. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  5648. return JSONResponse(
  5649. status_code=503,
  5650. content={"detail": "Authentication service temporarily unavailable"},
  5651. )
  5652. # Auth is enabled - require valid token
  5653. auth_header = request.headers.get("Authorization")
  5654. x_api_key = request.headers.get("X-API-Key")
  5655. # Check for API key auth first
  5656. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  5657. # API key authentication - let the request through to be validated by route handler
  5658. # API keys are validated per-route since they have different permission levels
  5659. return await call_next(request)
  5660. # Check for JWT auth
  5661. if not auth_header or not auth_header.startswith("Bearer "):
  5662. return JSONResponse(
  5663. status_code=401,
  5664. content={"detail": "Authentication required"},
  5665. headers={"WWW-Authenticate": "Bearer"},
  5666. )
  5667. # Validate JWT token
  5668. import jwt
  5669. try:
  5670. from backend.app.core.auth import (
  5671. ALGORITHM,
  5672. SECRET_KEY,
  5673. _is_token_fresh,
  5674. get_user_by_username,
  5675. is_jti_revoked,
  5676. )
  5677. token = auth_header.replace("Bearer ", "")
  5678. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  5679. username = payload.get("sub")
  5680. if not username:
  5681. raise ValueError("No username in token")
  5682. jti = payload.get("jti")
  5683. if not jti:
  5684. raise ValueError("No jti in token")
  5685. iat = payload.get("iat")
  5686. # Reject revoked tokens (defense-in-depth gateway check)
  5687. if await is_jti_revoked(jti):
  5688. return JSONResponse(
  5689. status_code=401,
  5690. content={"detail": "Token has been revoked"},
  5691. headers={"WWW-Authenticate": "Bearer"},
  5692. )
  5693. # Verify user exists, is active, and token is still fresh (L-R8-A)
  5694. async with async_session() as db:
  5695. user = await get_user_by_username(db, username)
  5696. if not user or not user.is_active:
  5697. return JSONResponse(
  5698. status_code=401,
  5699. content={"detail": "User not found or inactive"},
  5700. headers={"WWW-Authenticate": "Bearer"},
  5701. )
  5702. if not _is_token_fresh(iat, user):
  5703. return JSONResponse(
  5704. status_code=401,
  5705. content={"detail": "Token no longer valid"},
  5706. headers={"WWW-Authenticate": "Bearer"},
  5707. )
  5708. except jwt.ExpiredSignatureError:
  5709. return JSONResponse(
  5710. status_code=401,
  5711. content={"detail": "Token has expired"},
  5712. headers={"WWW-Authenticate": "Bearer"},
  5713. )
  5714. except (jwt.InvalidTokenError, ValueError, Exception):
  5715. return JSONResponse(
  5716. status_code=401,
  5717. content={"detail": "Invalid token"},
  5718. headers={"WWW-Authenticate": "Bearer"},
  5719. )
  5720. return await call_next(request)
  5721. @app.middleware("http")
  5722. async def trace_id_middleware(request, call_next):
  5723. """Stamp every HTTP request with a trace ID and echo it back.
  5724. Decorated AFTER auth_middleware on purpose: Starlette stacks
  5725. @app.middleware decorators LIFO, so the last-decorated runs first
  5726. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  5727. which means auth-middleware log lines (and every line emitted on the
  5728. way down to and back from the route handler) all carry the same
  5729. trace ID. If we put it before auth, auth's logs would be stamped
  5730. with the *previous* request's ID — useless for correlation.
  5731. Honours an inbound ``X-Trace-Id`` header so callers running their
  5732. own tracing can correlate their span IDs with our log lines, but
  5733. only if the value passes the whitelist gate in
  5734. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  5735. rejected (too long, contains control chars, etc.) silently triggers
  5736. a freshly minted server-side ID rather than failing the request.
  5737. The minted (or echoed) ID is set on a ContextVar so that every log
  5738. record emitted during the request — application logs *and* uvicorn's
  5739. access log — carries it via TraceIDFilter, and is also written to
  5740. the ``X-Trace-Id`` response header so clients can pin a server-side
  5741. log search to the exact request they made.
  5742. """
  5743. from backend.app.core.trace import (
  5744. generate_trace_id,
  5745. normalise_inbound_trace_id,
  5746. trace_id_var,
  5747. )
  5748. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  5749. trace_id = inbound if inbound is not None else generate_trace_id()
  5750. token = trace_id_var.set(trace_id)
  5751. try:
  5752. response = await call_next(request)
  5753. finally:
  5754. # Reset the ContextVar so a record emitted in a totally
  5755. # unrelated background task that just happens to inherit this
  5756. # context doesn't keep referencing this request's ID forever.
  5757. # In practice ContextVar.reset is best-effort under asyncio
  5758. # task-spawn semantics, but the cost is one attribute write so
  5759. # we may as well do it.
  5760. trace_id_var.reset(token)
  5761. response.headers["X-Trace-Id"] = trace_id
  5762. return response
  5763. # API routes
  5764. app.include_router(auth.router, prefix=app_settings.api_prefix)
  5765. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  5766. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  5767. app.include_router(users.router, prefix=app_settings.api_prefix)
  5768. app.include_router(groups.router, prefix=app_settings.api_prefix)
  5769. app.include_router(printers.router, prefix=app_settings.api_prefix)
  5770. app.include_router(archives.router, prefix=app_settings.api_prefix)
  5771. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  5772. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  5773. app.include_router(labels.router, prefix=app_settings.api_prefix)
  5774. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  5775. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  5776. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  5777. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  5778. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  5779. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  5780. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  5781. app.include_router(background_dispatch_routes.router, prefix=app_settings.api_prefix)
  5782. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  5783. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  5784. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  5785. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  5786. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  5787. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  5788. app.include_router(updates.router, prefix=app_settings.api_prefix)
  5789. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  5790. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  5791. app.include_router(camera.router, prefix=app_settings.api_prefix)
  5792. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  5793. app.include_router(projects.router, prefix=app_settings.api_prefix)
  5794. app.include_router(library.router, prefix=app_settings.api_prefix)
  5795. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  5796. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  5797. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  5798. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  5799. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  5800. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  5801. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  5802. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  5803. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  5804. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  5805. app.include_router(system.router, prefix=app_settings.api_prefix)
  5806. app.include_router(support.router, prefix=app_settings.api_prefix)
  5807. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  5808. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  5809. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  5810. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  5811. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  5812. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  5813. app.include_router(obico.router, prefix=app_settings.api_prefix)
  5814. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  5815. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  5816. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  5817. # Serve static files (React build)
  5818. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  5819. app.mount(
  5820. "/assets",
  5821. StaticFiles(directory=app_settings.static_dir / "assets"),
  5822. name="assets",
  5823. )
  5824. if (app_settings.static_dir / "img").exists():
  5825. app.mount(
  5826. "/img",
  5827. StaticFiles(directory=app_settings.static_dir / "img"),
  5828. name="img",
  5829. )
  5830. if (app_settings.static_dir / "icons").exists():
  5831. app.mount(
  5832. "/icons",
  5833. StaticFiles(directory=app_settings.static_dir / "icons"),
  5834. name="icons",
  5835. )
  5836. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  5837. # falls through to the SPA catch-all and returns index.html, which the
  5838. # browser's font sanitizer rejects ("downloadable font: rejected by
  5839. # sanitizer").
  5840. if (app_settings.static_dir / "fonts").exists():
  5841. app.mount(
  5842. "/fonts",
  5843. StaticFiles(directory=app_settings.static_dir / "fonts"),
  5844. name="fonts",
  5845. )
  5846. @app.get("/")
  5847. async def serve_frontend():
  5848. """Serve the React frontend."""
  5849. index_file = app_settings.static_dir / "index.html"
  5850. if index_file.exists():
  5851. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  5852. return {
  5853. "message": "Bambuddy API",
  5854. "docs": "/docs",
  5855. "frontend": "Build and place React app in /static directory",
  5856. }
  5857. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  5858. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  5859. # forever, but the HTML wrapping it is the only file that knows which hash
  5860. # is current. Without explicit cache-control headers Chromium decides
  5861. # heuristically (typically 10% of the time since Last-Modified) and on
  5862. # long-running kiosks happily serves stale HTML across browser restarts.
  5863. # That stale HTML references an old bundle hash, the old bundle is also
  5864. # in the disk cache, and the user ends up running pre-update JS forever
  5865. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  5866. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  5867. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  5868. @app.get("/health")
  5869. async def health_check():
  5870. """Health check endpoint."""
  5871. return {"status": "healthy"}
  5872. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  5873. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  5874. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  5875. # in deployment debugging.
  5876. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  5877. async def serve_manifest():
  5878. """Serve PWA manifest."""
  5879. manifest_file = app_settings.static_dir / "manifest.json"
  5880. if manifest_file.exists():
  5881. return FileResponse(manifest_file, media_type="application/manifest+json")
  5882. return {"error": "Manifest not found"}
  5883. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  5884. async def serve_service_worker():
  5885. """Serve service worker."""
  5886. sw_file = app_settings.static_dir / "sw.js"
  5887. if sw_file.exists():
  5888. return FileResponse(
  5889. sw_file,
  5890. media_type="application/javascript",
  5891. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  5892. )
  5893. return {"error": "Service worker not found"}
  5894. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  5895. async def serve_sw_register():
  5896. """Serve the service-worker registration bootstrap script.
  5897. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  5898. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  5899. """
  5900. reg_file = app_settings.static_dir / "sw-register.js"
  5901. if reg_file.exists():
  5902. return FileResponse(reg_file, media_type="application/javascript")
  5903. return {"error": "sw-register.js not found"}
  5904. # ── GCode viewer static files ────────────────────────────────────────────────
  5905. # Served via explicit routes so ordering is guaranteed (app.mount() loses
  5906. # to the /{full_path:path} catch-all in some Starlette versions).
  5907. _gcode_viewer_dir = (app_settings.static_dir.parent / "gcode_viewer").resolve()
  5908. # Surface packaging gaps at startup instead of as silent runtime 404s. If the
  5909. # directory is missing the explicit @app.get("/gcode-viewer/...") routes below
  5910. # return bare HTTPException(404) which renders as {"detail":"Not Found"} in
  5911. # the 3D Preview iframe (#1218) — easy to miss in normal operation, easy to
  5912. # spot if the operator scans the startup log or a support bundle.
  5913. if not (_gcode_viewer_dir / "index.html").is_file():
  5914. logging.getLogger(__name__).error(
  5915. "Embedded GCode viewer assets missing at %s — /gcode-viewer/ will return 404 "
  5916. "and 3D Preview will fail. This indicates a packaging bug; the gcode_viewer/ "
  5917. "directory must be present alongside static/.",
  5918. _gcode_viewer_dir,
  5919. )
  5920. def _gcode_viewer_response(rel: str) -> FileResponse:
  5921. from fastapi import HTTPException as _HTTPException
  5922. safe = (_gcode_viewer_dir / rel).resolve()
  5923. if not safe.is_relative_to(_gcode_viewer_dir):
  5924. raise _HTTPException(status_code=403)
  5925. if safe.is_file():
  5926. mt, _ = _mimetypes.guess_type(str(safe))
  5927. return FileResponse(str(safe), media_type=mt or "application/octet-stream")
  5928. raise _HTTPException(status_code=404)
  5929. @app.get("/gcode-viewer/")
  5930. async def serve_gcode_viewer_index() -> FileResponse:
  5931. """Raw PrettyGCode viewer for the iframe. The bare ``/gcode-viewer``
  5932. (no trailing slash) intentionally falls through to the SPA catch-all so a
  5933. full-page reload re-enters the React layout instead of serving the iframe
  5934. contents standalone."""
  5935. return _gcode_viewer_response("index.html")
  5936. @app.get("/gcode-viewer/{file_path:path}")
  5937. async def serve_gcode_viewer_file(file_path: str) -> FileResponse:
  5938. return _gcode_viewer_response(file_path)
  5939. # Catch-all route for React Router (must be last)
  5940. @app.get("/{full_path:path}")
  5941. async def serve_spa(full_path: str):
  5942. """Serve React app for client-side routing."""
  5943. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  5944. if full_path.startswith("api/"):
  5945. from fastapi import HTTPException
  5946. raise HTTPException(status_code=404, detail="Not found")
  5947. index_file = app_settings.static_dir / "index.html"
  5948. if index_file.exists():
  5949. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  5950. return {"error": "Frontend not built"}