main.py 335 KB

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