main.py 319 KB

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