main.py 393 KB

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