main.py 313 KB

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