main.py 340 KB

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