main.py 441 KB

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