main.py 336 KB

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