main.py 305 KB

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