main.py 331 KB

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