main.py 335 KB

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