main.py 474 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import secrets
  8. import time
  9. from contextlib import asynccontextmanager
  10. from datetime import datetime, timedelta, timezone
  11. from logging.handlers import RotatingFileHandler
  12. from pathlib import Path, PurePosixPath
  13. from urllib.parse import urlparse
  14. from fastapi import FastAPI
  15. from fastapi.responses import FileResponse
  16. from fastapi.staticfiles import StaticFiles
  17. from sqlalchemy import delete, or_, select, text
  18. from backend.app.api.routes import (
  19. ams_history,
  20. api_keys,
  21. archive_purge,
  22. archives,
  23. auth,
  24. bug_report,
  25. camera,
  26. camwall,
  27. cloud,
  28. discovery,
  29. external_links,
  30. filaments,
  31. finance,
  32. firmware,
  33. github_backup,
  34. groups,
  35. ha_sensors,
  36. inventory,
  37. kprofiles,
  38. labels,
  39. library,
  40. library_tags,
  41. library_trash,
  42. library_variants,
  43. local_backup,
  44. local_presets,
  45. location_ha_sensors,
  46. maintenance,
  47. makerworld,
  48. metrics,
  49. mfa,
  50. notification_templates,
  51. notifications,
  52. obico,
  53. orca_cloud,
  54. pending_uploads,
  55. pipeline_runs,
  56. print_log,
  57. print_queue,
  58. printer_sensor_history,
  59. printers,
  60. projects,
  61. scheduled_dryings,
  62. settings as settings_routes,
  63. slice_jobs,
  64. slicer_pipelines,
  65. slicer_presets,
  66. smart_plugs,
  67. sponsor_prompt,
  68. spoolbuddy,
  69. spoolman,
  70. spoolman_inventory,
  71. support,
  72. system,
  73. updates,
  74. user_notifications,
  75. users,
  76. virtual_printers,
  77. webhook,
  78. websocket,
  79. )
  80. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  81. from backend.app.api.routes.support import init_debug_logging
  82. from backend.app.core.config import APP_VERSION, settings as app_settings
  83. from backend.app.core.database import async_session, engine, init_db
  84. from backend.app.core.tasks import spawn_background_task
  85. from backend.app.core.websocket import ws_manager
  86. from backend.app.services import print_dispatch_context
  87. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  88. from backend.app.services.archive_purge import archive_purge_service
  89. from backend.app.services.bambu_ftp import (
  90. FileNotOnPrinterError,
  91. cache_3mf_download,
  92. clear_3mf_cache,
  93. download_file_async,
  94. download_file_try_paths_async,
  95. ftps_handshake_blocked,
  96. get_cached_3mf,
  97. get_ftp_retry_settings,
  98. normalize_3mf_name,
  99. with_ftp_retry,
  100. )
  101. from backend.app.services.bambu_mqtt import PrinterState
  102. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  103. from backend.app.services.github_backup import github_backup_service
  104. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  105. from backend.app.services.homeassistant import homeassistant_service
  106. from backend.app.services.library_trash import library_trash_service
  107. from backend.app.services.local_backup import local_backup_service
  108. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  109. from backend.app.services.mqtt_relay import mqtt_relay
  110. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  111. from backend.app.services.notification_service import notification_service
  112. from backend.app.services.obico_detection import obico_detection_service
  113. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  114. from backend.app.services.print_scheduler import scheduler as print_scheduler
  115. from backend.app.services.print_storage import (
  116. REASON_FTPS_COOLOFF,
  117. external_storage_present,
  118. ftp_probe_paths,
  119. print_file_reachable_over_ftp,
  120. )
  121. from backend.app.services.printer_manager import (
  122. init_printer_connections,
  123. parse_plate_id,
  124. printer_manager,
  125. printer_state_to_dict,
  126. resolve_plate_id,
  127. )
  128. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  129. from backend.app.services.slot_nozzle import (
  130. nozzle_diameter_for_extruder,
  131. nozzle_flow_for_extruder,
  132. resolve_slot_nozzle,
  133. )
  134. from backend.app.services.smart_plug_manager import smart_plug_manager
  135. from backend.app.services.spool_assignment_notifications import (
  136. notify_missing_spool_assignments_on_print_start,
  137. )
  138. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  139. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  140. from backend.app.services.spoolman_tracking import (
  141. cleanup_tracking as _cleanup_spoolman_tracking,
  142. report_usage as _report_spoolman_usage,
  143. store_print_data as _store_spoolman_print_data,
  144. )
  145. from backend.app.services.tasmota import tasmota_service
  146. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  147. from backend.app.utils.filament_types import printer_filament_type
  148. from backend.app.utils.fts_routing import extruder_for_inlet
  149. from backend.app.utils.local_time import utcnow_naive
  150. from backend.app.utils.print_jobs import is_internal_printer_job
  151. # =============================================================================
  152. # Dependency Check - runs before other imports to give helpful error messages
  153. # =============================================================================
  154. def _start_error_server(missing_packages: list):
  155. """Start a minimal HTTP server to display dependency errors in browser."""
  156. import os
  157. import signal
  158. from http.server import BaseHTTPRequestHandler, HTTPServer
  159. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  160. html = f"""<!DOCTYPE html>
  161. <html>
  162. <head>
  163. <title>Bambuddy - Setup Required</title>
  164. <style>
  165. body {{
  166. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  167. background: #0f172a; color: #e2e8f0;
  168. display: flex; justify-content: center; align-items: center;
  169. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  170. }}
  171. .container {{
  172. background: #1e293b; border-radius: 12px; padding: 40px;
  173. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  174. }}
  175. h1 {{ color: #f87171; margin-bottom: 10px; }}
  176. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  177. .packages {{
  178. background: #0f172a; border-radius: 8px; padding: 20px;
  179. margin: 20px 0; text-align: left;
  180. }}
  181. .packages ul {{ margin: 0; padding-left: 20px; }}
  182. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  183. .command {{
  184. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  185. margin: 15px 0; font-family: monospace; color: #4ade80;
  186. text-align: left; overflow-x: auto;
  187. }}
  188. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  189. </style>
  190. </head>
  191. <body>
  192. <div class="container">
  193. <h1>Setup Required</h1>
  194. <h2>Missing Python packages</h2>
  195. <div class="packages"><ul>{packages_html}</ul></div>
  196. <p>To fix, run this command on your server:</p>
  197. <div class="command">pip install -r requirements.txt</div>
  198. <p>Or if using a virtual environment:</p>
  199. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  200. <p class="note">After installing, restart Bambuddy:<br>
  201. <code>sudo systemctl restart bambuddy</code></p>
  202. </div>
  203. </body>
  204. </html>"""
  205. class ErrorHandler(BaseHTTPRequestHandler):
  206. def do_GET(self):
  207. self.send_response(503)
  208. self.send_header("Content-type", "text/html")
  209. self.end_headers()
  210. self.wfile.write(html.encode())
  211. def log_message(self, format, *args):
  212. print(f"[Error Server] {args[0]}")
  213. port = int(os.environ.get("PORT", 8000))
  214. print(f"\nStarting error server on http://0.0.0.0:{port}")
  215. print("Visit this URL in your browser to see the error details.\n")
  216. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  217. def shutdown(signum, frame):
  218. print("\nShutting down error server...")
  219. raise SystemExit(0)
  220. signal.signal(signal.SIGTERM, shutdown)
  221. signal.signal(signal.SIGINT, shutdown)
  222. server.serve_forever()
  223. def check_dependencies():
  224. """Check that all required packages are installed."""
  225. missing = []
  226. # Map of import name -> package name (for pip install)
  227. required = {
  228. "jwt": "PyJWT",
  229. "fastapi": "fastapi",
  230. "uvicorn": "uvicorn",
  231. "sqlalchemy": "sqlalchemy",
  232. "aiosqlite": "aiosqlite",
  233. "pydantic": "pydantic",
  234. "paho.mqtt": "paho-mqtt",
  235. }
  236. for module, package in required.items():
  237. try:
  238. __import__(module)
  239. except ImportError:
  240. missing.append(package)
  241. if missing:
  242. print("\n" + "=" * 60)
  243. print("ERROR: Missing required Python packages!")
  244. print("=" * 60)
  245. print(f"\nMissing packages: {', '.join(missing)}")
  246. print("\nTo fix, run:")
  247. print(" pip install -r requirements.txt")
  248. print("\nOr if using a virtual environment:")
  249. print(" ./venv/bin/pip install -r requirements.txt")
  250. print("=" * 60 + "\n")
  251. _start_error_server(missing)
  252. check_dependencies()
  253. # =============================================================================
  254. # Import settings first for logging configuration
  255. # Configure logging based on settings
  256. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  257. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  258. log_level = getattr(logging, log_level_str, logging.INFO)
  259. # Trace ID column ([-] when no request scope is active — startup, MQTT
  260. # callbacks, scheduled tasks not chained from a request — so the column
  261. # stays visually aligned and missing values are obvious in grep). See
  262. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  263. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  264. # Create root logger
  265. root_logger = logging.getLogger()
  266. root_logger.setLevel(log_level)
  267. # Trace-ID injection: this filter populates record.trace_id from the
  268. # per-request ContextVar so the format string above can reference it.
  269. # Attached to each HANDLER (not the root logger) because Python's
  270. # logging semantics only invoke a logger's filters on records that
  271. # *originated* at that logger — records propagated up from child
  272. # loggers (every named logger in the app) never trigger root's filter.
  273. # Putting it on the handlers means every record any handler emits gets
  274. # trace_id injected just before the formatter runs, regardless of which
  275. # logger created the record. Without this, the formatter raises
  276. # KeyError on every child-logger record and the record is silently
  277. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  278. # partially" bug we hit. See backend/app/core/trace.py for the
  279. # ContextVar the filter reads.
  280. from backend.app.core.trace import TraceIDFilter
  281. _trace_id_filter = TraceIDFilter()
  282. # Console handler - always enabled
  283. console_handler = logging.StreamHandler()
  284. console_handler.setLevel(log_level)
  285. console_handler.setFormatter(logging.Formatter(log_format))
  286. console_handler.addFilter(_trace_id_filter)
  287. root_logger.addHandler(console_handler)
  288. # File handler - only in production or if explicitly enabled
  289. if app_settings.log_to_file:
  290. log_file = app_settings.log_dir / "bambuddy.log"
  291. file_handler = RotatingFileHandler(
  292. log_file,
  293. maxBytes=app_settings.log_max_bytes,
  294. backupCount=app_settings.log_backup_count,
  295. encoding="utf-8",
  296. )
  297. file_handler.setLevel(log_level)
  298. file_handler.setFormatter(logging.Formatter(log_format))
  299. file_handler.addFilter(_trace_id_filter)
  300. root_logger.addHandler(file_handler)
  301. logging.info("Logging to file: %s", log_file)
  302. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  303. # access logger with propagate=False by default, so without this attach
  304. # there is no on-disk record of which endpoint triggered a server-state
  305. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  306. # for exactly this reason. Filtered to write methods only
  307. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  308. # frontend don't churn the rotation window faster than it's useful.
  309. from backend.app.core.logging_filters import (
  310. CancelledPoolNoiseFilter,
  311. WriteRequestsOnlyFilter,
  312. )
  313. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  314. uvicorn_access_logger.addHandler(file_handler)
  315. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  316. # Uvicorn's access logger has propagate=False (its own default), so the
  317. # root-attached TraceIDFilter never sees these records. Attach a
  318. # second instance directly so HTTP access lines carry the same trace
  319. # ID column as the application logs they correlate with.
  320. uvicorn_access_logger.addFilter(TraceIDFilter())
  321. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  322. # BaseHTTPMiddleware cancelling the inner task scope on client
  323. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  324. # underlying transaction leak; this filter only suppresses the residual
  325. # log records that pre-existing pools still emit during their cleanup.
  326. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  327. # Reduce noise from third-party libraries in production
  328. if not app_settings.debug:
  329. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  330. logging.getLogger("httpcore").setLevel(logging.WARNING)
  331. logging.getLogger("httpx").setLevel(logging.WARNING)
  332. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  333. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  334. # Track active prints: {(printer_id, filename): archive_id}
  335. _active_prints: dict[tuple[int, str], int] = {}
  336. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  337. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  338. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  339. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  340. # instead of running its own grab-now chain when present, so the finish photo
  341. # captures the better-framed pre-bed-drop moment without us having to force
  342. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  343. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  344. #
  345. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  346. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  347. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  348. # bank and the others are not — so the consumer can't tell them apart and
  349. # must not rotate again.
  350. _stage22_finish_frames: dict[int, bytes] = {}
  351. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  352. # `finally` block (whether it captured a frame or not). The consumer in
  353. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  354. # so the FINISH-state fallback path — where moment and completion are dispatched
  355. # back-to-back — doesn't race past the producer with an empty pop, and the
  356. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  357. # grab (Bambu printers allow only one RTSP client at a time).
  358. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  359. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  360. # layer-change and on print-progress advances (#2547) while the model is still
  361. # printing, then consumed by the FINISH-state finish-photo path when the
  362. # dispatcher recorded that it injected End G-code into this print. Bambu
  363. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  364. # plate-swap) has run, so a live grab there would capture the swapped/empty
  365. # plate.
  366. #
  367. # The load-bearing property: both drivers are print telemetry that stops before
  368. # the End G-code executes — no further layer_num increases, and mc_percent
  369. # freezes — so the last banked frame is always the finished print before the
  370. # swap. Anything added as a third driver must hold that same property.
  371. _inprint_frame_bank: dict[int, bytes] = {}
  372. # Monotonic timestamp of the last banked frame per printer — throttles banking
  373. # so tall prints don't add a camera grab on every layer.
  374. _inprint_frame_bank_ts: dict[int, float] = {}
  375. # Minimum seconds between banked frames, except the final object layer which
  376. # always refreshes for the best framing.
  377. _INPRINT_BANK_MIN_INTERVAL = 25.0
  378. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  379. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  380. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  381. # the first connected status update for that connection; transitions back
  382. # to False whenever we observe `state.connected = False` so the next
  383. # reconnect re-arms reconciliation. Keyed by printer_id.
  384. _printer_reconciled_since_connect: dict[int, bool] = {}
  385. # Same edge, same keying, for priming the printer's calibration table exactly
  386. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  387. # is otherwise filled only when someone opens the Profiles page or Configure
  388. # Slot, when a GitHub backup runs, or when the printer happens to answer
  389. # somebody else's query on the report topic. Until then the AMS slot card has
  390. # no K value to show on the printers whose trays carry none of their own
  391. # (#2854 — H2-series report cali_idx and nothing more).
  392. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  393. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  394. # {(printer_id, filename): archive_id}
  395. _expected_prints: dict[tuple[int, str], int] = {}
  396. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  397. # Used by usage tracker to map 3MF slots to physical AMS trays
  398. _print_ams_mappings: dict[int, list[int]] = {}
  399. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  400. _print_cost_center_ids: dict[int, int] = {}
  401. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  402. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  403. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  404. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  405. # for the queue path. Cleared on print completion or TTL eviction.
  406. _print_plate_ids: dict[int, int] = {}
  407. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  408. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  409. _last_progress_milestone: dict[int, int] = {}
  410. # Track whether first layer complete notification has been sent for current print
  411. _first_layer_notified: dict[int, bool] = {}
  412. # Track whether we already sent a kill-switch stop for the current unauthorized print
  413. _unauthorized_print_kill_sent: set[int] = set()
  414. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  415. # lookup briefly so an unknown active print does not query the database on
  416. # every status frame. A short TTL keeps settings changes responsive.
  417. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  418. _kill_switch_setting_cache: tuple[bool, float] | None = None
  419. # Provider notification started when the kill switch stops a print. The later
  420. # MQTT print-complete callback awaits this task and only sends its regular
  421. # provider notification when the immediate attempt failed.
  422. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  423. # Track HMS errors that have been notified: {printer_id: set of error codes}
  424. # This prevents sending duplicate notifications for the same error
  425. _notified_hms_errors: dict[int, set[str]] = {}
  426. # Track when HMS errors were last seen: {printer_id: timestamp}
  427. # Used to debounce clearing — prevents flapping errors from re-triggering notifications
  428. _hms_last_seen: dict[int, float] = {}
  429. _HMS_CLEAR_GRACE_SECONDS = 30.0
  430. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  431. # Used for snapshot-diff detection at print completion
  432. _timelapse_baselines: dict[int, set[str]] = {}
  433. # Track printers waiting for bed to cool after print completion.
  434. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  435. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  436. _bed_cool_waiters: dict[int, dict] = {}
  437. # Track printers where the user explicitly stopped the print from the queue UI.
  438. # When on_print_complete fires with status "failed" for these printers we treat it
  439. # as "cancelled" (stopped by user) so the correct notification email is sent.
  440. _user_stopped_printers: set[int] = set()
  441. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  442. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  443. # holds the previous observation so we only fire on the True → False edge (a
  444. # False → False repeat doesn't notify; an initial False at startup doesn't
  445. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  446. # holds the per-printer pending asyncio task that fires the notification
  447. # after a debounce window — cancelled if the printer reconnects before the
  448. # window elapses, so transient MQTT blips don't flood the user.
  449. _printer_last_connected: dict[int, bool] = {}
  450. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  451. # Debounce: a printer must stay offline this long before we notify. Sized
  452. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  453. # so a single stale-trigger cooldown isn't enough to fire — only a real
  454. # offline that survives one reconnect attempt notifies.
  455. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  456. # HMS short-code → human-readable failure reason. Used by _dispatch_archive_update
  457. # when status="failed" to label the print's failure_reason in archives.
  458. #
  459. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  460. # which is wrong on two counts:
  461. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  462. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  463. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  464. # the public wiki) as part of its user-cancel sequence. Matching on the module
  465. # alone caused user-cancellations to be archived as "Layer shift" failures.
  466. # We now match by full short code only — anything not in this map leaves
  467. # failure_reason=None rather than guessing.
  468. # Values are the canonical camelCase failure-reason keys, NOT display labels
  469. # (issue #2974). The vocabulary is enforced on writes by
  470. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  471. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  472. # Statistics breakdown. Storing a label here instead put a second spelling of
  473. # the same cause into one column: the Failure Analysis widget groups on the raw
  474. # value, so a print the backend classified and an identical one a user
  475. # classified counted as two different reasons, and the label form could never
  476. # be translated because there was no key for ``t()`` to resolve.
  477. _HMS_FAILURE_REASONS: dict[str, str] = {
  478. # Layer shift / step loss
  479. "0300_4057": "layerShift",
  480. "0300_4068": "layerShift",
  481. "0300_800C": "layerShift",
  482. # Filament runout (printer-side & per-AMS-slot)
  483. "0300_8004": "filamentRunout",
  484. "0700_8011": "filamentRunout",
  485. "0701_8011": "filamentRunout",
  486. "0702_8011": "filamentRunout",
  487. "0703_8011": "filamentRunout",
  488. "0704_8011": "filamentRunout",
  489. "0705_8011": "filamentRunout",
  490. "0706_8011": "filamentRunout",
  491. "0707_8011": "filamentRunout",
  492. "07FF_8011": "filamentRunout",
  493. # Clogged nozzle / extruder
  494. "0300_4006": "cloggedNozzle",
  495. "0300_8016": "cloggedNozzle",
  496. "0300_801C": "cloggedNozzle",
  497. "0700_8003": "cloggedNozzle",
  498. "0700_8007": "cloggedNozzle",
  499. "0700_8013": "cloggedNozzle",
  500. "0701_8003": "cloggedNozzle",
  501. "0701_8007": "cloggedNozzle",
  502. "0701_8013": "cloggedNozzle",
  503. "0702_8003": "cloggedNozzle",
  504. }
  505. def _hms_short_code(attr: int, code: int | str) -> str:
  506. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  507. if isinstance(code, str):
  508. code_int = int(code.replace("0x", ""), 16) if code else 0
  509. else:
  510. code_int = int(code or 0)
  511. attr_int = int(attr or 0)
  512. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  513. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  514. """Derive a human-readable failure_reason for an archived print.
  515. Returns "User cancelled" for cancelled/aborted prints; for failed prints,
  516. returns the first matching reason from _HMS_FAILURE_REASONS, or None when
  517. no HMS code matches (don't guess — null is honest).
  518. """
  519. if status in ("aborted", "cancelled"):
  520. return "userCancelled"
  521. if status != "failed":
  522. return None
  523. for err in hms_errors or []:
  524. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  525. if short_code in _HMS_FAILURE_REASONS:
  526. return _HMS_FAILURE_REASONS[short_code]
  527. return None
  528. # Track created_by_id for expected prints so the user email can be sent even when
  529. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  530. # {(printer_id, filename): created_by_id}
  531. _expected_print_creators: dict[tuple[int, str], int] = {}
  532. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  533. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  534. # updates for the same printer in quick succession (~30 ms apart, observed in
  535. # the wild on H2D + dual AMS).
  536. #
  537. # Without this serialisation, two concurrent on_ams_change callbacks each read
  538. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  539. # the second commit hits
  540. # IntegrityError: duplicate key value violates unique constraint
  541. # "spool_assignment_printer_id_ams_id_tray_id_key"
  542. # SQLite's WAL serial-write semantics had been silently swallowing the race
  543. # until optional Postgres support landed (asyncpg allows true concurrent
  544. # transactions and surfaces the constraint violation).
  545. #
  546. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  547. # assign) are inside the lock. The Spoolman sync block further down stays
  548. # concurrent because it's network-bound and idempotent.
  549. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  550. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  551. """Return the per-printer assignment lock, creating it on first use."""
  552. lock = _ams_assignment_locks.get(printer_id)
  553. if lock is None:
  554. lock = asyncio.Lock()
  555. _ams_assignment_locks[printer_id] = lock
  556. return lock
  557. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  558. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  559. # tag tuple changes for the slot. Cleared when the slot is reported empty
  560. # so remove + reinsert reliably re-prompts the UI.
  561. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  562. async def _broadcast_unknown_tag(
  563. *,
  564. printer_id: int,
  565. ams_id: int,
  566. tray_id: int,
  567. tag_uid: str,
  568. tray_uuid: str,
  569. tray_type: str | None = None,
  570. tray_color: str | None = None,
  571. tray_sub_brands: str | None = None,
  572. tray_count: int | None = None,
  573. ) -> None:
  574. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  575. _logger = logging.getLogger(__name__)
  576. slot_key = (ams_id, tray_id)
  577. tag_key = (tag_uid or "", tray_uuid or "")
  578. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  579. if per_printer.get(slot_key) == tag_key:
  580. _logger.debug(
  581. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  582. printer_id,
  583. ams_id,
  584. tray_id,
  585. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  586. )
  587. return
  588. _logger.info(
  589. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  590. printer_id,
  591. ams_id,
  592. tray_id,
  593. tray_type,
  594. tray_color,
  595. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  596. )
  597. # Broadcast first; only commit the dedup if the WS write succeeds.
  598. # If broadcast raises, the next MQTT push retries instead of being
  599. # permanently silenced by a poisoned dedup entry.
  600. await ws_manager.broadcast(
  601. {
  602. "type": "unknown_tag",
  603. "printer_id": printer_id,
  604. "ams_id": ams_id,
  605. "tray_id": tray_id,
  606. "tag_uid": tag_uid,
  607. "tray_uuid": tray_uuid,
  608. "tray_type": tray_type,
  609. "tray_color": tray_color,
  610. "tray_sub_brands": tray_sub_brands,
  611. "tray_count": tray_count,
  612. }
  613. )
  614. per_printer[slot_key] = tag_key
  615. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  616. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  617. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  618. if per_printer is None:
  619. return
  620. per_printer.pop((ams_id, tray_id), None)
  621. # TTL for expected-print entries: evict registrations older than this to prevent
  622. # unbounded growth when a print is registered but never starts (e.g. printer
  623. # disconnect, app restart, print started from the printer panel).
  624. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  625. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  626. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  627. # Cleanup loop interval
  628. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  629. _expected_prints_cleanup_task: asyncio.Task | None = None
  630. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  631. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  632. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  633. possible_keys: list[tuple[int, str]] = []
  634. filename = (state.gcode_file or state.current_print or "").strip()
  635. subtask_name = (state.subtask_name or "").strip()
  636. if subtask_name:
  637. possible_keys.append((printer_id, subtask_name))
  638. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  639. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  640. if filename:
  641. base_name = filename.rsplit("/", 1)[-1]
  642. if base_name.endswith(".gcode.3mf"):
  643. root_name = base_name[: -len(".gcode.3mf")]
  644. possible_keys.append((printer_id, root_name))
  645. possible_keys.append((printer_id, base_name))
  646. possible_keys.append((printer_id, f"{root_name}.gcode"))
  647. possible_keys.append((printer_id, f"{root_name}.3mf"))
  648. elif base_name.endswith(".3mf"):
  649. root_name = base_name[: -len(".3mf")]
  650. possible_keys.append((printer_id, root_name))
  651. possible_keys.append((printer_id, base_name))
  652. elif base_name.endswith(".gcode"):
  653. root_name = base_name[: -len(".gcode")]
  654. possible_keys.append((printer_id, root_name))
  655. possible_keys.append((printer_id, f"{root_name}.3mf"))
  656. possible_keys.append((printer_id, base_name))
  657. else:
  658. possible_keys.append((printer_id, base_name))
  659. possible_keys.append((printer_id, f"{base_name}.3mf"))
  660. return possible_keys
  661. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  662. """Check the cheap, process-local print ownership signals."""
  663. if printer_manager.get_current_print_user(printer_id):
  664. return True
  665. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  666. async def _is_printer_kill_switch_enabled_cached() -> bool:
  667. """Return the kill-switch setting without querying on every MQTT frame."""
  668. global _kill_switch_setting_cache
  669. now = time.monotonic()
  670. if _kill_switch_setting_cache is not None:
  671. enabled, expires_at = _kill_switch_setting_cache
  672. if now < expires_at:
  673. return enabled
  674. async with async_session() as db:
  675. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  676. enabled = await is_printer_kill_switch_enabled(db)
  677. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  678. return enabled
  679. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  680. """Resolve whether the current print was started by Bambuddy.
  681. ``None`` means identity is not yet safe to decide. The kill switch must
  682. defer in that case: stopping a print is irreversible, and the first status
  683. frames after a restart may arrive before all subtask fields are populated.
  684. """
  685. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  686. return True
  687. possible_keys = _build_status_print_keys(printer_id, state)
  688. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  689. # is on disk. subtask_id is minted per print and pins the answer to the job
  690. # actually running, rather than to an unrelated one that reuses a filename.
  691. raw_subtask_id = getattr(state, "subtask_id", None)
  692. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  693. if subtask_id in ("", "0"):
  694. return None
  695. from backend.app.models.archive import PrintArchive
  696. result = await db.execute(
  697. select(PrintArchive)
  698. .where(
  699. PrintArchive.printer_id == printer_id,
  700. PrintArchive.status == "printing",
  701. PrintArchive.subtask_id == subtask_id,
  702. )
  703. .order_by(PrintArchive.created_at.desc())
  704. .limit(1)
  705. )
  706. archive = result.scalar_one_or_none()
  707. # An archive row on its own proves nothing: `on_print_start` archives every
  708. # print it observes, including ones started from Bambu Studio or Handy, and
  709. # stamps them with the same status and subtask_id. Authorizing on its mere
  710. # existence would disable the kill switch the moment the 3MF finishes
  711. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  712. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  713. # (carried over from the queue item that started it).
  714. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  715. # Rehydrate the fast in-memory path for subsequent status frames. Include
  716. # both the archive filename and every normalized key reported by MQTT.
  717. _active_prints[(printer_id, archive.filename)] = archive.id
  718. for key in possible_keys:
  719. _active_prints[key] = archive.id
  720. return True
  721. # No dispatch marker. Before calling this someone else's print, check whether
  722. # Bambuddy has a job of its own running on this printer: a library-file
  723. # dispatch has no archive at send time, and an archive created seconds later
  724. # by `on_print_start` carries neither marker. The queue row, which the
  725. # scheduler commits to status="printing" before the MQTT send, is the one
  726. # durable record every Bambuddy print has. It cannot be tied to this
  727. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  728. # print is irreversible, and refusing to act costs nothing but a log line.
  729. from backend.app.models.print_queue import PrintQueueItem
  730. dispatched_here = await db.scalar(
  731. select(PrintQueueItem.id)
  732. .where(
  733. PrintQueueItem.printer_id == printer_id,
  734. PrintQueueItem.status == "printing",
  735. )
  736. .limit(1)
  737. )
  738. if dispatched_here is not None:
  739. return None
  740. return False
  741. async def _send_kill_switch_provider_notification(
  742. printer_id: int,
  743. printer_name: str,
  744. data: dict,
  745. ) -> bool:
  746. """Send the immediate print-stopped provider notification.
  747. Returning a success flag lets the normal MQTT completion path retry when
  748. this early notification could not be delivered.
  749. """
  750. logger = logging.getLogger(__name__)
  751. try:
  752. async with async_session() as db:
  753. await notification_service.on_print_complete(
  754. printer_id,
  755. printer_name,
  756. "stopped",
  757. data,
  758. db,
  759. )
  760. return True
  761. except Exception as e:
  762. logger.warning(
  763. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  764. printer_id,
  765. e,
  766. )
  767. return False
  768. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  769. """Wait for an immediate kill-switch notification, if one was scheduled."""
  770. if task is None:
  771. return False
  772. try:
  773. return await task
  774. except Exception as e:
  775. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  776. return False
  777. async def _get_plug_energy(plug, db) -> dict | None:
  778. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  779. For HA plugs, configures the service with current settings from DB.
  780. For MQTT plugs, returns data from the subscription service.
  781. For REST plugs, polls the status URL with JSON path extraction.
  782. """
  783. if plug.plug_type == "homeassistant":
  784. from backend.app.api.routes.settings import get_homeassistant_settings
  785. ha_settings = await get_homeassistant_settings(db)
  786. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  787. return await homeassistant_service.get_energy(plug)
  788. elif plug.plug_type == "mqtt":
  789. # MQTT plugs report "today" energy, not lifetime total
  790. # For per-print tracking, we use "today" as the counter (resets at midnight)
  791. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  792. if mqtt_data:
  793. return {
  794. "power": mqtt_data.power,
  795. "today": mqtt_data.energy,
  796. "total": mqtt_data.energy, # Use today as total for per-print calculations
  797. }
  798. return None
  799. elif plug.plug_type == "rest":
  800. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  801. return await rest_smart_plug_service.get_energy(plug)
  802. else:
  803. return await tasmota_service.get_energy(plug)
  804. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  805. """Capture the smart plug lifetime counter on the archive at print start.
  806. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  807. tracking survives a backend restart mid-print. The print-end handler reads
  808. this value back from the DB and computes the delta against the current
  809. plug counter.
  810. """
  811. _logger = logging.getLogger(__name__)
  812. try:
  813. candidates = await energy_plug_candidates(db, printer_id)
  814. if not candidates:
  815. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  816. return False
  817. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  818. if selected is None:
  819. # Naming the plugs matters here: with several linked to one printer
  820. # this is the difference between "the meter is offline" and "you
  821. # linked only accessories" (#2859).
  822. _logger.warning(
  823. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  824. printer_id,
  825. archive.id,
  826. ", ".join(plug.name for plug in candidates),
  827. )
  828. return False
  829. plug, energy = selected
  830. archive.energy_start_kwh = float(energy["total"])
  831. await db.commit()
  832. _logger.info(
  833. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  834. f" ({context})" if context else "",
  835. archive.id,
  836. plug.name,
  837. energy["total"],
  838. )
  839. return True
  840. except Exception as e:
  841. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  842. return False
  843. def register_expected_print(
  844. printer_id: int,
  845. filename: str,
  846. archive_id: int,
  847. ams_mapping: list[int] | None = None,
  848. created_by_id: int | None = None,
  849. cost_center_id: int | None = None,
  850. plate_id: int | None = None,
  851. ):
  852. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  853. # Store with multiple filename variations to catch different naming patterns
  854. _expected_prints[(printer_id, filename)] = archive_id
  855. # Also store without .3mf extension if present
  856. if filename.endswith(".3mf"):
  857. base = filename[:-4]
  858. _expected_prints[(printer_id, base)] = archive_id
  859. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  860. # Store AMS mapping for usage tracking at print completion
  861. if ams_mapping is not None:
  862. _print_ams_mappings[archive_id] = ams_mapping
  863. if cost_center_id is not None:
  864. _print_cost_center_ids[archive_id] = cost_center_id
  865. # Store plate_id for usage tracking when this is a single-plate dispatch from
  866. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  867. # file's filament total to the spool instead of just the printed plate (#1697).
  868. if plate_id is not None:
  869. _print_plate_ids[archive_id] = plate_id
  870. # Store created_by_id so the user start email can be sent even when the archive
  871. # itself has no created_by_id (e.g. library-file-based queue prints)
  872. if created_by_id is not None:
  873. _expected_print_creators[(printer_id, filename)] = created_by_id
  874. if filename.endswith(".3mf"):
  875. base = filename[:-4]
  876. _expected_print_creators[(printer_id, base)] = created_by_id
  877. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  878. # Record registration time for TTL-based eviction
  879. _registered_at = time.monotonic()
  880. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  881. if filename.endswith(".3mf"):
  882. base = filename[:-4]
  883. _expected_print_registered_at[(printer_id, base)] = _registered_at
  884. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  885. logging.getLogger(__name__).info(
  886. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  887. )
  888. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  889. """Undo :func:`register_expected_print` when the print never went out.
  890. Registration has to happen *before* the MQTT print command, because the
  891. printer can report the print before the line after the send executes. So
  892. every path that registers and then fails to send — a cancel winning the
  893. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  894. between — leaves an expectation for a print that will never arrive.
  895. The TTL sweep evicts those after two hours, which is far longer than it
  896. takes a user to react to a failed dispatch by pressing print again: that
  897. reprint would be folded into the *old* archive and take the stale
  898. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  899. Mirrors the sweep's rules, including the one that is easy to get wrong:
  900. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  901. file, so they may only be dropped once no live key still points at that
  902. archive.
  903. """
  904. keys = [(printer_id, filename)]
  905. if filename.endswith(".3mf"):
  906. base = filename[:-4]
  907. keys.append((printer_id, base))
  908. keys.append((printer_id, f"{base}.gcode"))
  909. removed = False
  910. for key in keys:
  911. if _expected_prints.pop(key, None) is not None:
  912. removed = True
  913. _expected_print_creators.pop(key, None)
  914. _expected_print_registered_at.pop(key, None)
  915. if archive_id not in set(_expected_prints.values()):
  916. _print_ams_mappings.pop(archive_id, None)
  917. _print_plate_ids.pop(archive_id, None)
  918. if removed:
  919. logging.getLogger(__name__).info(
  920. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  921. printer_id,
  922. filename,
  923. archive_id,
  924. )
  925. def _compute_run_filament_grams(
  926. status: str,
  927. archive_filament_used_grams: float | None,
  928. progress: float | int | None,
  929. usage_results: list[dict] | None,
  930. ) -> float | None:
  931. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  932. Priority for every status:
  933. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  934. weight delta — same source that drives "Total Consumed" on the
  935. Inventory page, so Stats and Inventory totals stay aligned).
  936. 2. For ``completed``: the slicer estimate (no tracker available, fall
  937. back to the canonical "this print used X" value).
  938. 3. For partial statuses: ``estimate * progress%``.
  939. 4. ``None`` if nothing is known.
  940. """
  941. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  942. if tracked_grams > 0:
  943. return round(tracked_grams, 1)
  944. if status == "completed":
  945. return archive_filament_used_grams
  946. if archive_filament_used_grams:
  947. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  948. if scale > 0:
  949. return round(archive_filament_used_grams * scale, 1)
  950. return None
  951. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  952. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  953. stored_ams_mapping = data.get("ams_mapping")
  954. if not stored_ams_mapping and archive_id:
  955. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  956. return stored_ams_mapping
  957. def _get_start_plate_id(archive_id: int | None) -> int | None:
  958. """Resolve plate_id for print start without consuming stored direct-Print state.
  959. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  960. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  961. read it back at print-start without popping (the entry is popped on print
  962. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  963. """
  964. if archive_id is None:
  965. return None
  966. return _print_plate_ids.get(archive_id)
  967. def _partial_progress_scale(progress: int | float | None) -> float:
  968. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  969. Used by every site that multiplies a "would-have-used" slicer estimate
  970. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  971. so the three sites in ``_background_notifications`` (and the per-plate
  972. override helper) can't drift apart on the coercion shape.
  973. """
  974. return max(0.0, min((progress or 0) / 100.0, 1.0))
  975. def _scope_notification_archive_data_to_plate(
  976. archive_data: dict,
  977. archive_file_path: str | None,
  978. plate_id: int | None,
  979. print_status: str,
  980. progress: int | float | None,
  981. base_dir: Path,
  982. ) -> dict:
  983. """Override summed-across-plates totals in ``archive_data`` with the values
  984. for ``plate_id`` so the completion notification reports what was actually
  985. printed, not the whole project (#1785).
  986. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  987. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  988. the archive card's "whole project" headline, wrong for the completion
  989. notification of a single-plate print. The queue UI already re-reads the
  990. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  991. notification payload (filament grams, time estimate, per-slot breakdown).
  992. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  993. no per-plate values — in every fail case the original ``archive_data`` is
  994. returned unchanged so the notification still sends.
  995. """
  996. if plate_id is None or not archive_file_path:
  997. return archive_data
  998. from backend.app.utils.threemf_tools import (
  999. extract_filament_usage_from_3mf,
  1000. extract_print_time_from_3mf,
  1001. )
  1002. archive_path = base_dir / archive_file_path
  1003. if not archive_path.exists():
  1004. return archive_data
  1005. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1006. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1007. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1008. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1009. if plate_time:
  1010. archive_data["print_time_seconds"] = plate_time
  1011. # Gate both the grams headline AND the per-slot breakdown on the same
  1012. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1013. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1014. # to the project-level grams the archive columns already provide rather
  1015. # than ship a project-level headline next to an all-zero per-plate
  1016. # breakdown.
  1017. if plate_grams > 0:
  1018. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1019. archive_data["filament_slots"] = [
  1020. {
  1021. "slot_id": s.get("slot_id"),
  1022. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1023. "type": s.get("type", ""),
  1024. "color": s.get("color", ""),
  1025. }
  1026. for s in plate_slots
  1027. ]
  1028. return archive_data
  1029. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1030. """Best-effort filament metadata from the MQTT print-start snapshot.
  1031. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1032. file during print, see #1533) so the fallback PrintArchive still has
  1033. enough filament info to support the inventory views and AMS-expansion
  1034. planning the operator opens it for. Returns a dict with optional
  1035. ``filament_type`` and ``filament_color`` keys in the same
  1036. comma-separated format the 3MF extractor produces, so the rest of the
  1037. codebase treats the fallback archive identically to a normal one.
  1038. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1039. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1040. entries). When supplied, only the slots actually consumed by this
  1041. print contribute. Without it the function falls back to every loaded
  1042. AMS slot — less accurate but still useful.
  1043. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1044. that the unit tests pass directly, AND the on_print_start callback
  1045. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1046. bambu_mqtt service hands to main.py at runtime. The original
  1047. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1048. handled the inner shape and silently returned ``{}`` for every real
  1049. print start, leaving fallback archives' filament fields NULL — the
  1050. exact regression the fix was meant to close. Reported with a log
  1051. proving the AMS state was right there at
  1052. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1053. """
  1054. result: dict[str, str] = {}
  1055. # Look at the on_print_start wrapper first, then the inner shape.
  1056. raw_data = (data or {}).get("raw_data")
  1057. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1058. if not isinstance(ams_root, dict):
  1059. ams_root = (data or {}).get("ams") or {}
  1060. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1061. if not isinstance(ams_units, list) or not ams_units:
  1062. return result
  1063. # Map global tray id (unit * 4 + tray) → (type, color).
  1064. loaded: dict[int, tuple[str, str]] = {}
  1065. for unit in ams_units:
  1066. if not isinstance(unit, dict):
  1067. continue
  1068. try:
  1069. unit_id = int(unit.get("id", 0))
  1070. except (TypeError, ValueError):
  1071. continue
  1072. for tray in unit.get("tray") or []:
  1073. if not isinstance(tray, dict):
  1074. continue
  1075. try:
  1076. tray_id = int(tray.get("id", 0))
  1077. except (TypeError, ValueError):
  1078. continue
  1079. ttype = (tray.get("tray_type") or "").strip()
  1080. tcolor = (tray.get("tray_color") or "").strip().upper()
  1081. if not ttype:
  1082. continue # Empty / unloaded slot.
  1083. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1084. if not loaded:
  1085. return result
  1086. if ams_mapping:
  1087. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1088. filaments = [loaded[g] for g in used_ids if g in loaded]
  1089. if not filaments:
  1090. return result # Mapping points entirely at slots we have no data for.
  1091. else:
  1092. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1093. types_joined = ",".join(f[0] for f in filaments)
  1094. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1095. # Column limits per backend/app/models/archive.py: filament_type=50,
  1096. # filament_color=200.
  1097. if types_joined:
  1098. result["filament_type"] = types_joined[:50]
  1099. if colors_joined:
  1100. result["filament_color"] = colors_joined[:200]
  1101. return result
  1102. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1103. """Start a layer-timelapse session for *archive_id* when the printer has
  1104. an external camera configured. Returns True if a session was started.
  1105. Three call sites in on_print_start (expected-archive promotion, fallback
  1106. archive creation, fresh-archive creation) used to inline this same
  1107. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1108. on the first pass). Centralising the conditional + call here makes the
  1109. contract testable in isolation and keeps the three sites locked in step.
  1110. """
  1111. if not (printer.external_camera_enabled and printer.external_camera_url):
  1112. return False
  1113. from backend.app.services.layer_timelapse import start_session
  1114. start_session(
  1115. printer_id,
  1116. archive_id,
  1117. printer.external_camera_url,
  1118. printer.external_camera_type or "mjpeg",
  1119. snapshot_url=printer.external_camera_snapshot_url,
  1120. rotation=getattr(printer, "camera_rotation", 0),
  1121. )
  1122. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1123. return True
  1124. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1125. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1126. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1127. — since #2926 — the description the parser already resolved, which is preferred
  1128. when present so the queue's failure reason reads the same as the status
  1129. response. The short code still produces the bracketed label, and still
  1130. resolves the sentence for a caller whose entries predate the field. Falls back
  1131. to the bare short code when no description is on file. Returns None for an
  1132. empty list so callers can leave error_message unset.
  1133. """
  1134. if not hms_errors:
  1135. return None
  1136. from backend.app.services.hms_errors import get_error_description
  1137. parts: list[str] = []
  1138. for err in hms_errors:
  1139. try:
  1140. # `_hms_short_code` rather than a local derivation: this one used to
  1141. # format the error without masking it to 16 bits, so an `hms[]` entry
  1142. # whose code carries an alert-level group produced a five-digit label
  1143. # like "0500_3000A" — not a code the user can look up, and never a
  1144. # catalogue key, so the sentence was lost with it.
  1145. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1146. except (TypeError, ValueError):
  1147. continue
  1148. description = err.get("description") or get_error_description(short_code)
  1149. parts.append(f"[{short_code}] {description}" if description else f"[{short_code}]")
  1150. return "; ".join(parts) if parts else None
  1151. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1152. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1153. print completes successfully. Gated to status=='completed': failed, cancelled
  1154. and aborted prints do not count as usage. Caller is responsible for committing
  1155. the session. No-op when the queue item has no linked library file (e.g. reprints
  1156. from an archive). See #1008."""
  1157. if queue_status != "completed" or item.library_file_id is None:
  1158. return
  1159. from backend.app.models.library import LibraryFile
  1160. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1161. if lib_file is None:
  1162. return
  1163. lib_file.print_count = (lib_file.print_count or 0) + 1
  1164. lib_file.last_printed_at = datetime.now(timezone.utc)
  1165. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1166. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1167. When on_print_complete fires with status 'failed' for a printer in this set we
  1168. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1169. rather than a 'print failed' notification.
  1170. """
  1171. _user_stopped_printers.add(printer_id)
  1172. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1173. _last_status_broadcast: dict[int, str] = {}
  1174. # Track printers where we've updated nozzle_count
  1175. _nozzle_count_updated: set[int] = set()
  1176. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1177. """Wait the debounce window then fire `on_printer_offline` if the printer
  1178. is still offline.
  1179. Scheduled by `on_printer_status_change` on the connected → disconnected
  1180. edge (#1752). Cancelled by the same handler if the printer reconnects
  1181. before the window elapses, so a single MQTT blip + recovery doesn't
  1182. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1183. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1184. route through the same status-change callback, so this covers both.
  1185. """
  1186. logger = logging.getLogger(__name__)
  1187. try:
  1188. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1189. still_offline = not printer_manager.is_connected(printer_id)
  1190. logger.info(
  1191. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1192. printer_id,
  1193. still_offline,
  1194. )
  1195. if not still_offline:
  1196. return
  1197. async with async_session() as db:
  1198. from backend.app.models.printer import Printer
  1199. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1200. printer = result.scalar_one_or_none()
  1201. if not printer:
  1202. logger.warning(
  1203. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1204. printer_id,
  1205. )
  1206. return
  1207. logger.info(
  1208. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1209. printer_id,
  1210. printer.name,
  1211. )
  1212. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1213. except asyncio.CancelledError:
  1214. raise
  1215. except Exception as e:
  1216. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1217. finally:
  1218. _printer_offline_notify_tasks.pop(printer_id, None)
  1219. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1220. """Handle printer status changes - broadcast via WebSocket."""
  1221. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1222. # transitions disconnected → connected — which covers both Bambuddy
  1223. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1224. # `reconcile_stale_active_prints` exactly once for this connection so
  1225. # any archive still in `status="printing"` that can't actually be
  1226. # running anymore (printer IDLE / different subtask / empty subtask)
  1227. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1228. # finished during a disconnect window + a smart-plug power cycle
  1229. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1230. # next boot. Reconciliation runs concurrently — it must not block the
  1231. # WebSocket dedup / broadcast logic below, and the connected edge is
  1232. # marked True BEFORE the await so concurrent status updates inside
  1233. # the same connection don't re-trigger reconciliation.
  1234. #
  1235. # Wait for a real push_status before reconciling (#1679): MQTT
  1236. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1237. # the connection, BEFORE `_request_push_all` round-trips. At that
  1238. # instant the `PrinterState` is still on construction defaults — most
  1239. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1240. # If reconcile spawns here, every in-flight archive falls through to
  1241. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1242. # creates a duplicate archive on the real PRINT COMPLETE and
  1243. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1244. # keeps the #1542 mechanism intact: once the first real push_status
  1245. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1246. # fires again with the flag still False — reconcile then runs against
  1247. # actual evidence.
  1248. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1249. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1250. _printer_reconciled_since_connect[printer_id] = True
  1251. spawn_background_task(
  1252. reconcile_stale_active_prints(printer_id),
  1253. name=f"reconcile-stale-prints-{printer_id}",
  1254. )
  1255. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1256. # Re-arm so the next reconnect triggers reconciliation again.
  1257. _printer_reconciled_since_connect[printer_id] = False
  1258. # Same edge, for the calibration table the AMS card reads its K values from.
  1259. #
  1260. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1261. # tables to ask for. A `state_known` gate alone is not enough: the first
  1262. # real push_status is what makes the state known, and the nozzle fields do
  1263. # not always arrive in it. Latching there would spend this connection's one
  1264. # attempt on a printer that could not yet say what was fitted.
  1265. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1266. if (
  1267. state.connected
  1268. and state_known
  1269. and nozzle_known
  1270. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1271. ):
  1272. _printer_kprofiles_primed_since_connect[printer_id] = True
  1273. spawn_background_task(
  1274. prime_kprofile_table(printer_id),
  1275. name=f"prime-kprofiles-{printer_id}",
  1276. )
  1277. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1278. _printer_kprofiles_primed_since_connect[printer_id] = False
  1279. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1280. # connected → disconnected. The "back online" channel is already covered
  1281. # by the print-failure notification (firmware reports gcode_state=FAILED
  1282. # on reconnect of an interrupted print), so we don't add a symmetric
  1283. # online event here.
  1284. prev_connected = _printer_last_connected.get(printer_id)
  1285. _printer_last_connected[printer_id] = state.connected
  1286. if prev_connected is True and not state.connected:
  1287. existing = _printer_offline_notify_tasks.get(printer_id)
  1288. if existing is None or existing.done():
  1289. logging.getLogger(__name__).info(
  1290. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1291. printer_id,
  1292. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1293. )
  1294. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1295. _maybe_notify_printer_offline(printer_id),
  1296. name=f"printer-offline-notify-{printer_id}",
  1297. )
  1298. elif state.connected:
  1299. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1300. if pending is not None and not pending.done():
  1301. logging.getLogger(__name__).info(
  1302. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1303. printer_id,
  1304. )
  1305. pending.cancel()
  1306. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1307. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1308. temps = state.temperatures or {}
  1309. nozzle_temp = round(temps.get("nozzle", 0))
  1310. bed_temp = round(temps.get("bed", 0))
  1311. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1312. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1313. # Auto-detect dual-nozzle printers from MQTT temperature data
  1314. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1315. _nozzle_count_updated.add(printer_id)
  1316. # Update nozzle_count in database
  1317. async with async_session() as db:
  1318. from backend.app.models.printer import Printer
  1319. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1320. printer = result.scalar_one_or_none()
  1321. if printer and printer.nozzle_count != 2:
  1322. printer.nozzle_count = 2
  1323. await db.commit()
  1324. logging.getLogger(__name__).info(
  1325. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1326. )
  1327. # Include target temps for heating phase detection
  1328. bed_target = round(temps.get("bed_target", 0))
  1329. nozzle_target = round(temps.get("nozzle_target", 0))
  1330. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1331. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1332. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts
  1333. ams_dry_key = tuple(a.get("dry_time", 0) for a in (state.raw_data.get("ams") or [])) if state.raw_data else ()
  1334. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1335. #
  1336. # The filament identity fields are here because Configure Slot writes
  1337. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1338. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1339. # matched, this function returned before broadcasting, and the card kept
  1340. # showing the old filament until the 30s fallback poll or a page reload —
  1341. # even though the configure route asks the printer for a fresh pushall and
  1342. # that push does carry the new values. Reset always worked, because it
  1343. # clears tray_type.
  1344. #
  1345. # These fields only change when someone configures a slot or swaps a spool,
  1346. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1347. ams_tray_key = (
  1348. tuple(
  1349. (
  1350. t.get("id"),
  1351. t.get("tray_type", ""),
  1352. t.get("state"),
  1353. t.get("tray_color", ""),
  1354. t.get("tray_info_idx", ""),
  1355. t.get("tray_sub_brands", ""),
  1356. t.get("cali_idx"),
  1357. )
  1358. for a in (state.raw_data.get("ams") or [])
  1359. for t in a.get("tray", [])
  1360. )
  1361. if state.raw_data
  1362. else ()
  1363. )
  1364. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1365. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1366. # in the AMS change-hash (tray fields only, and widening that would fire
  1367. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1368. # screen changed no key at all and the card's inlet badges sat stale until a
  1369. # reload. Like the filament-backup flag, these only move when someone
  1370. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1371. fts_key = (
  1372. state.fila_switch.installed if state.fila_switch else False,
  1373. tuple(sorted(state.ams_switch_inlet.items())),
  1374. # Which hotend holds which slot. Unlike the two above this does move
  1375. # mid-print, on every filament change — but only between discrete slots,
  1376. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1377. # it live: it decides which hotend the Load dialog may offer and whether
  1378. # Unload has anything to act on.
  1379. tuple(
  1380. sorted(
  1381. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1382. # Sort on the extruder id alone: the other members are nullable
  1383. # and comparing None with an int raises.
  1384. key=lambda entry: entry[0],
  1385. )
  1386. ),
  1387. )
  1388. status_key = (
  1389. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1390. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1391. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1392. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1393. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1394. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1395. )
  1396. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1397. if not is_active_print:
  1398. _unauthorized_print_kill_sent.discard(printer_id)
  1399. elif printer_id in _unauthorized_print_kill_sent:
  1400. # stop_print() was already sent for this print; avoid all further
  1401. # ownership and settings work until the printer leaves an active state.
  1402. pass
  1403. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1404. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1405. _unauthorized_print_kill_sent.discard(printer_id)
  1406. else:
  1407. kill_switch_enabled = False
  1408. authorization: bool | None = None
  1409. status_logger = logging.getLogger(__name__)
  1410. try:
  1411. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1412. if kill_switch_enabled:
  1413. async with async_session() as db:
  1414. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1415. except Exception as e:
  1416. # Fail safe: a database/reconciliation error must never turn into an
  1417. # irreversible stop of a print whose ownership is still unknown.
  1418. authorization = None
  1419. status_logger.warning(
  1420. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1421. )
  1422. if not kill_switch_enabled or authorization is True:
  1423. _unauthorized_print_kill_sent.discard(printer_id)
  1424. elif authorization is None:
  1425. _unauthorized_print_kill_sent.discard(printer_id)
  1426. status_logger.debug(
  1427. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1428. printer_id,
  1429. )
  1430. else:
  1431. try:
  1432. stopped = printer_manager.stop_print(printer_id)
  1433. if stopped:
  1434. _unauthorized_print_kill_sent.add(printer_id)
  1435. printer_info = printer_manager.get_printer(printer_id)
  1436. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1437. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1438. notification_data = {
  1439. "status": "stopped",
  1440. "filename": state.gcode_file or state.current_print or "",
  1441. "subtask_name": state.subtask_name or "",
  1442. "progress": state.progress,
  1443. "reason": "unauthorized_print",
  1444. }
  1445. status_logger.warning(
  1446. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1447. printer_id,
  1448. state.state,
  1449. )
  1450. try:
  1451. await ws_manager.broadcast(
  1452. {
  1453. "type": "kill_switch_triggered",
  1454. "printer_id": printer_id,
  1455. "printer_name": printer_name,
  1456. "filename": filename,
  1457. "reason": "unauthorized_print",
  1458. }
  1459. )
  1460. except Exception as e:
  1461. status_logger.warning(
  1462. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1463. )
  1464. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1465. if previous_task is not None and not previous_task.done():
  1466. previous_task.cancel()
  1467. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1468. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1469. name=f"kill-switch-notification-{printer_id}",
  1470. )
  1471. else:
  1472. status_logger.warning(
  1473. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1474. printer_id,
  1475. state.state,
  1476. )
  1477. except Exception as e:
  1478. status_logger.warning(
  1479. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1480. )
  1481. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1482. try:
  1483. printer_info = printer_manager.get_printer(printer_id)
  1484. if printer_info:
  1485. await mqtt_relay.on_printer_status(
  1486. printer_id,
  1487. state,
  1488. printer_info.name,
  1489. printer_info.serial_number,
  1490. printer_manager.is_awaiting_plate_clear(printer_id),
  1491. )
  1492. except Exception:
  1493. pass # Don't fail status callback if MQTT fails
  1494. if _last_status_broadcast.get(printer_id) == status_key:
  1495. return # No change, skip WebSocket broadcast
  1496. _last_status_broadcast[printer_id] = status_key
  1497. # Check for progress milestone notifications (25%, 50%, 75%)
  1498. progress = state.progress or 0
  1499. is_printing = state.state in ("RUNNING", "PRINTING")
  1500. if is_printing and progress > 0:
  1501. # Determine which milestone we've reached
  1502. current_milestone = 0
  1503. if progress >= 75:
  1504. current_milestone = 75
  1505. elif progress >= 50:
  1506. current_milestone = 50
  1507. elif progress >= 25:
  1508. current_milestone = 25
  1509. last_milestone = _last_progress_milestone.get(printer_id, 0)
  1510. # If we've crossed a new milestone, send notification
  1511. if current_milestone > last_milestone:
  1512. _last_progress_milestone[printer_id] = current_milestone
  1513. try:
  1514. from backend.app.models.printer import Printer
  1515. # Read the printer in a short session and release the connection
  1516. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1517. # pinned a pooled connection per milestone, per printer (issue #2572).
  1518. async with async_session() as db:
  1519. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1520. printer = result.scalar_one_or_none()
  1521. printer_name = printer.name if printer else f"Printer {printer_id}"
  1522. filename = state.subtask_name or state.gcode_file or "Unknown"
  1523. # remaining_time is in minutes, convert to seconds for notification
  1524. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1525. # Capture camera snapshot for notification image attachment (no DB held).
  1526. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1527. # Notification send needs a session (provider/template lookups).
  1528. async with async_session() as db:
  1529. await notification_service.on_print_progress(
  1530. printer_id,
  1531. printer_name,
  1532. filename,
  1533. current_milestone,
  1534. db,
  1535. remaining_time_seconds,
  1536. image_data=image_data,
  1537. )
  1538. except Exception as e:
  1539. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1540. elif progress < 5:
  1541. # Reset milestone tracking when print restarts or new print begins
  1542. _last_progress_milestone[printer_id] = 0
  1543. _first_layer_notified[printer_id] = False
  1544. # HMS error codes that should not trigger notifications even though they
  1545. # have known descriptions (e.g. user-initiated actions, not real errors).
  1546. _HMS_NOTIFICATION_SUPPRESS = {
  1547. "0500_400E", # Printing was cancelled (user action, not an error)
  1548. }
  1549. # Check for new HMS errors and send notifications
  1550. current_hms_errors = getattr(state, "hms_errors", []) or []
  1551. if current_hms_errors:
  1552. # Build set of current error codes (using attr for uniqueness)
  1553. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  1554. previously_notified = _notified_hms_errors.get(printer_id, set())
  1555. # Find new errors that haven't been notified yet
  1556. new_error_codes = current_error_codes - previously_notified
  1557. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  1558. _notified_hms_errors[printer_id] = current_error_codes
  1559. _hms_last_seen[printer_id] = time.time()
  1560. if new_error_codes:
  1561. # Get the actual new errors for the notification
  1562. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  1563. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  1564. try:
  1565. from backend.app.models.printer import Printer
  1566. # Read the printer in a short session and release the connection
  1567. # BEFORE the ~15s camera snapshot below (issue #2572).
  1568. async with async_session() as db:
  1569. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1570. printer = result.scalar_one_or_none()
  1571. printer_name = printer.name if printer else f"Printer {printer_id}"
  1572. # Format error details for notification
  1573. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1574. module_names = {
  1575. 0x03: "Print/Task",
  1576. 0x05: "Nozzle/Extruder",
  1577. 0x07: "AMS/Filament",
  1578. 0x0C: "Motion Controller",
  1579. 0x12: "Chamber",
  1580. }
  1581. # Capture camera snapshot once for all error notifications (no DB held).
  1582. error_image_data = await _capture_snapshot_for_notification(
  1583. printer_id, printer, logging.getLogger(__name__)
  1584. )
  1585. # Notification sends need a session (provider/template lookups).
  1586. async with async_session() as db:
  1587. sent_count = 0
  1588. for error in new_errors:
  1589. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1590. # Build short code like "0700_8010"
  1591. # Mask to 16 bits to handle printers that send larger values
  1592. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1593. error_code_masked = error_code_int & 0xFFFF
  1594. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1595. # Only notify for errors with known descriptions — printers
  1596. # send many undocumented/phantom codes that aren't real errors.
  1597. # Resolved at parse time (#2926); short_code is still needed
  1598. # for the suppression set below.
  1599. description = error.description
  1600. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1601. continue
  1602. error_type = f"{module_name} Error"
  1603. error_detail = description
  1604. await notification_service.on_printer_error(
  1605. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1606. )
  1607. sent_count += 1
  1608. if sent_count:
  1609. logging.getLogger(__name__).info(
  1610. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1611. )
  1612. # Also publish to MQTT relay (no DB).
  1613. printer_info = printer_manager.get_printer(printer_id)
  1614. if printer_info:
  1615. errors_data = [
  1616. {
  1617. "code": e.code,
  1618. "attr": e.attr,
  1619. "module": e.module,
  1620. "severity": e.severity,
  1621. }
  1622. for e in new_errors
  1623. ]
  1624. await mqtt_relay.on_printer_error(
  1625. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1626. )
  1627. except Exception as e:
  1628. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1629. else:
  1630. # No HMS errors — only clear tracking after a grace period to prevent
  1631. # flapping errors (brief hms:[] gaps) from re-triggering notifications.
  1632. # Some HMS codes (e.g. chamber temp regulation during PETG prints) toggle
  1633. # on/off every few seconds as conditions fluctuate around thresholds.
  1634. if printer_id in _notified_hms_errors:
  1635. last_seen = _hms_last_seen.get(printer_id, 0)
  1636. if time.time() - last_seen >= _HMS_CLEAR_GRACE_SECONDS:
  1637. _notified_hms_errors.pop(printer_id, None)
  1638. _hms_last_seen.pop(printer_id, None)
  1639. await ws_manager.send_printer_status(
  1640. printer_id,
  1641. printer_state_to_dict(
  1642. state,
  1643. printer_id,
  1644. printer_manager.get_model(printer_id),
  1645. printer_manager.get_drying_targets(printer_id),
  1646. ),
  1647. )
  1648. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1649. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1650. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1651. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1652. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1653. K-profiles are per-nozzle and the printer's calibration table is numbered
  1654. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1655. switch's other inlet therefore silently invalidates every configured slot in
  1656. it: the index stays put and now resolves against the other nozzle's table.
  1657. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1658. and 0.020 on the right kept the left profile after the move, and a manual
  1659. RFID re-read only re-asserted the same wrong one.
  1660. Configuring a slot is a deliberate preparation step, so this re-selects
  1661. rather than re-configures: only the calibration binding moves, and only for
  1662. slots whose spool already has a stored profile for the new nozzle. A slot
  1663. Bambuddy knows nothing about is left exactly as the operator left it.
  1664. """
  1665. logger = logging.getLogger(__name__)
  1666. target_extruder = extruder_for_inlet(inlet)
  1667. if target_extruder is None:
  1668. return
  1669. client = printer_manager.get_client(printer_id)
  1670. state = printer_manager.get_status(printer_id)
  1671. if not client or not state or not state.raw_data:
  1672. return
  1673. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1674. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1675. # the nozzle width, which changes both the K profile to select and the
  1676. # preset the slot should carry.
  1677. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1678. ams_raw = state.raw_data.get("ams")
  1679. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1680. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1681. if not unit:
  1682. return
  1683. try:
  1684. async with async_session() as db:
  1685. for tray in unit.get("tray", []):
  1686. tray_id = int(tray.get("id", -1))
  1687. if tray_id < 0 or not tray.get("tray_type"):
  1688. continue
  1689. current_idx = tray.get("cali_idx")
  1690. profile = await find_slot_kprofile_for_extruder(
  1691. db,
  1692. printer_id,
  1693. ams_id,
  1694. tray_id,
  1695. target_extruder,
  1696. nozzle_diameter,
  1697. printer_manager.get_model(printer_id),
  1698. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1699. )
  1700. if profile is None or profile.cali_idx is None:
  1701. continue
  1702. if current_idx == profile.cali_idx:
  1703. continue # Already on the right one.
  1704. logger.info(
  1705. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1706. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1707. printer_id,
  1708. ams_id,
  1709. tray_id,
  1710. inlet,
  1711. target_extruder,
  1712. profile.name,
  1713. current_idx,
  1714. profile.cali_idx,
  1715. profile.k_value,
  1716. )
  1717. client.extrusion_cali_sel(
  1718. ams_id=ams_id,
  1719. tray_id=tray_id,
  1720. cali_idx=profile.cali_idx,
  1721. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1722. nozzle_diameter=nozzle_diameter,
  1723. )
  1724. except Exception as e:
  1725. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1726. async def on_ams_change(printer_id: int, ams_data: list):
  1727. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  1728. logger = logging.getLogger(__name__)
  1729. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  1730. # on_print_complete may pop _active_sessions during our awaits (#880).
  1731. from backend.app.services.usage_tracker import _active_sessions
  1732. _print_active = printer_id in _active_sessions
  1733. # A slot that reports empty while a print is running is a filament runout,
  1734. # not a spool swap: the spool is still physically in the AMS, just
  1735. # consumed. Dropping either inventory backend's slot link there loses the
  1736. # only record of which spool fed the print, so the completion path can't
  1737. # charge the runout segment to anything. Both cleanup passes below consult
  1738. # this; computed once, up front, so neither depends on the other having run.
  1739. _unlink_state = printer_manager.get_status(printer_id)
  1740. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  1741. # MQTT relay - publish AMS change
  1742. try:
  1743. printer_info = printer_manager.get_printer(printer_id)
  1744. if printer_info:
  1745. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  1746. except Exception:
  1747. pass # Don't fail AMS callback if MQTT fails
  1748. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  1749. # This ensures frontend gets immediate updates when AMS slots are configured
  1750. try:
  1751. state = printer_manager.get_status(printer_id)
  1752. if state:
  1753. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  1754. await ws_manager.send_printer_status(
  1755. printer_id,
  1756. printer_state_to_dict(
  1757. state,
  1758. printer_id,
  1759. printer_manager.get_model(printer_id),
  1760. printer_manager.get_drying_targets(printer_id),
  1761. ),
  1762. )
  1763. except Exception as e:
  1764. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  1765. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1766. # Auto-unlink spool assignments with stale fingerprints
  1767. try:
  1768. async with async_session() as db:
  1769. from sqlalchemy.orm import selectinload
  1770. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1771. from backend.app.models.spool import Spool as _Spool
  1772. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1773. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1774. # Built-in assignments only. Since #2812 they survive a switch to
  1775. # Spoolman mode rather than being deleted by it, and this pass ends
  1776. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1777. # time as the AMS contents changed under the other mode, undoing the
  1778. # preservation more slowly but just as completely.
  1779. assignments = []
  1780. if not await spoolman_owns_assignments(db):
  1781. result = await db.execute(
  1782. select(SA)
  1783. .where(SA.printer_id == printer_id)
  1784. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1785. )
  1786. assignments = result.scalars().all()
  1787. # ``printing_now`` (top of this function) keeps a runout from
  1788. # unlinking the spool that fed the print — the next idle-time pass
  1789. # unlinks it if the user really did take it out.
  1790. stale = []
  1791. for assignment in assignments:
  1792. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1793. if assignment.ams_id == 255:
  1794. ps = printer_manager.get_status(printer_id)
  1795. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1796. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1797. current_tray = None
  1798. for vt in vt_tray_raw:
  1799. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1800. current_tray = vt
  1801. break
  1802. if not current_tray:
  1803. # vt_tray data may not have arrived yet — keep assignment
  1804. continue
  1805. else:
  1806. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1807. if not current_tray:
  1808. if printing_now:
  1809. logger.info(
  1810. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1811. assignment.spool_id,
  1812. assignment.ams_id,
  1813. assignment.tray_id,
  1814. )
  1815. continue
  1816. logger.info(
  1817. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1818. assignment.spool_id,
  1819. assignment.ams_id,
  1820. assignment.tray_id,
  1821. )
  1822. stale.append(assignment) # Slot empty
  1823. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1824. # A Bambu Lab spool is in this slot — check if it's the same spool
  1825. # that's currently assigned. If yes, keep the assignment (avoids
  1826. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1827. # the printer's filament preset on every startup).
  1828. tray_uuid = current_tray.get("tray_uuid", "")
  1829. tag_uid = current_tray.get("tag_uid", "")
  1830. spool = assignment.spool
  1831. spool_matches = False
  1832. if spool:
  1833. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1834. spool.tag_uid
  1835. and tag_uid
  1836. and tag_uid != "0000000000000000"
  1837. and spool.tag_uid.upper() == tag_uid.upper()
  1838. ):
  1839. spool_matches = True
  1840. if spool_matches:
  1841. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  1842. cur_color = current_tray.get("tray_color", "")
  1843. cur_type = current_tray.get("tray_type", "")
  1844. fp_color = assignment.fingerprint_color or ""
  1845. fp_type = assignment.fingerprint_type or ""
  1846. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  1847. assignment.fingerprint_color = cur_color
  1848. assignment.fingerprint_type = cur_type
  1849. logger.debug(
  1850. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  1851. assignment.spool_id,
  1852. assignment.ams_id,
  1853. assignment.tray_id,
  1854. )
  1855. continue
  1856. # Different BL spool or unrecognized — unlink so auto-assign can match
  1857. logger.info(
  1858. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  1859. assignment.spool_id,
  1860. assignment.ams_id,
  1861. assignment.tray_id,
  1862. tray_uuid,
  1863. )
  1864. stale.append(assignment)
  1865. else:
  1866. cur_color = current_tray.get("tray_color", "")
  1867. cur_type = current_tray.get("tray_type", "")
  1868. cur_state = current_tray.get("state")
  1869. fp_color = assignment.fingerprint_color or ""
  1870. fp_type = assignment.fingerprint_type or ""
  1871. # SpoolBuddy pre-config replay: fingerprint_type empty means
  1872. # the slot was empty when the user pre-assigned via SpoolBuddy
  1873. # (the firmware drops ams_filament_setting on empty slots, so
  1874. # MQTT was deferred). The moment any filament gets inserted
  1875. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  1876. # reconfigured spool — fire the deferred configuration.
  1877. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  1878. # extruder" code) OR, on firmwares that don't use the state
  1879. # enum meaningfully, a non-empty tray_type when state is
  1880. # NOT one of the firmware's explicit empty signals (9, 10).
  1881. # state-only was wrong for firmwares that never set 11 — A1
  1882. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  1883. # always report state=3 — so the replay never fired for them
  1884. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  1885. # explicit "empty" signals authoritative over any stale
  1886. # tray_type that might survive the relay's auto-clearing.
  1887. loaded = cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  1888. if not fp_type.strip() and loaded and assignment.spool:
  1889. try:
  1890. from backend.app.api.routes.inventory import (
  1891. apply_spool_to_slot_via_mqtt,
  1892. )
  1893. await apply_spool_to_slot_via_mqtt(
  1894. db=db,
  1895. current_user=None,
  1896. spool=assignment.spool,
  1897. printer_id=printer_id,
  1898. ams_id=assignment.ams_id,
  1899. tray_id=assignment.tray_id,
  1900. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  1901. current_tray_type=cur_type,
  1902. )
  1903. logger.info(
  1904. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  1905. assignment.spool_id,
  1906. printer_id,
  1907. assignment.ams_id,
  1908. assignment.tray_id,
  1909. )
  1910. except Exception:
  1911. logger.exception(
  1912. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  1913. assignment.spool_id,
  1914. printer_id,
  1915. assignment.ams_id,
  1916. assignment.tray_id,
  1917. )
  1918. assignment.fingerprint_color = cur_color
  1919. assignment.fingerprint_type = cur_type
  1920. continue
  1921. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  1922. # Blank tray data mid-print is a runout, not a swap: the
  1923. # firmware clears colour and type when it unloads a spool
  1924. # it just emptied. Unlinking here would erase the record
  1925. # of which spool fed the print so far.
  1926. if printing_now and not cur_color.strip() and not cur_type.strip():
  1927. logger.info(
  1928. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  1929. "(runout?)",
  1930. assignment.spool_id,
  1931. assignment.ams_id,
  1932. assignment.tray_id,
  1933. )
  1934. continue
  1935. # Fingerprint mismatch — but check if tray now matches the
  1936. # assigned spool (e.g. auto-configure changed the tray).
  1937. # Both sides are reduced to the type the slot can carry
  1938. # before comparing: the assign path writes that rather
  1939. # than the spool's raw material (#2902), so a spool whose
  1940. # material is a product line — "PLA+", "HTPLA" — reports
  1941. # back as "PLA" and would otherwise fail this check and
  1942. # be auto-unlinked from the slot it was just assigned to.
  1943. # Reducing the printer's side too keeps slots configured
  1944. # by an older Bambuddy, still reporting "PLA+", matching.
  1945. spool = assignment.spool
  1946. if spool:
  1947. spool_color = (spool.rgba or "FFFFFFFF").upper()
  1948. # Two ways the assign path can have arrived at the
  1949. # slot's type, so both count as "we wrote this".
  1950. # The material column is one; the spool's preset is
  1951. # the other, and it outranks the material when the
  1952. # spool has one -- a spool whose material says PLA
  1953. # and whose preset is "Bambu PLA Aero" puts
  1954. # PLA-AERO in the slot (#2902). Read from the stored
  1955. # preset name rather than resolving the preset,
  1956. # because this runs on every AMS push and a cloud
  1957. # lookup here would be both slow and unavailable on
  1958. # the unauthenticated replay path.
  1959. spool_types = {printer_filament_type(spool.material).upper()}
  1960. if spool.slicer_filament_name:
  1961. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  1962. # An imported local preset stores its type outright,
  1963. # which is what the assign path used -- and the name
  1964. # above may be unset. One keyed read, and only on a
  1965. # mismatch, which is rare.
  1966. #
  1967. # slicer_filament is free text up to fifty characters,
  1968. # so the digits have to be checked against the range
  1969. # of the integer primary key they are about to be
  1970. # compared with. Postgres raises on an out-of-range
  1971. # integer rather than simply not matching, and that
  1972. # would poison this session and abandon the rest of
  1973. # the cleanup pass.
  1974. lp_ref = (spool.slicer_filament or "").strip()
  1975. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  1976. from backend.app.models.local_preset import LocalPreset as _LP
  1977. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  1978. if lp_type:
  1979. spool_types.add(printer_filament_type(lp_type).upper())
  1980. if (
  1981. _colors_similar(cur_color, spool_color)
  1982. and printer_filament_type(cur_type).upper() in spool_types
  1983. ):
  1984. logger.info(
  1985. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  1986. assignment.spool_id,
  1987. assignment.ams_id,
  1988. assignment.tray_id,
  1989. )
  1990. assignment.fingerprint_color = cur_color
  1991. assignment.fingerprint_type = cur_type
  1992. continue
  1993. logger.info(
  1994. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  1995. assignment.spool_id,
  1996. assignment.ams_id,
  1997. assignment.tray_id,
  1998. cur_color,
  1999. cur_type,
  2000. fp_color,
  2001. fp_type,
  2002. spool.rgba if spool else "?",
  2003. spool.material if spool else "?",
  2004. )
  2005. stale.append(assignment) # Spool changed
  2006. # Snapshot slots before delete — ORM attribute access after the
  2007. # commit would refresh against a deleted row.
  2008. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2009. for a in stale:
  2010. await db.delete(a)
  2011. if stale:
  2012. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2013. # Commit any changes (stale deletions and/or fingerprint updates)
  2014. await db.commit()
  2015. # Tell open browsers the assignment is gone (#2575). Only the manual
  2016. # REST assign/unassign endpoints broadcast this event; without it the
  2017. # frontend's spool-assignments cache keeps rendering the unlinked
  2018. # spool on the slot until an unrelated refetch — which reads exactly
  2019. # like "the fix didn't work" (reporter verified: a browser refresh
  2020. # after the swap showed the correct state all along).
  2021. for ams_id, tray_id in unlinked_slots:
  2022. await ws_manager.broadcast(
  2023. {
  2024. "type": "spool_assignment_changed",
  2025. "printer_id": printer_id,
  2026. "ams_id": ams_id,
  2027. "tray_id": tray_id,
  2028. }
  2029. )
  2030. except Exception as e:
  2031. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2032. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2033. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2034. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2035. # "no existing assignment" for the same (printer, ams, tray) and race to
  2036. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2037. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2038. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2039. try:
  2040. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2041. from backend.app.api.routes.settings import get_setting
  2042. from backend.app.models.spool import Spool
  2043. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2044. from backend.app.services.spool_tag_matcher import (
  2045. auto_assign_spool,
  2046. create_spool_from_tray,
  2047. find_matching_untagged_spool,
  2048. get_spool_by_tag,
  2049. is_bambu_tag,
  2050. is_valid_tag,
  2051. link_tag_to_inventory_spool,
  2052. )
  2053. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2054. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2055. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2056. if not _spoolman_on or _spoolman_on.lower() != "true":
  2057. for ams_unit in ams_data:
  2058. if not isinstance(ams_unit, dict):
  2059. continue
  2060. ams_id = int(ams_unit.get("id", 0))
  2061. for tray in ams_unit.get("tray", []):
  2062. if not isinstance(tray, dict):
  2063. continue
  2064. tray_id = int(tray.get("id", 0))
  2065. tag_uid = tray.get("tag_uid", "")
  2066. tray_uuid = tray.get("tray_uuid", "")
  2067. tray_info_idx = tray.get("tray_info_idx", "")
  2068. if not tray.get("tray_type"):
  2069. # Slot reported empty — drop any cached unknown-tag
  2070. # broadcast so reinserting the same spool re-prompts.
  2071. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2072. continue # Empty slot
  2073. # Check if assignment already exists for this slot
  2074. existing = await db.execute(
  2075. select(SA)
  2076. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2077. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2078. )
  2079. existing_assignment = existing.scalar_one_or_none()
  2080. if existing_assignment:
  2081. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2082. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2083. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2084. # Skip during active prints: the usage tracker handles deduction
  2085. # precisely via 3MF data on print completion. Without this guard the
  2086. # AMS remain% SET and the usage tracker ADD both fire from the same
  2087. # MQTT message, doubling the deduction (#880).
  2088. if _print_active:
  2089. continue
  2090. remain_raw = tray.get("remain")
  2091. if (
  2092. remain_raw is not None
  2093. and existing_assignment.spool
  2094. and not existing_assignment.spool.weight_locked
  2095. ):
  2096. try:
  2097. remain_val = int(remain_raw)
  2098. except (TypeError, ValueError):
  2099. remain_val = -1
  2100. if 1 <= remain_val <= 100:
  2101. lw = existing_assignment.spool.label_weight or 1000
  2102. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2103. current_used = existing_assignment.spool.weight_used or 0
  2104. if new_used > current_used + 1:
  2105. logger.info(
  2106. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2107. existing_assignment.spool_id,
  2108. current_used,
  2109. new_used,
  2110. remain_val,
  2111. )
  2112. existing_assignment.spool.weight_used = new_used
  2113. await db.commit()
  2114. # Re-apply stored K-profile when the live tray's
  2115. # cali_idx drifted from the spool's stored profile.
  2116. # This catches "reset slot → re-read" and any other
  2117. # path where the firmware loses the user's K-profile
  2118. # selection while the SpoolAssignment row persists.
  2119. # Per the maintainer's rule: any time a spool tag is
  2120. # identified and matches inventory, the slot must be
  2121. # configured with the spool's stored settings. Without
  2122. # this block the existing-assignment branch only ran
  2123. # weight-sync and let the firmware-default cali_idx win.
  2124. try:
  2125. spool = existing_assignment.spool
  2126. if (
  2127. spool is not None
  2128. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2129. and spool.k_profiles
  2130. ):
  2131. state = printer_manager.get_status(printer_id)
  2132. slot_nozzle = resolve_slot_nozzle(
  2133. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2134. )
  2135. nozzle_diameter = slot_nozzle.diameter
  2136. slot_extruder = slot_nozzle.extruder
  2137. # Prefer exact extruder match, fall back to
  2138. # extruder-agnostic kp for the same printer +
  2139. # nozzle. Avoids hard-skipping when the AMS is
  2140. # mapped differently than at calibration time.
  2141. matching_kp = None
  2142. fallback_kp = None
  2143. for kp in spool.k_profiles:
  2144. if (
  2145. kp.printer_id != printer_id
  2146. or kp.nozzle_diameter != nozzle_diameter
  2147. or kp.cali_idx is None
  2148. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2149. ):
  2150. continue
  2151. if (
  2152. slot_extruder is not None
  2153. and kp.extruder is not None
  2154. and kp.extruder == slot_extruder
  2155. ):
  2156. matching_kp = kp
  2157. break
  2158. if fallback_kp is None:
  2159. fallback_kp = kp
  2160. chosen_kp = matching_kp or fallback_kp
  2161. if chosen_kp is not None:
  2162. live_cali_idx = tray.get("cali_idx")
  2163. # Only fire MQTT when the printer's live
  2164. # cali_idx differs from the stored value.
  2165. # Avoids spamming the broker on every
  2166. # MQTT push during steady-state operation.
  2167. if live_cali_idx != chosen_kp.cali_idx:
  2168. client = printer_manager.get_client(printer_id)
  2169. if client:
  2170. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2171. client.extrusion_cali_sel(
  2172. ams_id=ams_id,
  2173. tray_id=tray_id,
  2174. cali_idx=chosen_kp.cali_idx,
  2175. filament_id=cali_filament_id,
  2176. nozzle_diameter=nozzle_diameter,
  2177. )
  2178. logger.info(
  2179. "Re-applied K-profile cali_idx=%d for spool %d "
  2180. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2181. chosen_kp.cali_idx,
  2182. spool.id,
  2183. printer_id,
  2184. ams_id,
  2185. tray_id,
  2186. live_cali_idx,
  2187. )
  2188. except Exception:
  2189. logger.exception(
  2190. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2191. printer_id,
  2192. ams_id,
  2193. tray_id,
  2194. )
  2195. continue
  2196. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2197. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2198. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2199. if not spool:
  2200. # Try matching an untagged inventory spool (same material/color)
  2201. spool = await find_matching_untagged_spool(db, tray)
  2202. if spool:
  2203. await link_tag_to_inventory_spool(db, spool, tray)
  2204. elif _auto_add_unknown:
  2205. spool = await create_spool_from_tray(db, tray)
  2206. else:
  2207. # Auto-add disabled: surface the slot so the
  2208. # user can add it manually via the UI.
  2209. await _broadcast_unknown_tag(
  2210. printer_id=printer_id,
  2211. ams_id=ams_id,
  2212. tray_id=tray_id,
  2213. tag_uid=tag_uid,
  2214. tray_uuid=tray_uuid,
  2215. tray_type=tray.get("tray_type"),
  2216. tray_color=tray.get("tray_color"),
  2217. tray_sub_brands=tray.get("tray_sub_brands"),
  2218. tray_count=len(ams_unit.get("tray", [])),
  2219. )
  2220. continue
  2221. # Slot matched (existing tag, untagged inventory
  2222. # match, or freshly auto-created spool) — drop any
  2223. # stale dedup so a future tag swap re-prompts.
  2224. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2225. await auto_assign_spool(
  2226. printer_id,
  2227. ams_id,
  2228. tray_id,
  2229. spool,
  2230. printer_manager,
  2231. db,
  2232. tray_info_idx=tray_info_idx,
  2233. )
  2234. await db.commit()
  2235. await ws_manager.broadcast(
  2236. {
  2237. "type": "spool_auto_assigned",
  2238. "printer_id": printer_id,
  2239. "ams_id": ams_id,
  2240. "tray_id": tray_id,
  2241. "spool_id": spool.id,
  2242. }
  2243. )
  2244. logger.info(
  2245. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2246. spool.id,
  2247. printer_id,
  2248. ams_id,
  2249. tray_id,
  2250. )
  2251. elif is_valid_tag(tag_uid, tray_uuid):
  2252. # Non-BL spool with some tag — let user choose
  2253. await _broadcast_unknown_tag(
  2254. printer_id=printer_id,
  2255. ams_id=ams_id,
  2256. tray_id=tray_id,
  2257. tag_uid=tag_uid,
  2258. tray_uuid=tray_uuid,
  2259. tray_type=tray.get("tray_type"),
  2260. tray_color=tray.get("tray_color"),
  2261. tray_sub_brands=tray.get("tray_sub_brands"),
  2262. tray_count=len(ams_unit.get("tray", [])),
  2263. )
  2264. # No-tag slots (generic non-RFID filament) are left alone:
  2265. # nothing to identify, prompting "+ Add" would just create
  2266. # ghost spools with empty tags on every confirm.
  2267. except Exception as e:
  2268. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2269. try:
  2270. async with async_session() as db:
  2271. from backend.app.api.routes.settings import get_setting
  2272. from backend.app.models.printer import Printer
  2273. # Check if Spoolman is enabled
  2274. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2275. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2276. return
  2277. # Check sync mode
  2278. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2279. if sync_mode and sync_mode != "auto":
  2280. return # Only sync on auto mode
  2281. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2282. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2283. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2284. # always owned by per-print tracking, never by AMS auto-sync. The
  2285. # setting is still read by the settings UI for backwards compat but
  2286. # has no effect on the sync path here.
  2287. # Get Spoolman URL
  2288. spoolman_url = await get_setting(db, "spoolman_url")
  2289. if not spoolman_url:
  2290. return
  2291. # Get or create Spoolman client
  2292. client = await get_spoolman_client()
  2293. if not client:
  2294. try:
  2295. client = await init_spoolman_client(spoolman_url)
  2296. except ValueError as exc:
  2297. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2298. return
  2299. # Check if Spoolman is reachable
  2300. if not await client.health_check():
  2301. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2302. return
  2303. # Get printer name for location
  2304. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2305. printer = result.scalar_one_or_none()
  2306. printer_name = printer.name if printer else f"Printer {printer_id}"
  2307. # OPTIMIZATION: Fetch all spools once before processing trays
  2308. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2309. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2310. try:
  2311. cached_spools = await client.get_spools()
  2312. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2313. except Exception as e:
  2314. logger.error(
  2315. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2316. printer_id,
  2317. e,
  2318. )
  2319. return
  2320. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2321. from sqlalchemy.orm import selectinload
  2322. from backend.app.models.spool_assignment import SpoolAssignment
  2323. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2324. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2325. # Built-in remaining weight, used by sync_ams_tray only when the
  2326. # firmware reports an unusable remain%/tray_weight for a slot.
  2327. #
  2328. # Left empty since #2812. This block runs in Spoolman mode only,
  2329. # and until then the built-in table was emptied on the switch, so
  2330. # there was never anything here to read and the fallback was inert.
  2331. # Preserving those rows makes it live again, and it is keyed by slot
  2332. # rather than by spool: after a mode switch the tray may well hold
  2333. # different filament, and ``create_spool`` writes ``remaining_weight``
  2334. # unconditionally, so a stale figure would be seeded into a brand new
  2335. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2336. # intent survives for whoever revisits the cross-mode fallback.
  2337. inventory_weights: dict[tuple[int, int], float] = {}
  2338. if not await spoolman_owns_assignments(db):
  2339. try:
  2340. assign_result = await db.execute(
  2341. select(SpoolAssignment)
  2342. .options(selectinload(SpoolAssignment.spool))
  2343. .where(SpoolAssignment.printer_id == printer_id)
  2344. )
  2345. for assignment in assign_result.scalars().all():
  2346. spool = assignment.spool
  2347. if spool and spool.label_weight > 0:
  2348. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2349. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2350. except Exception as e:
  2351. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2352. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2353. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2354. try:
  2355. slot_result = await db.execute(
  2356. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2357. )
  2358. for slot in slot_result.scalars().all():
  2359. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2360. except Exception as e:
  2361. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2362. # Sync each AMS tray and collect slot changes for DB persistence
  2363. synced = 0
  2364. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2365. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2366. for ams_unit in ams_data:
  2367. if not isinstance(ams_unit, dict):
  2368. continue
  2369. ams_id = int(ams_unit.get("id", 0))
  2370. trays = ams_unit.get("tray", [])
  2371. for tray_data in trays:
  2372. if not isinstance(tray_data, dict):
  2373. continue
  2374. tray_id_raw = int(tray_data.get("id", 0))
  2375. tray = client.parse_ams_tray(ams_id, tray_data)
  2376. if not tray:
  2377. # Empty tray slot — record for local assignment cleanup
  2378. # and drop any cached unknown-tag broadcast so a
  2379. # reinserted spool re-prompts.
  2380. #
  2381. # Not during a running print: a slot that empties there
  2382. # is a filament runout, and the spool is still in the
  2383. # AMS. `spoolman_slot_assignments` is how a tag-less
  2384. # spool assigned through the Bambuddy UI is resolved at
  2385. # completion (#1459), so deleting the row mid-print
  2386. # loses the runout segment's usage — the same failure
  2387. # the internal inventory's auto-unlink had.
  2388. if not printing_now:
  2389. empty_slots.append((ams_id, tray_id_raw))
  2390. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2391. continue
  2392. spool_tag = (
  2393. tray.tray_uuid
  2394. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2395. else tray.tag_uid
  2396. )
  2397. # Provide the hint only when no RFID is available
  2398. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2399. try:
  2400. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2401. result = await client.sync_ams_tray(
  2402. tray,
  2403. printer_name,
  2404. # Per-print tracking is the only weight writer (#1119).
  2405. # AMS auto-sync still maintains spool metadata / slot
  2406. # assignments but no longer touches remaining_weight.
  2407. disable_weight_sync=True,
  2408. cached_spools=cached_spools,
  2409. inventory_remaining=inv_remaining,
  2410. spoolman_spool_id_hint=hint,
  2411. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2412. )
  2413. if result is None and spool_tag and not auto_add_unknown_rfid:
  2414. # Spoolman skipped auto-create per user setting — surface
  2415. # the slot so the UI can offer "+ Add to inventory".
  2416. await _broadcast_unknown_tag(
  2417. printer_id=printer_id,
  2418. ams_id=ams_id,
  2419. tray_id=tray.tray_id,
  2420. tag_uid=tray.tag_uid or "",
  2421. tray_uuid=tray.tray_uuid or "",
  2422. tray_type=tray.tray_type,
  2423. tray_color=tray.tray_color,
  2424. tray_sub_brands=tray.tray_sub_brands,
  2425. tray_count=len(trays),
  2426. )
  2427. elif result:
  2428. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2429. if result:
  2430. synced += 1
  2431. if result.get("id"):
  2432. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2433. # If a new spool was created, add it to the cache
  2434. # so subsequent trays can find it if they reference the same tag
  2435. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2436. if not spool_exists:
  2437. cached_spools.append(result)
  2438. logger.debug(
  2439. "[Printer %s] Added newly created spool %s to cache",
  2440. printer_id,
  2441. result["id"],
  2442. )
  2443. # Reconcile slot_preset_mappings (the same row internal
  2444. # mode keeps in sync via inventory + spool_tag_matcher).
  2445. # Without this the slot card surfaces the previous spool's
  2446. # preset name — same bug shape, different inventory mode.
  2447. from backend.app.services.slot_preset_writer import (
  2448. upsert_slot_preset_for_spoolman_spool,
  2449. )
  2450. await upsert_slot_preset_for_spoolman_spool(
  2451. db=db,
  2452. spoolman_spool=result,
  2453. tray_info_idx=tray.tray_info_idx or "",
  2454. tray_sub_brands=tray.tray_sub_brands or "",
  2455. tray_type=tray.tray_type or "",
  2456. printer_id=printer_id,
  2457. ams_id=ams_id,
  2458. tray_id=tray.tray_id,
  2459. )
  2460. except Exception as e:
  2461. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2462. if synced > 0:
  2463. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2464. # Persist slot assignment changes to the local table
  2465. if slot_changes or empty_slots:
  2466. try:
  2467. for ams_id, tray_id, spool_id in slot_changes:
  2468. await db.execute(
  2469. text(
  2470. "INSERT INTO spoolman_slot_assignments"
  2471. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2472. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2473. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2474. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2475. ),
  2476. {
  2477. "printer_id": printer_id,
  2478. "ams_id": ams_id,
  2479. "tray_id": tray_id,
  2480. "spool_id": spool_id,
  2481. },
  2482. )
  2483. for ams_id, tray_id in empty_slots:
  2484. await db.execute(
  2485. delete(SpoolmanSlotAssignment).where(
  2486. SpoolmanSlotAssignment.printer_id == printer_id,
  2487. SpoolmanSlotAssignment.ams_id == ams_id,
  2488. SpoolmanSlotAssignment.tray_id == tray_id,
  2489. )
  2490. )
  2491. await db.commit()
  2492. except Exception as e:
  2493. await db.rollback()
  2494. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2495. except Exception as e:
  2496. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2497. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  2498. """Capture a camera snapshot for notification image attachment.
  2499. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2500. Uses: external camera > buffered frame > fresh capture.
  2501. """
  2502. if not printer:
  2503. return None
  2504. try:
  2505. from backend.app.api.routes.settings import get_setting
  2506. async with async_session() as db:
  2507. capture_enabled = await get_setting(db, "capture_finish_photo")
  2508. if capture_enabled is not None and capture_enabled.lower() != "true":
  2509. return None
  2510. # Try external camera first
  2511. if printer.external_camera_enabled and printer.external_camera_url:
  2512. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2513. from backend.app.api.routes.camera import live_frame_for_capture
  2514. from backend.app.services.external_camera import capture_frame
  2515. # An external camera allows one reader, so capturing while a viewer
  2516. # is attached fails (#2707). A None here falls through to the paths
  2517. # below exactly as a failed capture did.
  2518. defer, buffered = live_frame_for_capture(printer_id)
  2519. if defer:
  2520. frame_data = buffered
  2521. else:
  2522. frame_data = await capture_frame(
  2523. printer.external_camera_url,
  2524. printer.external_camera_type or "mjpeg",
  2525. snapshot_url=printer.external_camera_snapshot_url,
  2526. )
  2527. if frame_data and len(frame_data) <= 2_500_000:
  2528. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2529. return _apply_camera_rotation(frame_data, printer, logger)
  2530. # Try buffered frame from active stream
  2531. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  2532. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  2533. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  2534. buffered_frame = get_buffered_frame(printer_id)
  2535. if (active_for_printer or active_chamber) and buffered_frame:
  2536. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  2537. if len(buffered_frame) <= 2_500_000:
  2538. return _apply_camera_rotation(buffered_frame, printer, logger)
  2539. # Fresh capture from printer camera
  2540. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  2541. from backend.app.services.camera import capture_camera_frame_bytes
  2542. frame_data = await capture_camera_frame_bytes(
  2543. printer.ip_address, printer.access_code, printer.model, timeout=15
  2544. )
  2545. if frame_data and len(frame_data) <= 2_500_000:
  2546. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  2547. return _apply_camera_rotation(frame_data, printer, logger)
  2548. except Exception as e:
  2549. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  2550. return None
  2551. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  2552. """#1867: bank a recent in-print camera frame for the finish photo.
  2553. Called on every layer change and (#2547) on every print-progress advance.
  2554. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  2555. path has a pre-End-G-code image for prints that end with a plate swap.
  2556. Both drivers are print telemetry that stops the instant printing ends: no
  2557. further layers, and progress freezes before the End G-code (e.g. SwapMod
  2558. plate swap) executes. So the last banked frame is always the finished print,
  2559. never the swapped plate — that property is what the #1867 path relies on and
  2560. it must survive any change to the throttle below.
  2561. Layer changes alone were not enough: they stop when the *final* layer
  2562. begins, which on a three-minute last layer left the bank stale by the whole
  2563. length of that layer (#2547). Progress keeps ticking through it.
  2564. Best-effort: any failure just leaves the previous banked frame.
  2565. """
  2566. logger = logging.getLogger(__name__)
  2567. client = printer_manager.get_client(printer_id)
  2568. state = client.state if client else None
  2569. if not state or state.state != "RUNNING":
  2570. return
  2571. # Only during actual extrusion — firmware ticks layer_num during the
  2572. # pre-print calibration sequence, whose sub-stages are non-zero.
  2573. if state.mc_print_sub_stage not in (None, 0):
  2574. return
  2575. # #2547: throttled uniformly, with no last-layer exemption. The old code
  2576. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  2577. # now that progress advances also drive banking, that exemption would fire a
  2578. # camera grab on every percent tick of the last layer. Bambu printers accept
  2579. # one RTSP client at a time, so each grab contends with the live view.
  2580. now = time.monotonic()
  2581. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  2582. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  2583. return
  2584. total = state.total_layers or 0
  2585. try:
  2586. async with async_session() as db:
  2587. from backend.app.models.printer import Printer
  2588. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2589. printer = result.scalar_one_or_none()
  2590. if not printer:
  2591. return
  2592. # Reuses the notification snapshot path, which honours the
  2593. # `capture_finish_photo` setting (returns None when disabled) so we
  2594. # don't bank frames the user never asked for.
  2595. frame = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2596. if frame:
  2597. _inprint_frame_bank[printer_id] = frame
  2598. _inprint_frame_bank_ts[printer_id] = now
  2599. logger.debug(
  2600. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  2601. printer_id,
  2602. layer_num,
  2603. total,
  2604. len(frame),
  2605. )
  2606. except Exception as e:
  2607. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  2608. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  2609. """Apply camera rotation to snapshot image if configured."""
  2610. from backend.app.services.camera import apply_camera_rotation
  2611. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  2612. async def _send_print_start_notification(
  2613. printer_id: int,
  2614. data: dict,
  2615. archive_data: dict | None = None,
  2616. logger=None,
  2617. ):
  2618. """Helper to send print start notification with optional archive data."""
  2619. if logger is None:
  2620. logger = logging.getLogger(__name__)
  2621. try:
  2622. async with async_session() as db:
  2623. from backend.app.models.printer import Printer
  2624. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2625. printer = result.scalar_one_or_none()
  2626. printer_name = printer.name if printer else f"Printer {printer_id}"
  2627. # Capture camera snapshot for notification image attachment
  2628. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  2629. if image_data:
  2630. if archive_data is None:
  2631. archive_data = {}
  2632. archive_data["image_data"] = image_data
  2633. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  2634. # Send user-specific email notification for print start
  2635. if archive_data and archive_data.get("created_by_id"):
  2636. await notification_service.send_user_print_email(
  2637. event_type="user_print_start",
  2638. created_by_id=archive_data["created_by_id"],
  2639. printer_name=printer_name,
  2640. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  2641. db=db,
  2642. )
  2643. except Exception as e:
  2644. logger.warning("Notification on_print_start failed: %s", e)
  2645. async def _dispatch_user_print_email(
  2646. status: str,
  2647. created_by_id: int | None,
  2648. printer_name: str,
  2649. filename: str,
  2650. db,
  2651. ) -> None:
  2652. """Send a user-specific print-completion email based on print status.
  2653. Maps the normalised print status to the correct event type and delegates
  2654. to :meth:`NotificationService.send_user_print_email`. A single helper
  2655. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  2656. "stopped"`` dispatch block at every call site.
  2657. Does nothing if *created_by_id* is ``None``.
  2658. """
  2659. if created_by_id is None:
  2660. return
  2661. if status == "completed":
  2662. event_type = "user_print_complete"
  2663. elif status == "failed":
  2664. event_type = "user_print_failed"
  2665. elif status in ("stopped", "aborted", "cancelled"):
  2666. event_type = "user_print_stopped"
  2667. else:
  2668. return
  2669. await notification_service.send_user_print_email(
  2670. event_type=event_type,
  2671. created_by_id=created_by_id,
  2672. printer_name=printer_name,
  2673. filename=filename,
  2674. db=db,
  2675. )
  2676. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  2677. """Extract printable objects from an archive's 3MF file and store in printer state."""
  2678. try:
  2679. from backend.app.services.archive import extract_printable_objects_from_archive
  2680. client = printer_manager.get_client(printer_id)
  2681. if not client:
  2682. return
  2683. # Extract with positions for UI overlay, scoped to the plate that
  2684. # is printing — resolve_plate_id is the same resolver /cover uses,
  2685. # so the object list can't disagree with the thumbnail it is drawn
  2686. # over (#2522).
  2687. printable_objects, bbox_all = extract_printable_objects_from_archive(
  2688. app_settings.base_dir / archive.file_path,
  2689. plate_number=resolve_plate_id(client.state),
  2690. )
  2691. if printable_objects:
  2692. client.state.printable_objects = printable_objects
  2693. client.state.printable_objects_bbox_all = bbox_all
  2694. client.state.skipped_objects = []
  2695. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  2696. except Exception as e:
  2697. logger.debug("Failed to extract printable objects from archive: %s", e)
  2698. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  2699. """Put the skip-objects list back after a restart mid-print.
  2700. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  2701. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  2702. which the #1304 guard suppresses on the first RUNNING push after startup.
  2703. Everything else this hook restores (the archive, the usage-tracking session,
  2704. the timelapse baseline) was already handled; the object list was not, so a
  2705. restart mid-print took skip-objects away for the rest of that print.
  2706. Nothing recovered it either: the printer card gates its Skip button on the
  2707. object count, and the one endpoint that can rebuild the list is reachable
  2708. only from the modal that button opens.
  2709. Anchored on ``subtask_id``, which the firmware mints per print, so a
  2710. leftover ``status="printing"`` row from a completion we never saw cannot
  2711. hand this print someone else's objects. Without one, nothing is loaded
  2712. rather than guessed — the reload path on ``GET /print/objects`` covers that
  2713. case on demand.
  2714. """
  2715. client = printer_manager.get_client(printer_id)
  2716. if client is None or client.state.printable_objects:
  2717. return
  2718. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  2719. if subtask_id in ("", "0"):
  2720. return
  2721. from backend.app.models.archive import PrintArchive
  2722. archive = await db.scalar(
  2723. select(PrintArchive)
  2724. .where(
  2725. PrintArchive.printer_id == printer_id,
  2726. PrintArchive.status == "printing",
  2727. PrintArchive.subtask_id == subtask_id,
  2728. )
  2729. .order_by(PrintArchive.created_at.desc())
  2730. .limit(1)
  2731. )
  2732. if archive is not None:
  2733. _load_objects_from_archive(archive, printer_id, logger)
  2734. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  2735. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  2736. # past it; the second covers a handshake that failed again on the way back and
  2737. # armed a fresh one. Module-level so tests can shrink them.
  2738. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  2739. # printer_id -> the in-flight retry task, so print completion can cancel it.
  2740. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  2741. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  2742. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  2743. # by view, so two views race), the cool-off retry task, and print completion.
  2744. # Without this they each read file_path == "" and each run a full copy, so the row
  2745. # ends up pointing at one timestamped directory while the others sit orphaned.
  2746. #
  2747. # Keyed by printer rather than archive because a printer runs one print at a time,
  2748. # which makes the two equally strong here — and it bounds the dict by printer
  2749. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  2750. # done safely: `Lock.locked()` reads False between release and the queued waiter
  2751. # resuming, so "no waiters" is not a question this API can answer.
  2752. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  2753. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2754. """Fill in a no-3MF archive from a 3MF that turned up later.
  2755. Returns True when the row was upgraded. Safe to call speculatively: it
  2756. verifies the archive still exists, is still a fallback, and that the file
  2757. is a readable 3MF before touching anything.
  2758. Serialised per printer — see ``_fallback_recovery_locks``.
  2759. """
  2760. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  2761. async with lock:
  2762. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  2763. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  2764. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  2765. import zipfile
  2766. from backend.app.models.archive import PrintArchive
  2767. from backend.app.services.archive import ArchiveService
  2768. logger = logging.getLogger(__name__)
  2769. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  2770. return False
  2771. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  2772. # A truncated or half-written download is worse than no download: it
  2773. # would replace an honest empty archive with wrong metadata.
  2774. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  2775. return False
  2776. async with async_session() as db:
  2777. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2778. if archive is None or archive.deleted_at is not None:
  2779. return False
  2780. if archive.file_path:
  2781. # Already recovered, or never was a fallback. Either way there is a
  2782. # real 3MF attached and overwriting it is not this function's job.
  2783. return False
  2784. print_data = (archive.extra_data or {}).get("_print_data") or {}
  2785. service = ArchiveService(db)
  2786. recovered = await service.archive_print(
  2787. printer_id=printer_id,
  2788. source_file=source_3mf,
  2789. print_data={**print_data, "status": archive.status or "printing"},
  2790. subtask_id=archive.subtask_id,
  2791. update_archive_id=archive.id,
  2792. )
  2793. if recovered is None:
  2794. return False
  2795. logger.info(
  2796. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  2797. archive_id,
  2798. source_3mf,
  2799. recovered.file_size,
  2800. )
  2801. # `archive_updated`, not `archive_created` — the row was already on the
  2802. # Archives page as an empty card and is now filled in, not new.
  2803. await ws_manager.send_archive_updated(
  2804. {
  2805. "id": recovered.id,
  2806. "printer_id": recovered.printer_id,
  2807. "filename": recovered.filename,
  2808. "print_name": recovered.print_name,
  2809. "status": recovered.status,
  2810. }
  2811. )
  2812. return True
  2813. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  2814. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  2815. Called from the paths that pull a 3MF for a print that is already under way
  2816. — chiefly the cover endpoint, which downloads the very file the archive flow
  2817. could not get and, before #2957, used it for a thumbnail and nothing else.
  2818. The bytes are already local, so this costs a parse and a row update.
  2819. No-op when the running print has a real archive, which is the common case.
  2820. """
  2821. from backend.app.models.archive import PrintArchive
  2822. logger = logging.getLogger(__name__)
  2823. # `_active_prints` is keyed on the raw names seen at print start — the
  2824. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  2825. # Callers here arrive with whichever variant their own path produced, so
  2826. # match on the same normalization the download cache uses rather than on an
  2827. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  2828. # endpoint find an archive registered under "Desktop_Goose".
  2829. wanted = normalize_3mf_name(name)
  2830. archive_id = None
  2831. for (key_printer_id, key_name), value in list(_active_prints.items()):
  2832. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  2833. archive_id = value
  2834. break
  2835. if archive_id is None:
  2836. return False
  2837. async with async_session() as db:
  2838. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  2839. # Cheap pre-check so the common case (a normal archive) does no work.
  2840. if archive is None or archive.file_path or archive.deleted_at is not None:
  2841. return False
  2842. try:
  2843. return await _recover_fallback_archive(archive_id, path, printer_id)
  2844. except Exception as e:
  2845. # Recovery is opportunistic. A failure here must never take down the
  2846. # caller, which is usually just trying to render a thumbnail.
  2847. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  2848. return False
  2849. def _schedule_fallback_3mf_retry(printer_id: int, archive_id: int, filenames: list[str]) -> None:
  2850. """Re-attempt the 3MF download after the printer's FTPS cool-off clears."""
  2851. logger = logging.getLogger(__name__)
  2852. async def _retry() -> None:
  2853. from backend.app.models.archive import PrintArchive
  2854. from backend.app.models.printer import Printer
  2855. for delay in _FALLBACK_3MF_RETRY_DELAYS_SECONDS:
  2856. await asyncio.sleep(delay)
  2857. async with async_session() as db:
  2858. archive = (
  2859. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2860. ).scalar_one_or_none()
  2861. if archive is None or archive.deleted_at is not None or archive.file_path:
  2862. return
  2863. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  2864. if printer is None:
  2865. return
  2866. # Read the fields while the session is open rather than touching
  2867. # a detached instance minutes later, mid-download.
  2868. printer_ip = printer.ip_address
  2869. printer_code = printer.access_code
  2870. printer_model = printer.model
  2871. # Someone else may have fetched it in the meantime — the cover
  2872. # endpoint routinely does, and its copy is the same bytes.
  2873. for name in filenames:
  2874. cached = get_cached_3mf(printer_id, name)
  2875. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  2876. return
  2877. if ftps_handshake_blocked(printer_ip):
  2878. logger.info(
  2879. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  2880. printer_id,
  2881. archive_id,
  2882. )
  2883. continue
  2884. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  2885. for candidate in filenames:
  2886. # Bare name only. These come from the print-start flow, which
  2887. # already strips the path, but the local temp write must not
  2888. # depend on that holding for every future caller — a name that
  2889. # is absolute or contains ".." would otherwise escape the data
  2890. # volume via the `/` operator.
  2891. name = Path(candidate).name
  2892. if not name or name in (".", ".."):
  2893. continue
  2894. if not name.endswith(".3mf"):
  2895. name = f"{name}.3mf"
  2896. temp_path = app_settings.archive_dir / "temp" / name
  2897. temp_path.parent.mkdir(parents=True, exist_ok=True)
  2898. try:
  2899. hit = await download_file_try_paths_async(
  2900. printer_ip,
  2901. printer_code,
  2902. ftp_probe_paths(name),
  2903. temp_path,
  2904. socket_timeout=ftp_timeout,
  2905. printer_model=printer_model,
  2906. )
  2907. except Exception as e:
  2908. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  2909. continue
  2910. if not hit:
  2911. continue
  2912. cache_3mf_download(printer_id, name, temp_path)
  2913. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  2914. return
  2915. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  2916. async def _guarded() -> None:
  2917. try:
  2918. await _retry()
  2919. except asyncio.CancelledError:
  2920. raise
  2921. except Exception as e:
  2922. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  2923. finally:
  2924. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  2925. _fallback_3mf_retry_tasks.pop(printer_id, None)
  2926. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  2927. if existing and not existing.done():
  2928. existing.cancel()
  2929. task = asyncio.create_task(_guarded())
  2930. _fallback_3mf_retry_tasks[printer_id] = task
  2931. logger.info(
  2932. "[RECOVER] Archive %s has no 3MF because printer %s was in its FTPS cool-off; will retry",
  2933. archive_id,
  2934. printer_id,
  2935. )
  2936. async def on_print_start(printer_id: int, data: dict):
  2937. """Handle print start - archive the 3MF file immediately."""
  2938. logger = logging.getLogger(__name__)
  2939. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  2940. # Clear any stale user-stopped flag from previous print cycles
  2941. _user_stopped_printers.discard(printer_id)
  2942. _kill_switch_notification_tasks.pop(printer_id, None)
  2943. # #1721: drop any leftover pre-captured finish frame from a prior print
  2944. # so a never-consumed cache entry can't bleed into the new print's photo.
  2945. _stage22_finish_frames.pop(printer_id, None)
  2946. # #1867: same for the in-print frame bank — a queued print must not reuse
  2947. # the previous job's banked frame.
  2948. _inprint_frame_bank.pop(printer_id, None)
  2949. _inprint_frame_bank_ts.pop(printer_id, None)
  2950. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  2951. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  2952. # print's flag instead of inheriting it.
  2953. print_dispatch_context.adopt(printer_id)
  2954. # Cancel any active bed cooldown waiter for this printer
  2955. if _bed_cool_waiters.pop(printer_id, None):
  2956. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  2957. # Clear cached cover images so the new print's thumbnail is fetched fresh
  2958. from backend.app.api.routes.printers import clear_cover_cache
  2959. clear_cover_cache(printer_id)
  2960. await ws_manager.send_print_start(printer_id, data)
  2961. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  2962. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  2963. # MQTT relay - publish print start
  2964. try:
  2965. printer_info = printer_manager.get_printer(printer_id)
  2966. if printer_info:
  2967. await mqtt_relay.on_print_start(
  2968. printer_id,
  2969. printer_info.name,
  2970. printer_info.serial_number,
  2971. data.get("filename", ""),
  2972. data.get("subtask_name", ""),
  2973. )
  2974. except Exception:
  2975. pass # Don't fail print start callback if MQTT fails
  2976. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  2977. # and mapping, and the seeded tray-change log.
  2978. #
  2979. # Unconditional, for both inventory backends. This only *captures* — the
  2980. # writing is still split, with the internal tracker skipped at completion
  2981. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  2982. # carries its plate-scoped 3MF figures and stored mapping, but not the
  2983. # tray-change log, and that log is the only record of which spool fed
  2984. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  2985. # it on one side only would leave Spoolman users with the mid-print
  2986. # restart bug this fixes for everyone else.
  2987. try:
  2988. async with async_session() as db:
  2989. from backend.app.api.routes.settings import get_setting
  2990. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  2991. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2992. await usage_on_print_start(
  2993. printer_id,
  2994. data,
  2995. printer_manager,
  2996. db=db,
  2997. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  2998. )
  2999. except Exception as e:
  3000. logger.warning("Usage tracker on_print_start failed: %s", e)
  3001. # Track if notification was sent (to avoid sending twice)
  3002. notification_sent = False
  3003. # Smart plug automation: turn on plug when print starts
  3004. try:
  3005. async with async_session() as db:
  3006. await smart_plug_manager.on_print_start(printer_id, db)
  3007. except Exception as e:
  3008. logger.warning("Smart plug on_print_start failed: %s", e)
  3009. async with async_session() as db:
  3010. from backend.app.models.printer import Printer
  3011. from backend.app.services.bambu_ftp import list_files_async
  3012. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3013. printer = result.scalar_one_or_none()
  3014. # Plate detection check - pause if objects detected on build plate
  3015. logger.info(
  3016. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3017. )
  3018. if printer and printer.plate_detection_enabled:
  3019. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3020. # Release the pooled DB connection before the plate-detection camera
  3021. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3022. # printer SELECT has run so far — nothing to persist — so this commit
  3023. # is a data-noop that ends the read transaction and returns the
  3024. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3025. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3026. # archive lookups below re-acquire a fresh connection on next execute.
  3027. await db.commit()
  3028. try:
  3029. from backend.app.services.plate_detection import check_plate_empty
  3030. # Build ROI tuple from printer settings if available
  3031. roi = None
  3032. if all(
  3033. [
  3034. printer.plate_detection_roi_x is not None,
  3035. printer.plate_detection_roi_y is not None,
  3036. printer.plate_detection_roi_w is not None,
  3037. printer.plate_detection_roi_h is not None,
  3038. ]
  3039. ):
  3040. roi = (
  3041. printer.plate_detection_roi_x,
  3042. printer.plate_detection_roi_y,
  3043. printer.plate_detection_roi_w,
  3044. printer.plate_detection_roi_h,
  3045. )
  3046. # Auto-turn on chamber light if it's off for better detection
  3047. light_was_off = False
  3048. client = printer_manager.get_client(printer_id)
  3049. if client and client.state:
  3050. light_was_off = not client.state.chamber_light
  3051. if light_was_off:
  3052. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3053. client.set_chamber_light(True)
  3054. # Wait for light to physically turn on and camera to adjust exposure
  3055. await asyncio.sleep(2.5)
  3056. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3057. plate_result = await check_plate_empty(
  3058. printer_id=printer_id,
  3059. ip_address=printer.ip_address,
  3060. access_code=printer.access_code,
  3061. model=printer.model,
  3062. include_debug_image=False,
  3063. external_camera_url=printer.external_camera_url,
  3064. external_camera_type=printer.external_camera_type,
  3065. use_external=printer.external_camera_enabled,
  3066. roi=roi,
  3067. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3068. )
  3069. # Restore chamber light to original state
  3070. if light_was_off and client:
  3071. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3072. client.set_chamber_light(False)
  3073. if not plate_result.needs_calibration and not plate_result.is_empty:
  3074. # Objects detected - pause the print!
  3075. logger.warning(
  3076. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3077. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3078. )
  3079. client = printer_manager.get_client(printer_id)
  3080. if client:
  3081. client.pause_print()
  3082. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3083. # Send notification about plate not empty
  3084. await ws_manager.broadcast(
  3085. {
  3086. "type": "plate_not_empty",
  3087. "printer_id": printer_id,
  3088. "printer_name": printer.name,
  3089. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3090. }
  3091. )
  3092. # Also send push notification
  3093. try:
  3094. await notification_service.on_plate_not_empty(
  3095. printer_id=printer_id,
  3096. printer_name=printer.name,
  3097. db=db,
  3098. difference_percent=plate_result.difference_percent,
  3099. )
  3100. except Exception as notif_err:
  3101. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3102. else:
  3103. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3104. except Exception as plate_err:
  3105. # Don't block print on plate detection errors
  3106. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3107. if not printer:
  3108. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3109. if not notification_sent:
  3110. await _send_print_start_notification(printer_id, data, logger=logger)
  3111. return
  3112. if not printer.auto_archive:
  3113. # auto-archive disabled — check if there's an expected print (dispatched
  3114. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3115. # If so, fall through to the expected-print handling below so the archive
  3116. # is tracked in _active_prints and usage tracking works at completion.
  3117. _fn = data.get("filename", "")
  3118. _sn = data.get("subtask_name", "")
  3119. _check_keys: list[tuple[int, str]] = []
  3120. if _sn:
  3121. _check_keys += [
  3122. (printer_id, _sn),
  3123. (printer_id, f"{_sn}.3mf"),
  3124. (printer_id, f"{_sn}.gcode.3mf"),
  3125. ]
  3126. if _fn:
  3127. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3128. _check_keys.append((printer_id, _base_fn))
  3129. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3130. _check_keys += [
  3131. (printer_id, _no_archive_base),
  3132. (printer_id, f"{_no_archive_base}.3mf"),
  3133. ]
  3134. _has_expected = any(k in _expected_prints for k in _check_keys)
  3135. if not _has_expected:
  3136. # No expected print — truly external print (started from slicer/touchscreen)
  3137. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3138. if not notification_sent:
  3139. _no_archive_creator: int | None = None
  3140. for _key in _check_keys:
  3141. _expected_prints.pop(_key, None)
  3142. _expected_print_registered_at.pop(_key, None)
  3143. popped_creator = _expected_print_creators.pop(_key, None)
  3144. if _no_archive_creator is None:
  3145. _no_archive_creator = popped_creator
  3146. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3147. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3148. return
  3149. else:
  3150. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3151. # Get the filename and subtask_name
  3152. filename = data.get("filename", "")
  3153. subtask_name = data.get("subtask_name", "")
  3154. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3155. # present, it lets us match an archive across a backend restart (#972):
  3156. # same id → same print → resume the existing row instead of cancelling
  3157. # it and recreating from scratch (which loses started_at). Treat "0"
  3158. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3159. raw_mqtt = data.get("raw_data") or {}
  3160. subtask_id = raw_mqtt.get("subtask_id")
  3161. if subtask_id is not None:
  3162. subtask_id = str(subtask_id).strip()
  3163. if subtask_id in ("", "0"):
  3164. subtask_id = None
  3165. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3166. # Skip the printer's own jobs — a calibration run is not a user's print.
  3167. # See is_internal_printer_job for what counts and why both fields are
  3168. # tested; the pressure-advance line reports as a subtask name with no
  3169. # /usr/ path, which the old prefix-only test here missed entirely.
  3170. #
  3171. # No notification either. The event describes the printer calibrating
  3172. # itself, so "Print started" is as wrong as the archive was, and the
  3173. # matching completion is suppressed in on_print_complete for the same
  3174. # reason.
  3175. if is_internal_printer_job(filename, subtask_name):
  3176. logger.info(
  3177. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3178. filename,
  3179. subtask_name,
  3180. )
  3181. return
  3182. if not filename and not subtask_name:
  3183. # Send notification without archive data (no filename)
  3184. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3185. if not notification_sent:
  3186. await _send_print_start_notification(printer_id, data, logger=logger)
  3187. return
  3188. # Check if this is an expected print from reprint/scheduled
  3189. # Build list of possible keys to check
  3190. expected_keys = []
  3191. if subtask_name:
  3192. expected_keys.append((printer_id, subtask_name))
  3193. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3194. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3195. if filename:
  3196. fname = filename.split("/")[-1] if "/" in filename else filename
  3197. expected_keys.append((printer_id, fname))
  3198. # Strip extensions to match
  3199. base = fname.replace(".gcode", "").replace(".3mf", "")
  3200. expected_keys.append((printer_id, base))
  3201. expected_keys.append((printer_id, f"{base}.3mf"))
  3202. expected_archive_id = None
  3203. for key in expected_keys:
  3204. expected_archive_id = _expected_prints.pop(key, None)
  3205. _expected_print_registered_at.pop(key, None)
  3206. if expected_archive_id:
  3207. # Clean up other possible keys for this print
  3208. for other_key in expected_keys:
  3209. _expected_prints.pop(other_key, None)
  3210. _expected_print_registered_at.pop(other_key, None)
  3211. break
  3212. if expected_archive_id:
  3213. # This is a reprint/scheduled print - use existing archive, don't create new one
  3214. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3215. from backend.app.models.archive import PrintArchive
  3216. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3217. archive = result.scalar_one_or_none()
  3218. if archive:
  3219. # Update archive status to printing
  3220. archive.status = "printing"
  3221. archive.started_at = datetime.now(timezone.utc)
  3222. # Reprint of an archive reuses the source row. Without resetting
  3223. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3224. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3225. # extracts the *original* print's last frame, which then ships in
  3226. # the completion notification (#1707). Clear the path so the
  3227. # scanner runs fresh; also unlink the old video file so reprints
  3228. # don't accumulate orphans in the archive directory. Photos list
  3229. # is left alone — accumulating one finish photo per run is fine.
  3230. # The print-start baseline (#2704) is stale for the same reason:
  3231. # it describes the printer before the previous run. The capture
  3232. # below overwrites it, but clear it here too so an early failure
  3233. # can't leave the scan diffing against the wrong snapshot.
  3234. archive.timelapse_baseline = None
  3235. stale_timelapse_relpath = archive.timelapse_path
  3236. if stale_timelapse_relpath:
  3237. archive.timelapse_path = None
  3238. try:
  3239. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3240. if stale_path.is_file():
  3241. stale_path.unlink()
  3242. logger.info(
  3243. "Deleted stale timelapse %s on reprint of archive %s",
  3244. stale_timelapse_relpath,
  3245. expected_archive_id,
  3246. )
  3247. except OSError as e:
  3248. logger.warning(
  3249. "Failed to delete stale timelapse %s on reprint: %s",
  3250. stale_timelapse_relpath,
  3251. e,
  3252. )
  3253. # Persist a restart-stable id so a later restart resumes this
  3254. # archive by subtask_id instead of name-matching + duplicating
  3255. # it (#1485). The printer often hasn't echoed subtask_id back
  3256. # this soon after dispatch, so fall back to the id Bambuddy
  3257. # minted when it sent the print command. Scoped to this
  3258. # expected-print branch on purpose: an expected match means
  3259. # Bambuddy dispatched this exact print in this process, so the
  3260. # client's last-dispatch id genuinely belongs to it — using it
  3261. # for an externally-started print could mis-tag the archive.
  3262. effective_subtask_id = subtask_id
  3263. if not effective_subtask_id:
  3264. _client = printer_manager.get_client(printer_id)
  3265. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3266. if _dispatched:
  3267. effective_subtask_id = str(_dispatched).strip() or None
  3268. # Update on first-set OR on reprint (the queue dispatcher mints
  3269. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3270. # the rewrite for reprints leaves the archive holding the FIRST
  3271. # run's id; if MQTT then reconnects mid-print, the reconciler
  3272. # (#1542) compares the stale stored id against the printer's
  3273. # live id, sees a mismatch, and synthesises a bogus PRINT
  3274. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3275. # in #1807. Inequality check preserves the noop-on-stable-push
  3276. # behaviour the earlier `not archive.subtask_id` guard provided.
  3277. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3278. archive.subtask_id = effective_subtask_id
  3279. # #1403 follow-up: VP-queue archives are created with
  3280. # printer_id=None at queue-add time (we don't know which
  3281. # printer will run the job yet). When the print actually
  3282. # starts on a specific printer the expected-archive lookup
  3283. # used to skip this assignment, leaving printer_id=None
  3284. # forever — which then disables the "Scan for timelapse"
  3285. # button in ArchivesPage (gated on !archive.printer_id).
  3286. if archive.printer_id != printer_id:
  3287. archive.printer_id = printer_id
  3288. await db.commit()
  3289. # Track as active print
  3290. _active_prints[(printer_id, archive.filename)] = archive.id
  3291. if subtask_name:
  3292. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3293. # Start timelapse session if external camera is enabled (#1353).
  3294. # Queue / VP-dispatched prints land here in the expected-archive
  3295. # branch and used to skip start_session entirely — frames were
  3296. # never captured and the post-print stitch silently returned None.
  3297. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  3298. # Inject ams_mapping into usage tracker session — the session was created
  3299. # before expected-print promotion, so it may have ams_mapping=None when
  3300. # the MQTT request topic subscription failed (common on P1S/A1).
  3301. _stored_map = _print_ams_mappings.get(expected_archive_id)
  3302. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  3303. if _stored_map or _stored_plate_id is not None:
  3304. try:
  3305. from backend.app.services.usage_tracker import _active_sessions
  3306. _ut_session = _active_sessions.get(printer_id)
  3307. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  3308. _ut_session.ams_mapping = _stored_map
  3309. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  3310. # plate_id injection covers direct-Print of plate N of a multi-plate
  3311. # 3MF — queue prints already capture it via the on_print_start queue
  3312. # lookup, but direct-Print never goes through the queue (#1697).
  3313. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  3314. _ut_session.plate_id = _stored_plate_id
  3315. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  3316. except Exception:
  3317. pass
  3318. # Set up energy tracking (#941: persist start on archive row)
  3319. await _record_energy_start(archive, printer_id, db, context="expected-print")
  3320. await ws_manager.send_archive_updated(
  3321. {
  3322. "id": archive.id,
  3323. "status": "printing",
  3324. }
  3325. )
  3326. # Send notification with archive data (reprint/scheduled)
  3327. if not notification_sent:
  3328. # Use archive's created_by_id; fall back to the creator registered via
  3329. # register_expected_print (handles library-file-based queue items where
  3330. # the freshly-created archive has no created_by_id yet).
  3331. # Pop ALL matching keys so no stale entries remain in the dict.
  3332. fallback_creator = None
  3333. for key in expected_keys:
  3334. popped = _expected_print_creators.pop(key, None)
  3335. if fallback_creator is None:
  3336. fallback_creator = popped
  3337. archive_data = {
  3338. "print_time_seconds": archive.print_time_seconds,
  3339. "created_by_id": archive.created_by_id or fallback_creator,
  3340. }
  3341. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3342. # Extract printable objects from the archived 3MF file
  3343. _load_objects_from_archive(archive, printer_id, logger)
  3344. # Store Spoolman tracking data for per-filament usage reporting
  3345. try:
  3346. await _store_spoolman_print_data(
  3347. printer_id,
  3348. archive.id,
  3349. archive.file_path,
  3350. db,
  3351. printer_manager,
  3352. ams_mapping=_get_start_ams_mapping(data, archive.id),
  3353. plate_id=_get_start_plate_id(archive.id),
  3354. )
  3355. except Exception as e:
  3356. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  3357. # Capture timelapse file baseline for snapshot-diff on completion
  3358. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  3359. # hit this branch — without the baseline the completion-time scan
  3360. # falls into its "take baseline now" fallback, which snapshots
  3361. # AFTER the new MP4 already exists and never matches a diff
  3362. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  3363. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  3364. return # Skip creating a new archive
  3365. # Check if there's already a "printing" archive for this printer/file
  3366. # This prevents duplicates when backend restarts during an active print
  3367. from backend.app.models.archive import PrintArchive
  3368. existing_archive: PrintArchive | None = None
  3369. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  3370. # across a backend restart for the same print, so this is the most
  3371. # reliable way to reattach. We also accept a previously stale-cancelled
  3372. # archive here so users upgrading mid-print get revived when the row
  3373. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  3374. if subtask_id:
  3375. by_id = await db.execute(
  3376. select(PrintArchive)
  3377. .where(PrintArchive.printer_id == printer_id)
  3378. .where(PrintArchive.subtask_id == subtask_id)
  3379. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  3380. .order_by(PrintArchive.created_at.desc())
  3381. .limit(1)
  3382. )
  3383. candidate = by_id.scalar_one_or_none()
  3384. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  3385. existing_archive = candidate
  3386. # Fallback match: name-based lookup. Kept as-is for prints whose
  3387. # subtask_id is missing ("0" / local / non-cloud prints).
  3388. if existing_archive is None:
  3389. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  3390. existing = await db.execute(
  3391. select(PrintArchive)
  3392. .where(PrintArchive.printer_id == printer_id)
  3393. .where(PrintArchive.status == "printing")
  3394. .where(
  3395. or_(
  3396. PrintArchive.print_name == check_name,
  3397. PrintArchive.filename.in_(
  3398. [
  3399. f"{check_name}.3mf",
  3400. f"{check_name}.gcode.3mf",
  3401. ]
  3402. ),
  3403. )
  3404. )
  3405. .order_by(PrintArchive.created_at.desc())
  3406. .limit(1)
  3407. )
  3408. existing_archive = existing.scalar_one_or_none()
  3409. if existing_archive:
  3410. # subtask_id match → always resume, regardless of age. Same print,
  3411. # just a backend restart. Revive if it was previously stale-cancelled.
  3412. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  3413. if subtask_match:
  3414. if existing_archive.status == "cancelled":
  3415. logger.warning(
  3416. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  3417. existing_archive.id,
  3418. subtask_id,
  3419. )
  3420. existing_archive.status = "printing"
  3421. existing_archive.failure_reason = None
  3422. await db.commit()
  3423. else:
  3424. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  3425. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3426. if existing_archive.energy_start_kwh is None:
  3427. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  3428. if not notification_sent:
  3429. archive_data = {
  3430. "print_time_seconds": existing_archive.print_time_seconds,
  3431. "created_by_id": existing_archive.created_by_id,
  3432. }
  3433. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3434. _load_objects_from_archive(existing_archive, printer_id, logger)
  3435. return
  3436. # Name-match only (no subtask_id to anchor on): decide resume vs.
  3437. # stale from the printer's *current* progress, not wall-clock age.
  3438. # A genuinely long print used to trip a blind 4h cutoff and have its
  3439. # live archive cancelled + duplicated on every backend restart
  3440. # (#1485). If the printer reports real progress, this name-matched
  3441. # 'printing' archive IS that ongoing print — resume it whatever its
  3442. # age. Only treat it as a stale leftover when the printer clearly
  3443. # shows a different, freshly-started print: near-0% progress on an
  3444. # archive far too old to still be at 0%. Unknown progress (printer
  3445. # not connected) never cancels — resuming is the safe default.
  3446. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  3447. live_status = printer_manager.get_status(printer_id)
  3448. live_progress = getattr(live_status, "progress", None) if live_status else None
  3449. looks_stale = (
  3450. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  3451. )
  3452. if looks_stale:
  3453. logger.warning(
  3454. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  3455. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  3456. )
  3457. existing_archive.status = "cancelled"
  3458. # Canonical key, not a sentence (issue #2974). "No status update
  3459. # received" is what both stale paths actually observed; which of
  3460. # the two it was is already carried by ``status`` -- cancelled
  3461. # here, the reconciled outcome at the reconnect site -- so one
  3462. # key loses no information and gives the Statistics breakdown a
  3463. # single bucket instead of two untranslatable prose strings.
  3464. existing_archive.failure_reason = "noStatusUpdate"
  3465. await db.commit()
  3466. # Fall through to create new archive (don't return)
  3467. else:
  3468. logger.info(
  3469. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  3470. )
  3471. # Track this as the active print
  3472. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  3473. # Attach subtask_id retroactively so future restarts can resume.
  3474. # Compare for inequality (not "is empty") to also pick up reprint
  3475. # dispatches that mint a fresh id — see #1807 for the bogus
  3476. # "Print Stopped" the strict-empty guard caused on reconnect.
  3477. if subtask_id and existing_archive.subtask_id != subtask_id:
  3478. existing_archive.subtask_id = subtask_id
  3479. await db.commit()
  3480. # Also set up energy tracking if not already tracked (#941: persisted column)
  3481. if existing_archive.energy_start_kwh is None:
  3482. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  3483. # Send notification with archive data (existing archive)
  3484. if not notification_sent:
  3485. archive_data = {
  3486. "print_time_seconds": existing_archive.print_time_seconds,
  3487. "created_by_id": existing_archive.created_by_id,
  3488. }
  3489. await _send_print_start_notification(printer_id, data, archive_data, logger)
  3490. # Extract printable objects from the archived 3MF file
  3491. _load_objects_from_archive(existing_archive, printer_id, logger)
  3492. return
  3493. # Build list of possible 3MF filenames to try
  3494. possible_names = []
  3495. # Bambu printers typically store files as "Name.gcode.3mf"
  3496. # The subtask_name is usually the best source for the filename
  3497. if subtask_name:
  3498. # Try common Bambu naming patterns
  3499. possible_names.append(f"{subtask_name}.gcode.3mf")
  3500. possible_names.append(f"{subtask_name}.3mf")
  3501. # Try original filename with .3mf extension
  3502. if filename:
  3503. # Extract just the filename part, not the full path
  3504. fname = filename.split("/")[-1] if "/" in filename else filename
  3505. if fname.endswith(".3mf"):
  3506. possible_names.append(fname)
  3507. elif fname.endswith(".gcode"):
  3508. base = fname.rsplit(".", 1)[0]
  3509. possible_names.append(f"{base}.gcode.3mf")
  3510. possible_names.append(f"{base}.3mf")
  3511. else:
  3512. possible_names.append(f"{fname}.gcode.3mf")
  3513. possible_names.append(f"{fname}.3mf")
  3514. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3515. space_variants = []
  3516. for name in possible_names:
  3517. if " " in name:
  3518. space_variants.append(name.replace(" ", "_"))
  3519. possible_names.extend(space_variants)
  3520. # Remove duplicates while preserving order
  3521. seen = set()
  3522. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  3523. logger.info("Trying filenames: %s", possible_names)
  3524. # Release the pooled DB connection before the 3MF FTP download. Reaching
  3525. # here means none of the expected-/existing-archive write branches ran
  3526. # (they all return earlier) — only SELECTs have executed on this path, so
  3527. # this commit persists nothing; it ends the read transaction so the
  3528. # connection returns to the pool during the download. That download tries
  3529. # up to five remote paths per candidate filename with retry/backoff and
  3530. # can run for minutes under FTP contention; holding the session across it
  3531. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  3532. # work runs during the download — the new-archive writes below re-acquire
  3533. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  3534. await db.commit()
  3535. # Try to find and download the 3MF file
  3536. temp_path = None
  3537. downloaded_filename = None
  3538. # Cache check: cover endpoint may have already pulled this 3MF during
  3539. # the print (frontend opens the card and shows the thumbnail) — reuse
  3540. # that file instead of re-downloading 36MB over the same FTP link that
  3541. # just served it (#972). The cache keys on a normalized filename so
  3542. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  3543. for try_filename in possible_names:
  3544. if not try_filename.endswith(".3mf"):
  3545. continue
  3546. cached = get_cached_3mf(printer_id, try_filename)
  3547. if cached:
  3548. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  3549. temp_path = cached
  3550. downloaded_filename = try_filename
  3551. break
  3552. # Does this printer keep the sliced file somewhere FTPS can reach? On
  3553. # H2-series and P2S the answer is routinely no — the file stays on
  3554. # internal eMMC and port 990 only ever serves external storage — and
  3555. # then the whole sweep below (six filenames x five directories x four
  3556. # retries, then the directory walk) is ~110 connections that cannot
  3557. # succeed. Skip it and say why (#2780).
  3558. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  3559. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  3560. # running rather than because the file is somewhere unreachable. The
  3561. # distinction is the whole of #2957: one is permanent, the other clears
  3562. # in minutes with the file still sitting on the printer.
  3563. blocked_by_ftps_cooloff = False
  3564. # Get FTP retry settings
  3565. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3566. # ...but "the printer put it on eMMC" is where it went, not whether we
  3567. # can read it. An H2D with a card in mirrors the job to /cache and
  3568. # serves it happily, and skipping on the URL alone cost that reporter
  3569. # every archive for two days (#2856). So ask the printer instead of
  3570. # guessing: the dispatch named the exact file, which is one connection
  3571. # walking five paths rather than the sweep's ~110. Only when the probe
  3572. # comes back empty does the verdict's reason stand.
  3573. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  3574. if ftps_handshake_blocked(printer.ip_address):
  3575. # Deliberately NOT recorded as a cool-off give-up. This branch
  3576. # only runs on an unreachable verdict, and that verdict is the
  3577. # honest, permanent reason the archive is empty — the probe was
  3578. # a long shot on top of it. Blaming the cool-off here would
  3579. # schedule a retry for a file sitting on internal eMMC, which is
  3580. # the sweep #2780 removed (#2957).
  3581. logger.debug(
  3582. "Not probing for %s on printer %s: its file service is not answering over TLS",
  3583. storage.probe_filename,
  3584. printer_id,
  3585. )
  3586. else:
  3587. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  3588. probe_path.parent.mkdir(parents=True, exist_ok=True)
  3589. try:
  3590. probe_hit = await download_file_try_paths_async(
  3591. printer.ip_address,
  3592. printer.access_code,
  3593. ftp_probe_paths(storage.probe_filename),
  3594. probe_path,
  3595. socket_timeout=ftp_timeout,
  3596. printer_model=printer.model,
  3597. )
  3598. except Exception as e:
  3599. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  3600. probe_hit = False
  3601. if probe_hit:
  3602. downloaded_filename = storage.probe_filename
  3603. temp_path = probe_path
  3604. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  3605. # Naming the path, not just the file: a printer that keeps
  3606. # uploads around for weeks can serve a same-named copy of an
  3607. # earlier slice, and without the directory in the log that
  3608. # mismatch is invisible rather than merely rare (#1820).
  3609. logger.info(
  3610. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  3611. downloaded_filename,
  3612. probe_hit,
  3613. printer_id,
  3614. storage.reason,
  3615. )
  3616. if not storage.reachable and not downloaded_filename:
  3617. # Same opening words whether or not a probe ran, because that is
  3618. # the phrase support asks people to grep for — only the tail says
  3619. # which of the two happened.
  3620. logger.info(
  3621. "Skipping the 3MF lookup for printer %s: %s — %s",
  3622. printer_id,
  3623. storage.reason,
  3624. "no copy of it on external storage either"
  3625. if storage.probe_filename
  3626. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  3627. )
  3628. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  3629. if not try_filename.endswith(".3mf"):
  3630. continue
  3631. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  3632. # printers, so try it first — deferring it to last cost #972's reporter
  3633. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  3634. # landing on the path that actually had the file.
  3635. remote_paths = [
  3636. f"/{try_filename}",
  3637. f"/cache/{try_filename}",
  3638. f"/model/{try_filename}",
  3639. f"/data/{try_filename}",
  3640. f"/data/Metadata/{try_filename}",
  3641. ]
  3642. temp_path = app_settings.archive_dir / "temp" / try_filename
  3643. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3644. for remote_path in remote_paths:
  3645. if ftps_handshake_blocked(printer.ip_address):
  3646. # The printer's FTPS service is not completing a TLS
  3647. # handshake, so it has no path we could reach — walking the
  3648. # remaining candidates only re-runs the same failure
  3649. # (#2780). Fall through to the no-3MF archive now.
  3650. #
  3651. # Remember *why*, though. This is the one give-up that is
  3652. # temporary: the cool-off clears in minutes and the file was
  3653. # on the printer the whole time. The fallback archive is
  3654. # stamped with it so a retry can be scheduled, and so the
  3655. # Archives banner stops blaming storage (#2957).
  3656. blocked_by_ftps_cooloff = True
  3657. logger.warning(
  3658. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  3659. printer_id,
  3660. )
  3661. break
  3662. logger.debug("Trying FTP download: %s", remote_path)
  3663. try:
  3664. if ftp_retry_enabled:
  3665. downloaded = await with_ftp_retry(
  3666. download_file_async,
  3667. printer.ip_address,
  3668. printer.access_code,
  3669. remote_path,
  3670. temp_path,
  3671. timeout=ftp_timeout,
  3672. socket_timeout=ftp_timeout,
  3673. printer_model=printer.model,
  3674. max_retries=ftp_retry_count,
  3675. retry_delay=ftp_retry_delay,
  3676. operation_name=f"Download 3MF from {remote_path}",
  3677. cooloff_ip=printer.ip_address,
  3678. non_retry_exceptions=(FileNotOnPrinterError,),
  3679. )
  3680. else:
  3681. downloaded = await download_file_async(
  3682. printer.ip_address,
  3683. printer.access_code,
  3684. remote_path,
  3685. temp_path,
  3686. timeout=ftp_timeout,
  3687. socket_timeout=ftp_timeout,
  3688. printer_model=printer.model,
  3689. )
  3690. if downloaded:
  3691. downloaded_filename = try_filename
  3692. logger.info("Downloaded: %s", remote_path)
  3693. # Populate shared cache so the cover endpoint (if it
  3694. # runs next) doesn't refetch the same 36MB over FTP.
  3695. cache_3mf_download(printer_id, try_filename, temp_path)
  3696. break
  3697. except FileNotOnPrinterError:
  3698. # 550 — file isn't at this path. Advance to next candidate
  3699. # without burning the retry budget.
  3700. logger.debug("3MF not at %s (550), trying next path", remote_path)
  3701. except Exception as e:
  3702. logger.debug("FTP download failed for %s: %s", remote_path, e)
  3703. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  3704. break
  3705. # If still not found, try listing directories to find matching file
  3706. # Different printer models use different directory structures. Skipped
  3707. # when the printer's FTPS handshake is failing — the directory walk is
  3708. # five more connections that cannot get further than the download did.
  3709. if (
  3710. not downloaded_filename
  3711. and storage.reachable
  3712. and (filename or subtask_name)
  3713. and not ftps_handshake_blocked(printer.ip_address)
  3714. ):
  3715. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  3716. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  3717. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  3718. for search_dir in search_dirs:
  3719. if downloaded_filename:
  3720. break
  3721. try:
  3722. dir_files = await list_files_async(
  3723. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  3724. )
  3725. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  3726. if threemf_files:
  3727. logger.info(
  3728. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  3729. )
  3730. for f in dir_files:
  3731. if f.get("is_directory"):
  3732. continue
  3733. fname = f.get("name", "")
  3734. # Normalize both for comparison (spaces and underscores are equivalent)
  3735. fname_normalized = fname.lower().replace(" ", "_")
  3736. search_normalized = search_term.replace(" ", "_")
  3737. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  3738. logger.info("Found matching file in %s: %s", search_dir, fname)
  3739. temp_path = app_settings.archive_dir / "temp" / fname
  3740. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3741. remote_full_path = posixpath.join(search_dir, fname)
  3742. if ftp_retry_enabled:
  3743. downloaded = await with_ftp_retry(
  3744. download_file_async,
  3745. printer.ip_address,
  3746. printer.access_code,
  3747. remote_full_path,
  3748. temp_path,
  3749. timeout=ftp_timeout,
  3750. socket_timeout=ftp_timeout,
  3751. printer_model=printer.model,
  3752. max_retries=ftp_retry_count,
  3753. retry_delay=ftp_retry_delay,
  3754. operation_name=f"Download 3MF from {remote_full_path}",
  3755. cooloff_ip=printer.ip_address,
  3756. )
  3757. else:
  3758. downloaded = await download_file_async(
  3759. printer.ip_address,
  3760. printer.access_code,
  3761. remote_full_path,
  3762. temp_path,
  3763. timeout=ftp_timeout,
  3764. socket_timeout=ftp_timeout,
  3765. printer_model=printer.model,
  3766. )
  3767. if downloaded:
  3768. downloaded_filename = fname
  3769. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  3770. cache_3mf_download(printer_id, fname, temp_path)
  3771. break
  3772. except Exception as e:
  3773. logger.debug("Failed to list %s: %s", search_dir, e)
  3774. # Validate the downloaded 3MF actually matches the plate that's running
  3775. # (#1204): subtask_name lags across consecutive plates of the same model,
  3776. # so the first FTP candidate (built from subtask_name) can land on the
  3777. # previous plate's still-resident upload. Cross-check the slice_info
  3778. # plate index against the plate parsed from gcode_file (always fresh —
  3779. # it's the field whose change triggered this callback).
  3780. if downloaded_filename and temp_path:
  3781. expected_plate = parse_plate_id(filename)
  3782. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  3783. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  3784. logger.warning(
  3785. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  3786. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  3787. downloaded_filename,
  3788. actual_plate,
  3789. expected_plate,
  3790. subtask_name,
  3791. )
  3792. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  3793. retry_succeeded = False
  3794. if corrected_subtask and corrected_subtask != subtask_name:
  3795. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  3796. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  3797. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  3798. for remote_path in (
  3799. f"/{try_filename}",
  3800. f"/cache/{try_filename}",
  3801. f"/model/{try_filename}",
  3802. f"/data/{try_filename}",
  3803. f"/data/Metadata/{try_filename}",
  3804. ):
  3805. try:
  3806. if ftp_retry_enabled:
  3807. downloaded = await with_ftp_retry(
  3808. download_file_async,
  3809. printer.ip_address,
  3810. printer.access_code,
  3811. remote_path,
  3812. retry_temp_path,
  3813. timeout=ftp_timeout,
  3814. socket_timeout=ftp_timeout,
  3815. printer_model=printer.model,
  3816. max_retries=ftp_retry_count,
  3817. retry_delay=ftp_retry_delay,
  3818. operation_name=f"Re-download 3MF from {remote_path}",
  3819. cooloff_ip=printer.ip_address,
  3820. non_retry_exceptions=(FileNotOnPrinterError,),
  3821. )
  3822. else:
  3823. downloaded = await download_file_async(
  3824. printer.ip_address,
  3825. printer.access_code,
  3826. remote_path,
  3827. retry_temp_path,
  3828. timeout=ftp_timeout,
  3829. socket_timeout=ftp_timeout,
  3830. printer_model=printer.model,
  3831. )
  3832. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  3833. logger.info(
  3834. "[CALLBACK] Re-download succeeded with corrected name %s "
  3835. "(plate %s) — replacing wrong file",
  3836. try_filename,
  3837. expected_plate,
  3838. )
  3839. try:
  3840. temp_path.unlink(missing_ok=True)
  3841. except OSError:
  3842. pass
  3843. temp_path = retry_temp_path
  3844. downloaded_filename = try_filename
  3845. subtask_name = corrected_subtask
  3846. cache_3mf_download(printer_id, try_filename, temp_path)
  3847. retry_succeeded = True
  3848. break
  3849. elif downloaded:
  3850. # Wrong plate again — discard and keep trying
  3851. try:
  3852. retry_temp_path.unlink(missing_ok=True)
  3853. except OSError:
  3854. pass
  3855. except FileNotOnPrinterError:
  3856. continue
  3857. except Exception as e:
  3858. logger.debug("Re-download failed for %s: %s", remote_path, e)
  3859. if retry_succeeded:
  3860. break
  3861. # If the retry didn't find a matching file, drop the wrong 3MF
  3862. # so the no-3MF fallback below creates an archive whose name
  3863. # at least reflects the right plate.
  3864. if not retry_succeeded:
  3865. logger.warning(
  3866. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  3867. expected_plate,
  3868. )
  3869. try:
  3870. temp_path.unlink(missing_ok=True)
  3871. except OSError:
  3872. pass
  3873. temp_path = None
  3874. downloaded_filename = None
  3875. # Override the stale subtask_name so the fallback archive's
  3876. # print_name reflects the correct plate. Prefer the swapped
  3877. # name when we have one; otherwise let filename win.
  3878. if corrected_subtask:
  3879. subtask_name = corrected_subtask
  3880. else:
  3881. subtask_name = ""
  3882. if not downloaded_filename or not temp_path:
  3883. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  3884. # Create a fallback archive without 3MF data so the print is still tracked
  3885. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  3886. try:
  3887. from backend.app.models.archive import PrintArchive
  3888. # Derive print name from subtask_name or filename
  3889. print_name = subtask_name or filename
  3890. if print_name:
  3891. # Clean up the name (remove extensions, path parts)
  3892. print_name = print_name.split("/")[-1]
  3893. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  3894. else:
  3895. print_name = "Unknown Print"
  3896. # Recover estimated print time from MQTT (best-effort for notifications)
  3897. fallback_print_time = None
  3898. mqtt_remaining = data.get("remaining_time")
  3899. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  3900. fallback_print_time = int(mqtt_remaining)
  3901. if fallback_print_time is None:
  3902. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  3903. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  3904. fallback_print_time = int(mc_remaining * 60)
  3905. # Best-effort filament metadata from MQTT — see
  3906. # _extract_filament_data_from_mqtt. Without this the fallback
  3907. # archive's filament fields stayed NULL even though the AMS
  3908. # state at print start was sitting right there in `data`.
  3909. # The slicer's ams_mapping (when present) narrows the result
  3910. # to slots actually used by the print (#1533).
  3911. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  3912. # Create minimal archive entry
  3913. fallback_archive = PrintArchive(
  3914. printer_id=printer_id,
  3915. filename=filename or f"{print_name}.3mf",
  3916. file_path="", # Empty - no 3MF file available
  3917. file_size=0,
  3918. print_name=print_name,
  3919. print_time_seconds=fallback_print_time,
  3920. status="printing",
  3921. started_at=datetime.now(timezone.utc),
  3922. subtask_id=subtask_id,
  3923. filament_type=mqtt_filament_meta.get("filament_type"),
  3924. filament_color=mqtt_filament_meta.get("filament_color"),
  3925. extra_data={
  3926. "no_3mf_available": True,
  3927. # Why the card is empty, when we know. The banner reads
  3928. # this to stop telling H2/P2 owners to switch on a
  3929. # setting that is already on and would not help (#2780).
  3930. # A cool-off outranks the storage verdict: the sweep was
  3931. # skipped at the transport, so the verdict never got to
  3932. # be tested, and reporting it would blame the SD card
  3933. # for a TLS handshake (#2957).
  3934. "no_3mf_reason": REASON_FTPS_COOLOFF if blocked_by_ftps_cooloff else storage.reason,
  3935. "original_subtask": subtask_name,
  3936. "_print_data": data,
  3937. },
  3938. )
  3939. db.add(fallback_archive)
  3940. await db.commit()
  3941. await db.refresh(fallback_archive)
  3942. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  3943. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  3944. # Track as active print
  3945. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  3946. if filename:
  3947. _active_prints[(printer_id, filename)] = fallback_archive.id
  3948. if subtask_name:
  3949. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  3950. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  3951. # Record starting energy if smart plug available (#941: persisted column)
  3952. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  3953. # Send WebSocket notification
  3954. await ws_manager.send_archive_created(
  3955. {
  3956. "id": fallback_archive.id,
  3957. "printer_id": fallback_archive.printer_id,
  3958. "filename": fallback_archive.filename,
  3959. "print_name": fallback_archive.print_name,
  3960. "status": fallback_archive.status,
  3961. }
  3962. )
  3963. # MQTT relay - publish archive created
  3964. try:
  3965. await mqtt_relay.on_archive_created(
  3966. archive_id=fallback_archive.id,
  3967. print_name=fallback_archive.print_name,
  3968. printer_name=printer.name,
  3969. status=fallback_archive.status,
  3970. )
  3971. except Exception:
  3972. pass # Don't fail if MQTT fails
  3973. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  3974. try:
  3975. await _store_spoolman_print_data(
  3976. printer_id,
  3977. fallback_archive.id,
  3978. fallback_archive.file_path,
  3979. db,
  3980. printer_manager,
  3981. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  3982. plate_id=_get_start_plate_id(fallback_archive.id),
  3983. )
  3984. except Exception as e:
  3985. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  3986. # A cool-off give-up is temporary and the file is on the
  3987. # printer — come back for it once the handshake block clears
  3988. # (#2957). Deliberately not scheduled for a storage verdict:
  3989. # a file on internal eMMC will not appear at any FTPS path
  3990. # however long we wait, and retrying it is exactly the sweep
  3991. # #2780 removed.
  3992. if blocked_by_ftps_cooloff and possible_names:
  3993. # `possible_names`, not the raw MQTT strings: it is the exact
  3994. # list this flow just tried, already stripped of any path
  3995. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  3996. # some firmware) and deduped.
  3997. _schedule_fallback_3mf_retry(
  3998. printer_id=printer_id,
  3999. archive_id=fallback_archive.id,
  4000. filenames=list(possible_names),
  4001. )
  4002. # Send notification without archive data (file not found)
  4003. if not notification_sent:
  4004. await _send_print_start_notification(printer_id, data, logger=logger)
  4005. # The same baseline the other two on_print_start branches take
  4006. # (#2704), and last for the same reason they are: it lists the
  4007. # printer's timelapse directory, so a slow card must not delay
  4008. # the _active_prints registration, the energy reading, the
  4009. # archive-created event or the start notification above it.
  4010. #
  4011. # This branch never took one, so every no-3MF archive reached
  4012. # completion with no baseline in memory and none on the row, and
  4013. # the completion scan fell into its "snapshot now" fallback --
  4014. # which runs after the printer has written the video, so the new
  4015. # file landed inside the baseline and no diff ever matched
  4016. # (#2957 follow-up).
  4017. #
  4018. # Skipped when the FTPS cool-off is what produced this fallback:
  4019. # the listing needs the same connection that just failed, so it
  4020. # could only record that the card was unreadable. The scan
  4021. # handles that case by refusing to choose between candidates.
  4022. if not blocked_by_ftps_cooloff:
  4023. await _capture_timelapse_baseline_at_start(
  4024. printer, printer_id, logger, archive_id=fallback_archive.id
  4025. )
  4026. return
  4027. except Exception as e:
  4028. logger.error("Failed to create fallback archive: %s", e)
  4029. # Send notification without archive data (file not found)
  4030. if not notification_sent:
  4031. await _send_print_start_notification(printer_id, data, logger=logger)
  4032. return
  4033. try:
  4034. # Archive the file with status "printing"
  4035. service = ArchiveService(db)
  4036. archive = await service.archive_print(
  4037. printer_id=printer_id,
  4038. source_file=temp_path,
  4039. print_data={**data, "status": "printing"},
  4040. subtask_id=subtask_id,
  4041. )
  4042. if archive:
  4043. # Track this active print (use both original filename and downloaded filename)
  4044. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4045. if filename and filename != downloaded_filename:
  4046. _active_prints[(printer_id, filename)] = archive.id
  4047. if subtask_name:
  4048. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4049. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4050. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4051. # Record starting energy from smart plug if available (#941: persisted column)
  4052. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4053. await ws_manager.send_archive_created(
  4054. {
  4055. "id": archive.id,
  4056. "printer_id": archive.printer_id,
  4057. "filename": archive.filename,
  4058. "print_name": archive.print_name,
  4059. "status": archive.status,
  4060. }
  4061. )
  4062. # MQTT relay - publish archive created
  4063. try:
  4064. await mqtt_relay.on_archive_created(
  4065. archive_id=archive.id,
  4066. print_name=archive.print_name,
  4067. printer_name=printer.name,
  4068. status=archive.status,
  4069. )
  4070. except Exception:
  4071. pass # Don't fail if MQTT fails
  4072. # Send notification with archive data (new archive created)
  4073. if not notification_sent:
  4074. archive_data = {
  4075. "print_time_seconds": archive.print_time_seconds,
  4076. "created_by_id": archive.created_by_id,
  4077. }
  4078. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4079. # Extract printable objects for skip object functionality
  4080. try:
  4081. from backend.app.services.archive import extract_printable_objects_from_3mf
  4082. client = printer_manager.get_client(printer_id)
  4083. if client:
  4084. with open(temp_path, "rb") as f:
  4085. threemf_data = f.read()
  4086. # Extract with positions for UI overlay, scoped to the
  4087. # plate that is printing — an all-plates 3MF carries
  4088. # every plate's objects (#2522).
  4089. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4090. threemf_data,
  4091. plate_number=resolve_plate_id(client.state),
  4092. include_positions=True,
  4093. )
  4094. if printable_objects:
  4095. # Store objects in printer state
  4096. client.state.printable_objects = printable_objects
  4097. client.state.printable_objects_bbox_all = bbox_all
  4098. client.state.skipped_objects = [] # Reset skipped objects for new print
  4099. logger.info(
  4100. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4101. )
  4102. except Exception as e:
  4103. logger.debug("Failed to extract printable objects: %s", e)
  4104. # Store Spoolman tracking data for per-filament usage reporting
  4105. try:
  4106. await _store_spoolman_print_data(
  4107. printer_id,
  4108. archive.id,
  4109. archive.file_path,
  4110. db,
  4111. printer_manager,
  4112. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4113. plate_id=_get_start_plate_id(archive.id),
  4114. )
  4115. except Exception as e:
  4116. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4117. # Capture timelapse file baseline for snapshot-diff on completion
  4118. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4119. finally:
  4120. # Keep temp_path around until print completes so the cover endpoint
  4121. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4122. # the file. If the cache entry was evicted early (file vanished),
  4123. # clean up any stragglers here to avoid leaking disk on retries.
  4124. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4125. if temp_path and temp_path.exists() and cached_now != temp_path:
  4126. temp_path.unlink()
  4127. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4128. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4129. # tests can shrink them without waiting out real delays.
  4130. #
  4131. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4132. # looking. Across 247 support bundles the attempt that found the video was #1
  4133. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4134. # decaying one, which is the signature of a budget that expires while files are
  4135. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4136. # prints make big videos and the printer writes them after the print ends, so
  4137. # the poll now runs for minutes and costs one FTP LIST per round.
  4138. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4139. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4140. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4141. def _timelapse_scan_max_attempts() -> int:
  4142. """Round cap for the poll, derived from the wall-clock budget.
  4143. The deadline alone is not a sufficient bound: it assumes each round really
  4144. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4145. and an FTP list that fails immediately would otherwise spin against the
  4146. printer at full speed for the whole window. Whichever bound is reached
  4147. first ends the poll.
  4148. """
  4149. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4150. # A zero interval makes the wall-clock budget meaningless; fall back to
  4151. # the round count the production interval would have given.
  4152. return 32
  4153. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4154. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4155. """Video filenames already attached to some other archive of this printer.
  4156. Used to disambiguate when more than one file is new since the baseline —
  4157. which happens when a previous print's video landed after this print's
  4158. baseline was taken. Ordering the candidates would be the obvious fix and is
  4159. the wrong one: it can only be done on mtime or on the filename timestamp,
  4160. both of which come from the printer's own clock, and a LAN-only printer
  4161. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4162. ``attach_timelapse`` saves the video into the archive directory under the
  4163. printer's original filename, and the later MP4 conversion keeps the stem,
  4164. so the stem of ``timelapse_path`` recovers what was claimed.
  4165. """
  4166. from backend.app.models.archive import PrintArchive
  4167. rows = await db.execute(
  4168. select(PrintArchive.timelapse_path).where(
  4169. PrintArchive.printer_id == printer_id,
  4170. PrintArchive.id != exclude_archive_id,
  4171. PrintArchive.timelapse_path.is_not(None),
  4172. )
  4173. )
  4174. return {Path(p).stem for p in rows.scalars().all() if p}
  4175. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4176. """Whether an *empty* timelapse listing for *printer* can be believed.
  4177. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4178. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4179. from one holding no videos. Everywhere that only wants to know "is there a
  4180. video yet" the difference does not matter — both mean "not yet, retry".
  4181. It matters where an empty listing is recorded as a *baseline*. Recording
  4182. "the card held nothing" for a card that was never read means every video on
  4183. it counts as new once the cool-off expires, and the completion scan then
  4184. attaches a stale video to this print and deletes it from the printer
  4185. (#2957 follow-up). Those two callers ask this first.
  4186. """
  4187. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  4188. ip_address = getattr(printer, "ip_address", None)
  4189. if not ip_address:
  4190. return True
  4191. return not ftps_handshake_blocked(ip_address)
  4192. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4193. """List video files from printer's timelapse directory.
  4194. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4195. Returns (video_files, found_path) where video_files is a list of file dicts
  4196. and found_path is the directory where they were found, or ([], None).
  4197. An empty return does not distinguish "no videos" from "could not read the
  4198. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  4199. baseline callers consult before believing one.
  4200. """
  4201. from backend.app.services.bambu_ftp import list_files_async
  4202. logger = logging.getLogger(__name__)
  4203. # No card in the slot means no /timelapse to walk — four connections that
  4204. # can only fail, on a path whose failures are swallowed and so would go on
  4205. # costing time silently forever (#2780).
  4206. #
  4207. # ``getattr`` rather than ``printer.id``: every dereference below happens
  4208. # inside the loop's own try/except, so a caller that passed something
  4209. # unexpected used to get an empty listing rather than an exception. Keep
  4210. # that, instead of making this gate the first thing that can raise here.
  4211. printer_id = getattr(printer, "id", None)
  4212. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  4213. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  4214. return [], None
  4215. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  4216. try:
  4217. found_files = await list_files_async(
  4218. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  4219. )
  4220. if found_files:
  4221. video_files = [
  4222. f
  4223. for f in found_files
  4224. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  4225. ]
  4226. if video_files:
  4227. return video_files, timelapse_path
  4228. except Exception as e:
  4229. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  4230. continue
  4231. return [], None
  4232. async def _capture_timelapse_baseline_at_start(
  4233. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  4234. ) -> None:
  4235. """Snapshot the printer's timelapse directory at print start so the
  4236. completion-time scan can pick the new file by set-difference.
  4237. Must be called from every on_print_start path that proceeds to a real
  4238. print — both the new-archive branch and the expected-archive branch (which
  4239. queue / VP-dispatched prints take). Without a baseline,
  4240. _scan_for_timelapse_with_retries falls into its "take baseline now"
  4241. fallback that runs AFTER the new MP4 has already landed on the SD card,
  4242. so the new file ends up in the "baseline" set and no diff ever matches.
  4243. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  4244. unreliable — the snapshot-diff approach sidesteps that entirely.
  4245. When ``archive_id`` is known the baseline is also written to the archive
  4246. row, so it survives a restart and the manual "Scan for Timelapse" button
  4247. can run the same diff instead of falling back to clock-based matching
  4248. (#2704). Only baselines taken at print start are persisted — one taken at
  4249. completion already contains the new video and would poison a later scan.
  4250. """
  4251. names: set[str] | None = None
  4252. try:
  4253. if not _timelapse_listing_is_trustworthy(printer):
  4254. # Recorded anyway, deliberately. An empty baseline taken off a card
  4255. # we could not read is not authoritative, but it is still the right
  4256. # *default*: Bambuddy deletes each video from the printer once it is
  4257. # attached, so the usual card holds exactly one video at completion
  4258. # and an empty baseline resolves it correctly. Persisting NULL
  4259. # instead would send completion to take its own snapshot, by which
  4260. # point this print's video is on the card and would be swallowed by
  4261. # it. The ambiguity is handled where it actually bites — see
  4262. # ``require_unambiguous`` in the scan (#2957 follow-up).
  4263. logger.warning(
  4264. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  4265. "handshake cool-off, so the card could not be read — treating it as empty",
  4266. printer_id,
  4267. )
  4268. baseline_files, _ = await _list_timelapse_videos(printer)
  4269. names = {f.get("name", "") for f in baseline_files}
  4270. _timelapse_baselines[printer_id] = names
  4271. logger.info(
  4272. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  4273. len(names),
  4274. printer_id,
  4275. )
  4276. except Exception as e:
  4277. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  4278. if archive_id is None:
  4279. return
  4280. try:
  4281. async with async_session() as db:
  4282. from backend.app.models.archive import PrintArchive
  4283. archive = await db.get(PrintArchive, archive_id)
  4284. if archive is not None:
  4285. # Written even when the listing failed, and then as NULL. A
  4286. # reprint reuses the archive row, so leaving the previous run's
  4287. # baseline in place would have the scan diff this print against
  4288. # the state of the printer before the *last* one — and a stale
  4289. # baseline reads as authoritative, where NULL correctly falls
  4290. # back to a fresh snapshot.
  4291. archive.timelapse_baseline = sorted(names) if names is not None else None
  4292. await db.commit()
  4293. except Exception as e:
  4294. # In-memory baseline still covers the normal completion path.
  4295. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  4296. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  4297. """Poll the printer for this print's timelapse and attach it.
  4298. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  4299. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  4300. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  4301. (#2704). Comparing the current listing against the set of filenames that
  4302. existed when the print started needs no clock at all, because the printer
  4303. writes the video only once the print has ended.
  4304. Baseline precedence: the caller's in-memory set, then the one persisted on
  4305. the archive at print start, then a snapshot taken now. The last of those is
  4306. a poor substitute — by completion the new video may already be on the card,
  4307. in which case it lands in the "baseline" and no diff can ever match — but it
  4308. is all that is available for a print that began before Bambuddy started.
  4309. On success the video is deleted from the printer, which keeps ``/timelapse``
  4310. down to the unclaimed files and makes the next diff unambiguous.
  4311. """
  4312. logger = logging.getLogger(__name__)
  4313. # Cleared when the baseline had to be taken off a card we could not read, so
  4314. # the attach step refuses to choose between several candidates (#2957).
  4315. baseline_trusted = True
  4316. # --- Phase 1: establish the baseline -------------------------------------
  4317. try:
  4318. async with async_session() as db:
  4319. from backend.app.models.printer import Printer
  4320. service = ArchiveService(db)
  4321. archive = await service.get_archive(archive_id)
  4322. if not archive:
  4323. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  4324. return
  4325. if archive.timelapse_path:
  4326. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  4327. return
  4328. if not archive.printer_id:
  4329. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  4330. return
  4331. if baseline_names is not None:
  4332. logger.info(
  4333. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  4334. len(baseline_names),
  4335. archive_id,
  4336. )
  4337. elif archive.timelapse_baseline is not None:
  4338. # Persisted at print start — survives a restart mid-print.
  4339. baseline_names = set(archive.timelapse_baseline)
  4340. logger.info(
  4341. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  4342. len(baseline_names),
  4343. archive_id,
  4344. )
  4345. else:
  4346. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4347. printer = result.scalar_one_or_none()
  4348. if not printer:
  4349. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  4350. return
  4351. if not _timelapse_listing_is_trustworthy(printer):
  4352. # The card is unreadable at the one moment a baseline has to
  4353. # be taken, so the empty listing below means "we never
  4354. # looked", not "these are all new". Carry on with it anyway
  4355. # — the usual card holds exactly one video, which resolves
  4356. # correctly — but stop the poll from *choosing* between
  4357. # several, which is how a stale video got attached to this
  4358. # print and then deleted off the printer (#2957 follow-up).
  4359. baseline_trusted = False
  4360. logger.warning(
  4361. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  4362. "handshake cool-off. A single new video still resolves; several will not be "
  4363. "guessed between — use Scan for Timelapse to pick one by hand",
  4364. archive_id,
  4365. archive.printer_id,
  4366. )
  4367. baseline_files, _ = await _list_timelapse_videos(printer)
  4368. baseline_names = {f.get("name", "") for f in baseline_files}
  4369. logger.info(
  4370. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  4371. len(baseline_names),
  4372. archive_id,
  4373. )
  4374. except Exception as e:
  4375. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  4376. return
  4377. # --- Phase 2: poll for a file that was not there when the print began -----
  4378. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  4379. max_attempts = _timelapse_scan_max_attempts()
  4380. seen_names: set[str] = set()
  4381. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  4382. attempt = 0
  4383. while True:
  4384. await asyncio.sleep(delay)
  4385. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  4386. attempt += 1
  4387. try:
  4388. from backend.app.models.printer import Printer
  4389. # Read phase: fetch archive + printer in a short session and release
  4390. # the pooled connection BEFORE the FTP list/download below. Holding it
  4391. # across the FTP round-trips left one connection idle-in-transaction per
  4392. # in-flight scan (issue #2572).
  4393. async with async_session() as db:
  4394. service = ArchiveService(db)
  4395. archive = await service.get_archive(archive_id)
  4396. if not archive:
  4397. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  4398. return
  4399. if archive.timelapse_path:
  4400. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  4401. return
  4402. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  4403. printer = result.scalar_one_or_none()
  4404. if not printer:
  4405. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  4406. return
  4407. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  4408. # I/O phase (no DB connection held): FTP list + download.
  4409. video_files, found_path = await _list_timelapse_videos(printer)
  4410. # The poll can run for dozens of rounds, so only narrate a round
  4411. # that saw something change. Repeating the whole listing every 30 s
  4412. # would bury the one interesting line in the support bundle.
  4413. names_now = {f.get("name", "") for f in video_files}
  4414. changed = attempt == 1 or names_now != seen_names
  4415. seen_names = names_now
  4416. speak = logger.info if changed else logger.debug
  4417. if video_files:
  4418. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  4419. if changed:
  4420. for f in video_files[:5]:
  4421. logger.info("[TIMELAPSE] - %s", f.get("name"))
  4422. attached = await _attach_first_unclaimed_timelapse(
  4423. archive_id,
  4424. printer,
  4425. video_files,
  4426. baseline_names,
  4427. claimed,
  4428. attempt,
  4429. logger,
  4430. quiet=not changed,
  4431. require_unambiguous=not baseline_trusted,
  4432. )
  4433. if attached:
  4434. return
  4435. else:
  4436. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  4437. except Exception as e:
  4438. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  4439. if attempt >= max_attempts or time.monotonic() >= deadline:
  4440. break
  4441. # No name-match fallback: it compared the print name against the filename,
  4442. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  4443. # bundles it fired 159 times and matched zero times, so all it added was a
  4444. # misleading log line before giving up.
  4445. logger.warning(
  4446. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  4447. archive_id,
  4448. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  4449. )
  4450. async def _attach_first_unclaimed_timelapse(
  4451. archive_id: int,
  4452. printer,
  4453. video_files: list[dict],
  4454. baseline_names: set[str],
  4455. claimed: set[str],
  4456. attempt: int,
  4457. logger: logging.Logger,
  4458. *,
  4459. quiet: bool = False,
  4460. require_unambiguous: bool = False,
  4461. ) -> bool:
  4462. """Download and attach the one video that belongs to this print.
  4463. A candidate is any file absent from the print-start baseline. More than one
  4464. can qualify when a previous print's video landed late, after this print's
  4465. baseline was taken — those are filtered out by name, because they are
  4466. already attached to another archive. Sorting the candidates instead would
  4467. mean sorting on mtime or on the filename timestamp, both of which come from
  4468. the printer's unsynced clock.
  4469. Returns True once a video is attached. The printer's copy is deleted only
  4470. after the attach succeeds on bytes whose length matched the listing.
  4471. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  4472. already seen this exact listing — the poll runs for many rounds and only the
  4473. rounds where something changed are worth an INFO line.
  4474. """
  4475. from backend.app.services.bambu_ftp import (
  4476. delete_archived_timelapse,
  4477. download_file_bytes_async,
  4478. remote_file_settled,
  4479. )
  4480. speak = logger.debug if quiet else logger.info
  4481. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  4482. if not new_files:
  4483. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  4484. return False
  4485. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  4486. if not candidates:
  4487. speak(
  4488. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  4489. attempt,
  4490. len(new_files),
  4491. )
  4492. return False
  4493. if len(candidates) > 1:
  4494. if require_unambiguous:
  4495. # The baseline is not evidence -- it was taken off a card that could
  4496. # not be read -- so "new since the baseline" does not narrow these
  4497. # down at all. Taking the first would attach an arbitrary video to
  4498. # this print and then delete it from the printer.
  4499. logger.warning(
  4500. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  4501. "leaving all of them on the printer for manual selection",
  4502. attempt,
  4503. len(candidates),
  4504. ", ".join(str(f.get("name")) for f in candidates),
  4505. )
  4506. return False
  4507. logger.warning(
  4508. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  4509. "the rest stay on the printer for manual selection",
  4510. attempt,
  4511. len(candidates),
  4512. ", ".join(str(f.get("name")) for f in candidates),
  4513. )
  4514. target = candidates[0]
  4515. file_name = target.get("name")
  4516. remote_path = target.get("path") or f"/timelapse/{file_name}"
  4517. logger.info(
  4518. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  4519. attempt,
  4520. file_name,
  4521. archive_id,
  4522. )
  4523. # The listing always carries a size (`list_files` skips entries it can't
  4524. # parse), but read it explicitly: the delete below is destructive and must
  4525. # depend on a size we actually had, not on one we hoped was there.
  4526. expected_size = target.get("size")
  4527. timelapse_data = await download_file_bytes_async(
  4528. printer.ip_address,
  4529. printer.access_code,
  4530. remote_path,
  4531. printer_model=printer.model,
  4532. expected_size=expected_size,
  4533. )
  4534. if not timelapse_data:
  4535. # Short or failed transfer. The printer keeps its copy, so the next
  4536. # round can try again — which is exactly why the delete below is
  4537. # gated on a verified download.
  4538. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  4539. return False
  4540. # The length check above proves we got what the listing said, not that the
  4541. # printer had finished writing. A video still being written can be listed
  4542. # short, served short, and pass — so confirm it has stopped growing before
  4543. # committing to it and deleting the original (#2704).
  4544. if not await remote_file_settled(
  4545. printer.ip_address,
  4546. printer.access_code,
  4547. remote_path,
  4548. len(timelapse_data),
  4549. printer_model=printer.model,
  4550. ):
  4551. return False
  4552. # Write phase: attach in a fresh short-lived session.
  4553. async with async_session() as db:
  4554. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  4555. if not success:
  4556. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  4557. return False
  4558. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  4559. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  4560. await delete_archived_timelapse(
  4561. printer.ip_address,
  4562. printer.access_code,
  4563. remote_path,
  4564. verified=expected_size is not None,
  4565. printer_model=printer.model,
  4566. printer_name=printer.name,
  4567. )
  4568. return True
  4569. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  4570. # module-level so tests can monkeypatch them down to ~0 without timing out.
  4571. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  4572. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  4573. # How long the *background* upgrade keeps waiting after the notification has
  4574. # already gone out (#2704 follow-up). The short bound above exists so a slow
  4575. # printer can't hold up the print-complete notification; this one exists so the
  4576. # archive still ends up with the better frame afterwards.
  4577. #
  4578. # Measured across 261 attaches in the support bundles, the video lands a median
  4579. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  4580. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  4581. # was 546s. Every other model was inside 26s. The long budget is therefore
  4582. # almost entirely for P1-series users; on everything else the short wait already
  4583. # wins and this task never runs.
  4584. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  4585. async def _capture_finish_photo_from_timelapse(
  4586. archive_id: int,
  4587. archive_dir: Path,
  4588. timeout: float | None = None,
  4589. rotation: int = 0,
  4590. ) -> tuple[str | None, bool]:
  4591. """Wait for the per-print timelapse to land on the archive and extract its
  4592. last frame as the finish photo (#1397).
  4593. Bambu firmware stops timelapse recording after the toolhead parks but
  4594. before the bed-drop end-gcode runs, so the last frame frames the finished
  4595. print correctly. A live camera grab at gcode_state=FINISH captures the
  4596. bed already lowered.
  4597. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  4598. ``archive.timelapse_path`` when the file lands. This function polls for
  4599. that field.
  4600. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  4601. the wait ran out with no video on the archive yet — i.e. the video may
  4602. still be coming and a later attempt could succeed. It is False when the
  4603. video landed (whether or not extraction worked), because in that case
  4604. waiting longer changes nothing. The caller uses that to decide between
  4605. falling back permanently and scheduling a background upgrade.
  4606. ``rotation`` is the printer's camera_rotation, applied to the extracted
  4607. still (#2708) so this source agrees with every other finish-photo source.
  4608. The archived video itself is the printer's own file and is left alone —
  4609. rotating it would mean re-encoding it.
  4610. """
  4611. import uuid
  4612. from backend.app.models.archive import PrintArchive
  4613. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  4614. logger = logging.getLogger(__name__)
  4615. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  4616. deadline = asyncio.get_event_loop().time() + budget
  4617. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  4618. while True:
  4619. async with async_session() as db:
  4620. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  4621. archive = result.scalar_one_or_none()
  4622. timelapse_relpath = archive.timelapse_path if archive else None
  4623. if timelapse_relpath:
  4624. video_path = app_settings.base_dir / timelapse_relpath
  4625. if video_path.exists() and video_path.stat().st_size > 0:
  4626. photos_dir = archive_dir / "photos"
  4627. photos_dir.mkdir(parents=True, exist_ok=True)
  4628. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  4629. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  4630. output_path = photos_dir / filename
  4631. if await extract_video_last_frame(video_path, output_path):
  4632. await apply_camera_rotation_to_file(output_path, rotation, logger)
  4633. logger.info(
  4634. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  4635. video_path.name,
  4636. archive_id,
  4637. )
  4638. return filename, False
  4639. logger.warning(
  4640. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  4641. video_path.name,
  4642. archive_id,
  4643. )
  4644. return None, False
  4645. if asyncio.get_event_loop().time() >= deadline:
  4646. logger.info(
  4647. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  4648. archive_id,
  4649. budget,
  4650. )
  4651. return None, True
  4652. await asyncio.sleep(poll_interval)
  4653. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  4654. """Add the timelapse's last frame to an archive after the fact (#2704).
  4655. The print-complete notification waits only ~60s for the video, because
  4656. holding a notification for minutes is worse than sending it with a live
  4657. camera grab. On a P1-series printer the video often lands well after that,
  4658. so the archive used to be stuck with the live grab — which is taken at
  4659. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  4660. the worse photo of the two.
  4661. This keeps waiting in the background and, when the video arrives, extracts
  4662. the frame and puts it *first* in the archive's photo list, so opening the
  4663. gallery shows it. The live grab is deliberately kept: the notification that
  4664. already went out links to that exact file, and deleting it would leave a
  4665. broken image in Discord or Telegram.
  4666. """
  4667. logger = logging.getLogger(__name__)
  4668. filename, _ = await _capture_finish_photo_from_timelapse(
  4669. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  4670. )
  4671. if not filename:
  4672. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  4673. return
  4674. try:
  4675. async with async_session() as db:
  4676. from backend.app.models.archive import PrintArchive
  4677. archive = await db.get(PrintArchive, archive_id)
  4678. if archive is None:
  4679. return
  4680. photos = list(archive.photos or [])
  4681. if filename in photos:
  4682. return
  4683. # Front of the list: PhotoGalleryModal opens at index 0.
  4684. archive.photos = [filename, *photos]
  4685. await db.commit()
  4686. except Exception as e:
  4687. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  4688. return
  4689. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  4690. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  4691. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  4692. """Put the filament-attribution context back after a restart mid-print.
  4693. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  4694. both die with the process. The print keeps running, so at completion the
  4695. tracker would fall back to whatever the printer reports *now* — and AMS
  4696. filament backup makes "now" the substitute tray, charging the whole print
  4697. to the spool that only finished it.
  4698. The persisted row is only trusted when its print name still matches what
  4699. the printer says it is running: a row left behind by a completion we never
  4700. saw must not attach itself to the next print.
  4701. """
  4702. try:
  4703. from backend.app.api.routes.settings import get_setting
  4704. from backend.app.services.usage_tracker import (
  4705. clear_persisted_session,
  4706. get_persisted_print_name,
  4707. restore_session,
  4708. )
  4709. persisted_name = await get_persisted_print_name(db, printer_id)
  4710. current_name = (state.subtask_name or "").strip()
  4711. if persisted_name and current_name and persisted_name.strip() != current_name:
  4712. logger.info(
  4713. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  4714. printer_id,
  4715. persisted_name,
  4716. current_name,
  4717. )
  4718. await clear_persisted_session(db, printer_id)
  4719. # Fall through to seeding: the print on the printer is real, it just
  4720. # isn't the one the row described.
  4721. persisted_log = None
  4722. else:
  4723. # Spoolman users get the tray-change log back but no in-memory
  4724. # session — see ``on_print_start`` on why that dict is load-bearing
  4725. # for the remain%-sync guard.
  4726. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4727. persisted_log = await restore_session(
  4728. db,
  4729. printer_id,
  4730. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  4731. )
  4732. if persisted_log:
  4733. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  4734. # Anything this process already observed goes after the persisted
  4735. # history — the log is ordered by layer, and a fresh process can
  4736. # only have seen changes from later in the print.
  4737. for entry in state.tray_change_log or []:
  4738. if tuple(entry) not in restored:
  4739. restored.append(tuple(entry))
  4740. state.tray_change_log = restored
  4741. tray_now = state.tray_now
  4742. if 0 <= tray_now <= 254:
  4743. if not state.tray_change_log:
  4744. # No persisted history — a print that started before this build,
  4745. # or before the row existed. Seed with the tray feeding right
  4746. # now so the remainder of the print is at least attributable to
  4747. # the right spool.
  4748. state.tray_change_log = [(tray_now, state.layer_num)]
  4749. logger.info(
  4750. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  4751. printer_id,
  4752. tray_now,
  4753. state.layer_num,
  4754. )
  4755. # The tray handler updates ``last_loaded_tray`` on every push
  4756. # regardless of whether it logged a change, so re-align it to avoid
  4757. # a duplicate entry on the next push. Only ever with a real tray:
  4758. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  4759. # 255" fallback, and writing 255 into it would defeat that.
  4760. state.last_loaded_tray = tray_now
  4761. except Exception:
  4762. # Never let attribution recovery cost the caller its timelapse
  4763. # baseline — that capture has to happen before the printer uploads
  4764. # the in-flight MP4 and there is no second chance at it.
  4765. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  4766. async def on_print_running_observed(printer_id: int, data: dict):
  4767. """Restart-recovery for a print that started before Bambuddy came up.
  4768. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  4769. after Bambuddy startup (#1304 guard, prevents duplicate archive
  4770. creation). This hook restores the persisted archive into ``_active_prints``
  4771. and captures the timelapse baseline that normally hangs off print start.
  4772. Fires once per session, in lieu of on_print_start when restart-recovery
  4773. kicks in. The printer doesn't upload the timelapse until after PRINT
  4774. COMPLETE, so a baseline captured any time during the print is still
  4775. pre-upload.
  4776. """
  4777. logger = logging.getLogger(__name__)
  4778. async with async_session() as db:
  4779. from backend.app.models.printer import Printer
  4780. state = printer_manager.get_status(printer_id)
  4781. if state is not None:
  4782. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  4783. if authorization is True:
  4784. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  4785. await _restore_usage_tracking_session(printer_id, state, db, logger)
  4786. await _restore_printable_objects(printer_id, state, db, logger)
  4787. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4788. printer = result.scalar_one_or_none()
  4789. if not printer:
  4790. logger.warning(
  4791. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  4792. printer_id,
  4793. )
  4794. return
  4795. # Avoid double-capture: ownership reconciliation above must still run when
  4796. # a baseline already exists, but the camera work itself is one-shot.
  4797. if printer_id in _timelapse_baselines:
  4798. logger.debug(
  4799. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  4800. printer_id,
  4801. )
  4802. return
  4803. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  4804. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  4805. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  4806. against the printer's current MQTT state.
  4807. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  4808. COMPLETE events, typically a print finishing during an MQTT disconnect
  4809. window followed by a smart-plug power cycle):
  4810. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  4811. provably not running anymore — only branch that should fire under
  4812. normal disconnect-then-reconnect timing.
  4813. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  4814. firmware mints a fresh ``subtask_id`` for each print, including the
  4815. ghost replay it runs after a power cycle from a leftover SD file —
  4816. so a mismatch unambiguously means the in-DB archive is no longer
  4817. the print on the printer.
  4818. 3. Printer is running but ``subtask_name`` is empty. The printer
  4819. doesn't know what it's running; the archive's reference to it is
  4820. already broken.
  4821. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  4822. with matching subtask_id+subtask_name is left alone. The cost of a false
  4823. positive is a duplicate archive on the next real PRINT COMPLETE — the
  4824. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  4825. clears on synthesis, so the real completion creates a fresh row instead
  4826. of overwriting the synthesised one (#1679). The cost of a false negative
  4827. is the ghost-print loop in #1542.
  4828. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  4829. MQTT has connected but the first ``push_status`` response hasn't been
  4830. applied yet — ``PrinterState`` is sitting on its construction defaults.
  4831. The reconcile caller in ``on_printer_status_change`` is already gated
  4832. on a real ``state.state``, so in normal operation this branch is
  4833. unreachable; it's kept as belt-and-braces for future callers and for
  4834. the narrow window where a partial state update could arrive
  4835. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  4836. ``not stale`` on degenerate input is strictly conservative: a real
  4837. stale archive will still be caught by the next push_status arriving
  4838. with terminal state.
  4839. """
  4840. current_state = (state.state or "").upper()
  4841. if current_state in ("", "UNKNOWN"):
  4842. # No real push_status yet — PrinterState defaults are not evidence.
  4843. return False, ""
  4844. if current_state in ("IDLE", "FINISH", "FAILED"):
  4845. return True, f"printer state {current_state}"
  4846. # Below here the printer is in a running / pre-running state (RUNNING /
  4847. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  4848. current_subtask_id = (state.subtask_id or "").strip()
  4849. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  4850. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  4851. current_subtask_name = (state.subtask_name or "").strip()
  4852. if not current_subtask_name:
  4853. return True, "printer subtask_name empty"
  4854. return False, ""
  4855. async def prime_kprofile_table(printer_id: int) -> int:
  4856. """Read the printer's calibration table once per connection.
  4857. The AMS slot card shows a K value per slot (#2854). On the printers whose
  4858. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  4859. report ``cali_idx`` and nothing else -- that number can only come from
  4860. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  4861. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  4862. backup, or the printer answering a query BambuStudio made on the report
  4863. topic we share. A Bambuddy that nobody visited showed a card with no K
  4864. values at all.
  4865. Only the diameters actually fitted are asked for, which is one request on a
  4866. single-nozzle printer and two on a dual. Probing the four sizes blind is
  4867. what the backup does, and it is both wasteful and the thing that used to
  4868. blank the table.
  4869. Returns the number of nozzles whose table was read.
  4870. """
  4871. client = printer_manager.get_client(printer_id)
  4872. state = printer_manager.get_status(printer_id)
  4873. if client is None or state is None or not state.connected:
  4874. return 0
  4875. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  4876. # ask once, and both entries are empty until the first push_status lands.
  4877. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  4878. if not diameters:
  4879. logging.getLogger(__name__).debug(
  4880. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  4881. printer_id,
  4882. )
  4883. return 0
  4884. primed = 0
  4885. for diameter in diameters:
  4886. try:
  4887. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  4888. except Exception as exc: # noqa: BLE001
  4889. # A printer that won't answer costs the card its K values, nothing
  4890. # more — never the connection this runs on the back of.
  4891. logging.getLogger(__name__).warning(
  4892. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  4893. )
  4894. continue
  4895. primed += 1
  4896. logging.getLogger(__name__).info(
  4897. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  4898. )
  4899. return primed
  4900. async def reconcile_stale_active_prints(printer_id: int) -> int:
  4901. """Synthesise ``on_print_complete`` for archives whose print can't be
  4902. running on the printer anymore.
  4903. Called once per MQTT (re)connection (from on_printer_status_change when
  4904. the connected edge flips False → True) and at Bambuddy startup (from
  4905. the FastAPI lifespan). Without this, a print that completes during a
  4906. disconnect window — followed by a smart-plug-driven power cycle — leaves
  4907. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  4908. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  4909. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  4910. power cycle until the operator notices (#1542 follow-up). Reconciliation
  4911. closes the loop by faking the missed PRINT COMPLETE — the existing
  4912. cleanup chain handles SD-file deletion, status updates, usage tracking,
  4913. and notifications.
  4914. Synthesised ``status="aborted"`` is the conservative label: we have no
  4915. proof the print finished successfully (and no progress evidence to
  4916. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  4917. fires later, overwrites the status with the correct value.
  4918. Returns the number of archives reconciled.
  4919. """
  4920. state = printer_manager.get_status(printer_id)
  4921. if not state:
  4922. return 0
  4923. # Don't reconcile while disconnected — we'd be making a decision against
  4924. # stale cached state. The connected → reconcile edge handles this.
  4925. if not state.connected:
  4926. return 0
  4927. from backend.app.models.archive import PrintArchive
  4928. reconciled = 0
  4929. async with async_session() as db:
  4930. result = await db.execute(
  4931. select(PrintArchive).where(
  4932. PrintArchive.printer_id == printer_id,
  4933. PrintArchive.status == "printing",
  4934. )
  4935. )
  4936. active = list(result.scalars().all())
  4937. if not active:
  4938. return 0
  4939. logger = logging.getLogger(__name__)
  4940. for archive in active:
  4941. is_stale, reason = _is_active_archive_stale(archive, state)
  4942. if not is_stale:
  4943. continue
  4944. logger.info(
  4945. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  4946. printer_id,
  4947. archive.id,
  4948. archive.filename,
  4949. reason,
  4950. )
  4951. # Synthesised payload: minimal fields the on_print_complete chain
  4952. # needs. `_reconciled` marker lets downstream code distinguish this
  4953. # from a real MQTT-driven completion if it ever needs to (e.g. for
  4954. # metrics / debug logging). raw_data is the live printer state so
  4955. # the usage tracker can compare end-of-print remain% against the
  4956. # captured start values.
  4957. try:
  4958. await on_print_complete(
  4959. printer_id,
  4960. {
  4961. "status": "aborted",
  4962. "filename": archive.filename,
  4963. "subtask_name": archive.print_name or "",
  4964. "subtask_id": archive.subtask_id or "",
  4965. "raw_data": state.raw_data or {},
  4966. "_reconciled": True,
  4967. },
  4968. )
  4969. reconciled += 1
  4970. except Exception as e:
  4971. # Catch-all: a reconciliation failure must not block the
  4972. # printer's normal status flow. The archive stays in
  4973. # ``status="printing"`` and the next reconnect retries.
  4974. logger.warning(
  4975. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  4976. archive.id,
  4977. e,
  4978. )
  4979. return reconciled
  4980. # #2547: clearance left between the nozzle and the top of the print when the
  4981. # plate is commanded back into camera framing. The nozzle is parked away from
  4982. # the part by then, so this is belt-and-braces against a max_z_height that
  4983. # under-reports (e.g. a slicer that excludes a final Z hop).
  4984. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  4985. # How far below the restored position to drop the plate again afterwards, so
  4986. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  4987. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  4988. # on machines with less headroom.
  4989. _PLATE_PARK_DROP_MM = 100.0
  4990. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  4991. # this axis, so it is a proven-safe speed for the full travel.
  4992. _PLATE_RESTORE_FEEDRATE = 600
  4993. # Time allowed for the plate to reach the restored position before the camera
  4994. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  4995. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  4996. # How long `_background_finish_photo` waits for this producer. Must cover the
  4997. # settle window plus a worst-case RTSP grab (15s), and stay below the
  4998. # notification path's own photo wait so a slow producer degrades to a
  4999. # photo-less notification rather than a missed one.
  5000. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5001. async def _max_z_for_current_print(printer_id: int, data: dict, logger) -> float | None:
  5002. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5003. This number becomes the target of a real Z move, so every step here refuses
  5004. rather than guesses. A height belonging to some *other* print is the one
  5005. failure that could drive the nozzle into the model: 20 mm carried onto a
  5006. 200 mm print would command the plate up through the part.
  5007. Two independent things therefore have to agree before a height is returned:
  5008. 1. **Identity.** The archive is matched by the finished print's own
  5009. ``subtask_name``, by equality rather than a ``LIKE``, so "Cube" can never
  5010. resolve to "Cube v2". Matching on "most recent archive for this printer"
  5011. is not good enough — ``on_print_complete`` pops the ``_active_prints``
  5012. binding concurrently with us, and a print Bambuddy failed to archive
  5013. would silently resolve to its predecessor.
  5014. 2. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5015. match the layer count the printer itself reported over MQTT for the print
  5016. that just ended. These come from genuinely different sources, so a
  5017. mismatch means the row is not this print, whatever its name says.
  5018. ``completed`` is accepted alongside ``printing`` only because
  5019. ``on_print_complete`` may already have flipped the status by the time we
  5020. run; the identity check above is what actually selects the row.
  5021. """
  5022. subtask_name = (data.get("subtask_name") or "").strip()
  5023. if not subtask_name:
  5024. # Nothing to identify the print by — refuse rather than fall back to
  5025. # "whatever ran last on this printer".
  5026. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5027. return None
  5028. try:
  5029. from backend.app.models.archive import PrintArchive
  5030. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5031. async with async_session() as db:
  5032. result = await db.execute(
  5033. select(PrintArchive)
  5034. .where(
  5035. PrintArchive.printer_id == printer_id,
  5036. PrintArchive.status.in_(("printing", "completed")),
  5037. PrintArchive.deleted_at.is_(None),
  5038. or_(
  5039. PrintArchive.print_name == subtask_name,
  5040. PrintArchive.filename == subtask_name,
  5041. PrintArchive.filename == f"{subtask_name}.3mf",
  5042. PrintArchive.filename == f"{subtask_name}.gcode.3mf",
  5043. ),
  5044. )
  5045. .order_by(PrintArchive.id.desc())
  5046. .limit(1)
  5047. )
  5048. archive = result.scalar_one_or_none()
  5049. if archive is None or not archive.file_path:
  5050. logger.info("[PLATE-RESTORE] printer %s: no archive matches %r — skipping", printer_id, subtask_name)
  5051. return None
  5052. client = printer_manager.get_client(printer_id)
  5053. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  5054. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  5055. logger.warning(
  5056. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  5057. "— refusing to move the plate on a height that may not be this print's",
  5058. printer_id,
  5059. archive.id,
  5060. archive.total_layers,
  5061. reported_layers,
  5062. )
  5063. return None
  5064. path = Path(archive.file_path)
  5065. if not path.is_absolute():
  5066. path = Path(app_settings.data_dir) / path
  5067. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, archive.plate_id or 1)
  5068. except Exception as e:
  5069. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  5070. return None
  5071. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  5072. """Raise the plate back into camera framing before the finish photo (#2547).
  5073. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  5074. the time ``gcode_state`` reaches FINISH the finished print sits far below
  5075. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  5076. This commands an absolute ``G1 Z`` back to just above the last printed
  5077. layer.
  5078. Absolute, not relative, is the whole safety argument. ``max_z_height +
  5079. clearance`` is a height the toolhead was physically at seconds earlier, so
  5080. it is inside the travel limits by construction and leaves the nozzle above
  5081. the part. It is also unambiguous across model families: Z is the
  5082. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  5083. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  5084. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  5085. (#2579).
  5086. Returns True if the move was sent and waited out, False if it was skipped.
  5087. """
  5088. client = printer_manager.get_client(printer_id)
  5089. if client is None:
  5090. return False
  5091. # Re-read state immediately before commanding motion. If the queue has
  5092. # already started the next print, the printer is no longer ours to move.
  5093. state = getattr(client, "state", None)
  5094. if state is None or state.state != "FINISH":
  5095. logger.info(
  5096. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  5097. printer_id,
  5098. getattr(state, "state", "unknown"),
  5099. )
  5100. return False
  5101. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  5102. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  5103. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  5104. return False
  5105. logger.info(
  5106. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  5107. printer_id,
  5108. target_z,
  5109. max_z_height,
  5110. _PLATE_RESTORE_CLEARANCE_MM,
  5111. _PLATE_RESTORE_SETTLE_SECONDS,
  5112. )
  5113. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  5114. return True
  5115. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  5116. """Drop the plate again after the finish photo (#2547).
  5117. Without this the user walks up to a finished print sitting just under the
  5118. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  5119. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  5120. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  5121. print homes anyway.
  5122. """
  5123. client = printer_manager.get_client(printer_id)
  5124. state = getattr(client, "state", None) if client else None
  5125. if client is None or state is None or state.state != "FINISH":
  5126. return
  5127. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  5128. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  5129. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  5130. """True if a queue item is about to take this printer (#2547).
  5131. The scheduler dispatches the next job the moment a print completes, and a
  5132. plate move interleaved with a print start is not a race worth having. The
  5133. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  5134. this window; this closes the head of it.
  5135. """
  5136. try:
  5137. from backend.app.models.print_queue import PrintQueueItem
  5138. async with async_session() as db:
  5139. result = await db.execute(
  5140. select(PrintQueueItem.id)
  5141. .where(
  5142. PrintQueueItem.printer_id == printer_id,
  5143. PrintQueueItem.status.in_(("pending", "printing")),
  5144. )
  5145. .limit(1)
  5146. )
  5147. return result.scalar_one_or_none() is not None
  5148. except Exception as e:
  5149. # Fail closed: if we can't tell, don't move the plate.
  5150. logging.getLogger(__name__).debug(
  5151. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  5152. )
  5153. return True
  5154. async def on_finish_photo_moment(printer_id: int, data: dict):
  5155. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  5156. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  5157. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  5158. fallback for prints that skip stage 22 (cancel, external-spool-only,
  5159. HMS halt, firmware variants). Grabs one frame via the same
  5160. external-camera / RTSP path the post-completion fallback uses, stores
  5161. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  5162. ``_background_finish_photo`` consume the cached bytes when it runs.
  5163. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  5164. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  5165. set to Smooth (#1721). No force-on now means the user's explicit
  5166. timelapse=off in the slicer send dialog is respected.
  5167. """
  5168. logger = logging.getLogger(__name__)
  5169. trigger = data.get("trigger", "unknown")
  5170. timelapse_was_active = bool(data.get("timelapse_was_active"))
  5171. logger.info(
  5172. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  5173. printer_id,
  5174. trigger,
  5175. timelapse_was_active,
  5176. )
  5177. # If a timelapse is actively recording, skip the pre-capture — the
  5178. # post-completion path will extract the last frame from the recorded
  5179. # video, which still provides the best framing (toolhead parked,
  5180. # before bed drop) without the per-layer parking side effects.
  5181. if timelapse_was_active:
  5182. logger.info(
  5183. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  5184. printer_id,
  5185. )
  5186. return
  5187. # #1790: register the producer-done event BEFORE the first await so the
  5188. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  5189. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  5190. # The `finally` below guarantees `set()` runs on every exit, including
  5191. # early returns and exceptions, so the consumer's bounded wait can't hang.
  5192. producer_done = asyncio.Event()
  5193. _stage22_finish_in_flight[printer_id] = producer_done
  5194. # #2547: set once the plate has actually been raised, and read by the
  5195. # `finally` below. Declared out here so a failure anywhere after the move —
  5196. # a camera timeout, a DB error — still lowers the plate again.
  5197. restore_max_z: float | None = None
  5198. try:
  5199. async with async_session() as db:
  5200. from backend.app.api.routes.settings import get_setting
  5201. from backend.app.models.printer import Printer
  5202. capture_setting = await get_setting(db, "capture_finish_photo")
  5203. if capture_setting is not None and capture_setting.lower() != "true":
  5204. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  5205. return
  5206. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  5207. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  5208. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5209. printer = result.scalar_one_or_none()
  5210. if printer is None:
  5211. logger.warning(
  5212. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  5213. printer_id,
  5214. )
  5215. return
  5216. frame_bytes: bytes | None = None
  5217. # #2708: the banked frame arrives already rotated — it comes from
  5218. # `_capture_snapshot_for_notification`, which rotates before returning.
  5219. # Every other source below is a raw grab. Tracking which lets us store
  5220. # exactly one rotation in `_stage22_finish_frames` either way.
  5221. frame_already_rotated = False
  5222. # On the FINISH-state path the End G-code has already run, and two very
  5223. # different situations arrive here needing opposite answers.
  5224. #
  5225. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  5226. # snippet may have ejected the plate — the scene in front of the camera
  5227. # is no longer the finished print, and no amount of moving the plate
  5228. # brings it back. Use the banked in-print frame instead.
  5229. #
  5230. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  5231. # than the camera frames well, and the toolhead is parked out of the
  5232. # way. That is the *best* moment available on firmware that never emits
  5233. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  5234. # back. Preferring the bank here unconditionally, as this code used to,
  5235. # is what shipped a mid-print photo with the toolhead over the part.
  5236. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  5237. banked = _inprint_frame_bank.get(printer_id)
  5238. if banked:
  5239. frame_bytes = banked
  5240. frame_already_rotated = True
  5241. logger.info(
  5242. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  5243. "frame (%d bytes) instead of a post-swap live grab",
  5244. len(banked),
  5245. )
  5246. else:
  5247. logger.warning(
  5248. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  5249. "in-print bank is empty — falling back to a live grab, which may show a "
  5250. "swapped or empty plate",
  5251. printer_id,
  5252. )
  5253. # `restore_max_z` is set only once the plate is actually up, because the
  5254. # `finally` reads it to decide whether it owes a move back down.
  5255. #
  5256. # Never on a print whose End G-code Bambuddy injected, even when the bank
  5257. # came up empty above: that machine may have just ejected its plate, and
  5258. # driving Z into whatever a swap mechanism is doing is not a risk worth
  5259. # taking for a photo of a bed we already know may be bare.
  5260. if (
  5261. frame_bytes is None
  5262. and trigger == "finish_state"
  5263. and restore_plate_enabled
  5264. and not print_dispatch_context.end_gcode_injected(printer_id)
  5265. ):
  5266. wants_restore = await _max_z_for_current_print(printer_id, data, logger)
  5267. if wants_restore is None:
  5268. logger.info(
  5269. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  5270. printer_id,
  5271. )
  5272. elif await _plate_restore_is_blocked_by_queue(printer_id):
  5273. logger.info(
  5274. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  5275. printer_id,
  5276. )
  5277. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  5278. restore_max_z = wants_restore
  5279. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  5280. from backend.app.api.routes.camera import live_frame_for_capture
  5281. from backend.app.services.external_camera import capture_frame
  5282. # #2707: this used to collide with the live view and fail, which is
  5283. # how finish-photo notifications went out with no image attached.
  5284. # Leaving frame_bytes None keeps the rest of the fallback chain.
  5285. defer, buffered = live_frame_for_capture(printer_id)
  5286. if defer:
  5287. frame_bytes = buffered
  5288. else:
  5289. frame_bytes = await capture_frame(
  5290. printer.external_camera_url,
  5291. printer.external_camera_type or "mjpeg",
  5292. snapshot_url=printer.external_camera_snapshot_url,
  5293. )
  5294. if frame_bytes:
  5295. logger.info(
  5296. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  5297. len(frame_bytes),
  5298. )
  5299. elif frame_bytes is None:
  5300. from backend.app.api.routes.camera import get_buffered_frame
  5301. buffered = get_buffered_frame(printer_id)
  5302. if buffered:
  5303. frame_bytes = buffered
  5304. logger.info(
  5305. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  5306. len(frame_bytes),
  5307. )
  5308. else:
  5309. from backend.app.services.camera import capture_camera_frame_bytes
  5310. frame_bytes = await capture_camera_frame_bytes(
  5311. ip_address=printer.ip_address,
  5312. access_code=printer.access_code,
  5313. model=printer.model,
  5314. timeout=15,
  5315. )
  5316. if frame_bytes:
  5317. logger.info(
  5318. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  5319. len(frame_bytes),
  5320. )
  5321. if frame_bytes:
  5322. if not frame_already_rotated:
  5323. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  5324. _stage22_finish_frames[printer_id] = frame_bytes
  5325. else:
  5326. logger.warning(
  5327. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  5328. printer_id,
  5329. )
  5330. except Exception as e:
  5331. logger.warning(
  5332. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  5333. printer_id,
  5334. e,
  5335. )
  5336. finally:
  5337. # #2547: we raised the plate, so we own lowering it — including when the
  5338. # capture above failed or threw partway through.
  5339. if restore_max_z is not None:
  5340. try:
  5341. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  5342. except Exception as e:
  5343. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  5344. # #1790: always unblock the consumer's bounded wait — whether we stored
  5345. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  5346. # dict entry by the consumer doesn't affect signalling.
  5347. producer_done.set()
  5348. def _subtask_name_from_filename(filename: str) -> str:
  5349. """Recover the subtask name a print command would have carried for *filename*.
  5350. The dispatcher derives the printer-facing subtask name from the archive's
  5351. file name, so stripping the extensions back off gives the value MQTT echoes
  5352. on completion. Only the two extensions Bambuddy actually stores are removed,
  5353. and in the order they nest (``.gcode.3mf``), so a model whose own name
  5354. contains a dot -- ``My.Model.3mf`` -- keeps it.
  5355. """
  5356. name = PurePosixPath(filename).name
  5357. for suffix in (".3mf", ".gcode"):
  5358. if name.lower().endswith(suffix):
  5359. name = name[: -len(suffix)]
  5360. return name
  5361. # How the printer marks a subtask name it had to cut short. Observed on real
  5362. # hardware at ~100 characters, but the cut-off is not a fixed character count
  5363. # (a name with multibyte characters came back at 98), so match the marker
  5364. # rather than a length.
  5365. _SUBTASK_TRUNCATION_MARKER = "..."
  5366. def _normalise_subtask_name(name: str) -> str:
  5367. """Canonical form for comparing a dispatched name against MQTT's echo.
  5368. The printer does not echo the name back verbatim: it substitutes
  5369. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  5370. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  5371. The 3MF lookup in this module has always known that -- it builds
  5372. space-to-underscore variants of every candidate filename, and its
  5373. directory search normalises both sides before comparing. This exists so
  5374. the completion check reads the same rule from the same place instead of
  5375. growing its own, which is exactly how it came to disagree (#2829).
  5376. """
  5377. return name.strip().replace(" ", "_").casefold()
  5378. def _subtask_names_match(expected: str, observed: str) -> bool:
  5379. """Whether two subtask names describe the same print.
  5380. Beyond the space/underscore substitution, the printer truncates long names
  5381. and marks the cut with ``...``. A truncated echo has to count as a match or
  5382. every print with a long name strands its queue item the same way.
  5383. """
  5384. expected_n = _normalise_subtask_name(expected)
  5385. observed_n = _normalise_subtask_name(observed)
  5386. if expected_n == observed_n:
  5387. return True
  5388. # Either side can be the truncated one: the printer truncates what it
  5389. # echoes, and an archive whose own filename was recorded from a previous
  5390. # truncated echo carries the marker too.
  5391. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  5392. if cut.endswith(_SUBTASK_TRUNCATION_MARKER) and full.startswith(cut[: -len(_SUBTASK_TRUNCATION_MARKER)]):
  5393. return True
  5394. return False
  5395. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  5396. """Whether this completion event is plausibly about *item*'s print.
  5397. The caller finds its queue row by printer and ``status='printing'`` alone,
  5398. which is all a completion event gives it -- there is no run identifier in
  5399. the MQTT payload to match on. That makes the lookup indiscriminate: any
  5400. completion delivered for this printer closes whichever row happens to be
  5401. printing, however unrelated. Comparing the subtask name against the archive
  5402. the row was dispatched with costs one primary-key load and rules that out.
  5403. Deliberately permissive: it answers False only on a positive disagreement
  5404. between two names we actually have. A row with no archive, an archive with
  5405. no file name, or an event with no subtask name is unverifiable rather than
  5406. wrong, and refusing those would strand the item in ``printing`` and wedge
  5407. the printer's queue -- a worse failure than the one being prevented.
  5408. """
  5409. observed = (data.get("subtask_name") or "").strip()
  5410. if not observed or item.archive_id is None:
  5411. return True
  5412. from backend.app.models.archive import PrintArchive
  5413. archive = await db.get(PrintArchive, item.archive_id)
  5414. if archive is None or not archive.filename:
  5415. return True
  5416. expected = _subtask_name_from_filename(archive.filename)
  5417. if not expected or _subtask_names_match(expected, observed):
  5418. return True
  5419. logging.getLogger(__name__).warning(
  5420. "Ignoring print completion for queue item %s: it was dispatched as %r "
  5421. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  5422. "printing rather than closing a run this event is not about.",
  5423. item.id,
  5424. expected,
  5425. archive.id,
  5426. archive.filename,
  5427. observed,
  5428. )
  5429. return False
  5430. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  5431. """Spend the 3MF download cache on a still-empty fallback archive.
  5432. ``on_print_complete`` drops the cache as its first act, which deletes the
  5433. file. If the cover endpoint (or anything else) pulled the 3MF while the
  5434. print ran and the archive never got one, this is the last moment those bytes
  5435. exist (#2957).
  5436. """
  5437. logger = logging.getLogger(__name__)
  5438. names = [
  5439. n
  5440. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  5441. if n
  5442. ]
  5443. for name in names:
  5444. try:
  5445. cached = get_cached_3mf(printer_id, name)
  5446. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  5447. return
  5448. except Exception as e:
  5449. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  5450. async def on_print_complete(printer_id: int, data: dict):
  5451. """Handle print completion - update the archive status."""
  5452. import time
  5453. logger = logging.getLogger(__name__)
  5454. start_time = time.time()
  5455. def log_timing(section: str):
  5456. elapsed = time.time() - start_time
  5457. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  5458. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  5459. # A kill-switch stop sends its provider notification immediately. Keep the
  5460. # task so the later notification path can await it and avoid a duplicate;
  5461. # if that immediate attempt failed, the regular completion path retries.
  5462. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  5463. # Last chance before the bytes go: if this print's archive is still an empty
  5464. # fallback and something downloaded the 3MF while it ran, fill the archive in
  5465. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  5466. # below deletes the file (#2957).
  5467. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  5468. # A pending cool-off retry has nothing left to recover for — the cache is
  5469. # about to be dropped and the print is over.
  5470. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  5471. if retry_task and not retry_task.done():
  5472. retry_task.cancel()
  5473. # Drop the 3MF download cache for this printer (#972). The print is over,
  5474. # nothing else legitimately needs the bytes; keeping them would only risk
  5475. # handing a stale file to the next print if it reuses the same name.
  5476. clear_3mf_cache(printer_id)
  5477. try:
  5478. ws_data = {
  5479. "status": data.get("status"),
  5480. "filename": data.get("filename"),
  5481. "subtask_name": data.get("subtask_name"),
  5482. "timelapse_was_active": data.get("timelapse_was_active"),
  5483. }
  5484. await ws_manager.send_print_complete(printer_id, ws_data)
  5485. log_timing("WebSocket send_print_complete")
  5486. except Exception as e:
  5487. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  5488. # Capture user info before clearing (needed for print log entry)
  5489. _print_user_info = printer_manager.get_current_print_user(printer_id)
  5490. # Clear current print user tracking (Issue #206)
  5491. printer_manager.clear_current_print_user(printer_id)
  5492. # If the user explicitly stopped this print from the queue UI the printer will
  5493. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  5494. # correct "print stopped" notification/email is sent instead of a failure alert.
  5495. _raw_status = data.get("status", "completed")
  5496. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  5497. logger.info(
  5498. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  5499. _raw_status,
  5500. printer_id,
  5501. )
  5502. data = {**data, "status": "cancelled"}
  5503. _user_stopped_printers.discard(printer_id)
  5504. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  5505. # may have left material on the bed: a user can cancel ten hours into a
  5506. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  5507. # touchscreen-stop reports `aborted` rather than `cancelled` because
  5508. # `_user_stopped_printers` is only populated when the user stops via the
  5509. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  5510. # which auto-dispatched the next queued print onto a fouled bed two seconds
  5511. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  5512. # Auto Off power cycles and Bambuddy restarts.
  5513. _final_status = data.get("status", "completed")
  5514. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  5515. printer_manager.set_awaiting_plate_clear(printer_id, True)
  5516. # MQTT relay - publish print complete
  5517. try:
  5518. printer_info = printer_manager.get_printer(printer_id)
  5519. if printer_info:
  5520. await mqtt_relay.on_print_complete(
  5521. printer_id,
  5522. printer_info.name,
  5523. printer_info.serial_number,
  5524. data.get("filename", ""),
  5525. data.get("subtask_name", ""),
  5526. data.get("status", "completed"),
  5527. )
  5528. except Exception:
  5529. pass # Don't fail print complete callback if MQTT fails
  5530. filename = data.get("filename", "")
  5531. subtask_name = data.get("subtask_name", "")
  5532. if not filename and not subtask_name:
  5533. logger.warning("Print complete without filename or subtask_name")
  5534. return
  5535. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  5536. # Build list of possible keys to try (matching how they were registered in on_print_start)
  5537. possible_keys = []
  5538. # Try subtask_name variations first (most reliable for matching)
  5539. if subtask_name:
  5540. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5541. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5542. possible_keys.append((printer_id, subtask_name))
  5543. # Try filename variations
  5544. if filename:
  5545. # Extract just the filename if it's a path
  5546. fname = filename.split("/")[-1] if "/" in filename else filename
  5547. if fname.endswith(".3mf"):
  5548. possible_keys.append((printer_id, fname))
  5549. elif fname.endswith(".gcode"):
  5550. base_name = fname.rsplit(".", 1)[0]
  5551. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5552. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5553. possible_keys.append((printer_id, fname))
  5554. else:
  5555. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5556. possible_keys.append((printer_id, f"{fname}.3mf"))
  5557. possible_keys.append((printer_id, fname))
  5558. # Also try full path versions
  5559. if filename.endswith(".3mf"):
  5560. possible_keys.append((printer_id, filename))
  5561. elif filename.endswith(".gcode"):
  5562. base_name = filename.rsplit(".", 1)[0]
  5563. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5564. possible_keys.append((printer_id, filename))
  5565. else:
  5566. possible_keys.append((printer_id, f"{filename}.3mf"))
  5567. possible_keys.append((printer_id, filename))
  5568. # Find the archive for this print
  5569. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  5570. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  5571. archive_id = None
  5572. for key in possible_keys:
  5573. archive_id = _active_prints.pop(key, None)
  5574. if archive_id:
  5575. logger.info("Found archive %s with key %s", archive_id, key)
  5576. # Also clean up any other keys pointing to this archive
  5577. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  5578. for k in keys_to_remove:
  5579. _active_prints.pop(k, None)
  5580. break
  5581. if not archive_id:
  5582. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  5583. async with async_session() as db:
  5584. from backend.app.models.archive import PrintArchive
  5585. # Try matching by subtask_name (stored as print_name) first
  5586. if subtask_name:
  5587. result = await db.execute(
  5588. select(PrintArchive)
  5589. .where(PrintArchive.printer_id == printer_id)
  5590. .where(PrintArchive.status == "printing")
  5591. .where(
  5592. or_(
  5593. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  5594. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  5595. )
  5596. )
  5597. .order_by(PrintArchive.created_at.desc())
  5598. .limit(1)
  5599. )
  5600. archive = result.scalar_one_or_none()
  5601. if archive:
  5602. archive_id = archive.id
  5603. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  5604. # Also try by filename
  5605. if not archive_id and filename:
  5606. result = await db.execute(
  5607. select(PrintArchive)
  5608. .where(PrintArchive.printer_id == printer_id)
  5609. .where(PrintArchive.filename == filename)
  5610. .where(PrintArchive.status == "printing")
  5611. .order_by(PrintArchive.created_at.desc())
  5612. .limit(1)
  5613. )
  5614. archive = result.scalar_one_or_none()
  5615. if archive:
  5616. archive_id = archive.id
  5617. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  5618. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  5619. # auto-start files found in root on power cycle, causing ghost prints.
  5620. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  5621. try:
  5622. if subtask_name:
  5623. archive_filename: str | None = None
  5624. async with async_session() as db:
  5625. from backend.app.models.archive import PrintArchive
  5626. from backend.app.models.printer import Printer
  5627. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5628. printer = result.scalar_one_or_none()
  5629. if archive_id:
  5630. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  5631. archive_filename = archive_row.scalar_one_or_none()
  5632. if printer:
  5633. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  5634. from backend.app.utils.filename import derive_remote_filename
  5635. # Primary candidate: the exact path the dispatcher uploaded to
  5636. # (derived from archive.filename via the same rule as upload).
  5637. # Without it, a library row that ended up with a doubled
  5638. # .gcode.3mf (#1542) leaves the real file behind because the
  5639. # subtask_name + ext fallbacks below don't match what's on the
  5640. # SD card. Fallbacks remain for archive-less prints (subtask
  5641. # never resolved to an archive) and for older naming variants.
  5642. candidate_paths: list[str] = []
  5643. if archive_filename:
  5644. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  5645. for ext in (".3mf", ".gcode"):
  5646. fallback = f"/{subtask_name}{ext}"
  5647. if fallback not in candidate_paths:
  5648. candidate_paths.append(fallback)
  5649. # Three outcomes track across all candidates so the final log
  5650. # line reflects what actually happened. The A1 in #1721 always
  5651. # ends here with ``any_not_found=True`` and the others False
  5652. # — its firmware auto-cleans the SD card before our cleanup
  5653. # runs, every candidate FTP-DELE returns 550, and the old
  5654. # code burned 3 retries × 2 s × 3 candidates per print
  5655. # logging a misleading "may linger" WARNING on a successful
  5656. # print.
  5657. any_deleted = False
  5658. any_real_failure = False
  5659. any_not_found = False
  5660. for remote_path in candidate_paths:
  5661. # Retry only the FAILED case — 550 NOT_FOUND will never
  5662. # recover by waiting, so a "file isn't here" answer
  5663. # advances immediately to the next candidate without
  5664. # consuming the retry budget.
  5665. for attempt in range(1, 4):
  5666. try:
  5667. delete_result = await delete_file_async(
  5668. printer.ip_address,
  5669. printer.access_code,
  5670. remote_path,
  5671. printer_model=printer.model,
  5672. )
  5673. except Exception as e:
  5674. delete_result = DeleteResult.FAILED
  5675. logger.warning(
  5676. "SD card cleanup attempt %d/3 raised for %s: %s",
  5677. attempt,
  5678. remote_path,
  5679. e,
  5680. )
  5681. if delete_result == DeleteResult.DELETED:
  5682. any_deleted = True
  5683. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  5684. break
  5685. if delete_result == DeleteResult.NOT_FOUND:
  5686. any_not_found = True
  5687. break # 550 will not recover; try next candidate
  5688. # FAILED: real error — retry with backoff, then give up
  5689. if attempt < 3:
  5690. await asyncio.sleep(2)
  5691. else:
  5692. any_real_failure = True
  5693. logger.warning(
  5694. "SD card cleanup failed after 3 attempts for %s "
  5695. "(network/auth/transient error — file may linger on SD card)",
  5696. remote_path,
  5697. )
  5698. if not any_deleted and not any_real_failure and any_not_found:
  5699. # Every candidate said "not here." Either the printer
  5700. # firmware swept the SD card itself (common on A1) or the
  5701. # dispatcher's upload path doesn't match our candidate
  5702. # rule. Either way: nothing to clean up, no warning.
  5703. logger.debug(
  5704. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  5705. "(printer likely self-cleaned)",
  5706. printer.name,
  5707. )
  5708. except Exception as e:
  5709. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  5710. log_timing("SD card cleanup")
  5711. # Update queue item status early — must run before the archive_id early-return
  5712. # so queue items don't get stuck in "printing" when archive lookup fails.
  5713. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  5714. queue_item_id = None
  5715. billing_run_id: str | None = None
  5716. billing_user_id: int | None = None
  5717. billing_cost_center_id: int | None = None
  5718. billing_plate_id: int | None = None
  5719. queue_status = None
  5720. queue_auto_off = False
  5721. try:
  5722. from backend.app.core.database import run_with_retry
  5723. from backend.app.models.print_queue import PrintQueueItem
  5724. async def _update_queue_status(db):
  5725. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  5726. nonlocal queue_item_id, queue_status, queue_auto_off
  5727. result = await db.execute(
  5728. select(PrintQueueItem)
  5729. .where(PrintQueueItem.printer_id == printer_id)
  5730. .where(PrintQueueItem.status == "printing")
  5731. )
  5732. printing_items = list(result.scalars().all())
  5733. if len(printing_items) > 1:
  5734. logger.warning(
  5735. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  5736. printer_id,
  5737. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  5738. )
  5739. item = printing_items[0] if printing_items else None
  5740. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  5741. return
  5742. if item:
  5743. queue_status = data.get("status", "completed")
  5744. # MQTT sends "aborted" for cancelled prints; normalise to
  5745. # "cancelled" so it matches the queue schema Literal.
  5746. if queue_status == "aborted":
  5747. queue_status = "cancelled"
  5748. item.status = queue_status
  5749. item.completed_at = datetime.now(timezone.utc)
  5750. if queue_status == "failed" and not item.error_message:
  5751. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  5752. # Bump usage counters on the source library file so admins can
  5753. # sort by "last printed" and (eventually) auto-purge stale
  5754. # files — #1008.
  5755. await _bump_library_file_usage_if_completed(db, item, queue_status)
  5756. await db.commit()
  5757. queue_item_id = item.id
  5758. billing_run_id = item.billing_run_id
  5759. billing_user_id = item.created_by_id
  5760. billing_cost_center_id = item.cost_center_id
  5761. billing_plate_id = item.plate_id
  5762. queue_auto_off = item.auto_off_after
  5763. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  5764. await run_with_retry(_update_queue_status, label="queue status update")
  5765. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  5766. # their own sessions and have their own error handling — no retry needed.
  5767. if queue_item_id is not None:
  5768. # Batch orders (#342): this run may have been the last one an order
  5769. # owed. Re-evaluate here rather than lazily on read, so a finished
  5770. # order reports itself complete without someone opening the page.
  5771. try:
  5772. from backend.app.services.print_batch import refresh_batch_status_for_item
  5773. async with async_session() as db:
  5774. await refresh_batch_status_for_item(db, queue_item_id)
  5775. await db.commit()
  5776. except Exception as e:
  5777. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  5778. # MQTT relay - publish queue job completed
  5779. try:
  5780. printer_info = printer_manager.get_printer(printer_id)
  5781. await mqtt_relay.on_queue_job_completed(
  5782. job_id=queue_item_id,
  5783. filename=filename or subtask_name,
  5784. printer_id=printer_id,
  5785. printer_name=printer_info.name if printer_info else "Unknown",
  5786. status=queue_status,
  5787. )
  5788. except Exception:
  5789. pass # Don't fail if MQTT fails
  5790. # Check if queue is now empty and send notification
  5791. try:
  5792. from sqlalchemy import func as sa_func
  5793. async with async_session() as db:
  5794. count_result = await db.execute(
  5795. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  5796. )
  5797. pending_count = count_result.scalar() or 0
  5798. if pending_count == 0:
  5799. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  5800. completed_result = await db.execute(
  5801. select(sa_func.count(PrintQueueItem.id)).where(
  5802. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  5803. PrintQueueItem.completed_at >= today_start,
  5804. )
  5805. )
  5806. completed_count = completed_result.scalar() or 1
  5807. await notification_service.on_queue_completed(
  5808. completed_count=completed_count,
  5809. db=db,
  5810. )
  5811. except Exception:
  5812. pass # Don't fail if notification fails
  5813. # Handle auto_off_after - power off printer if the queue item opted
  5814. # in. Delegates to the smart-plug manager so the off honours each
  5815. # plug's configured strategy (time delay or temperature threshold),
  5816. # is cancelled if the printer starts printing again, and never cuts
  5817. # power on a loaded print (#1890). Previously an inline block here
  5818. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  5819. # timeout regardless of print state — cutting a touchscreen reprint.
  5820. if queue_auto_off:
  5821. try:
  5822. async with async_session() as db:
  5823. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  5824. except Exception as e:
  5825. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  5826. except Exception as e:
  5827. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  5828. log_timing("Queue item update")
  5829. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  5830. # Must run before archive_id early-return so it fires for all prints (including
  5831. # prints started from BambuStudio/touchscreen that have no archive).
  5832. if data.get("status") == "completed":
  5833. try:
  5834. from backend.app.api.routes.settings import get_setting
  5835. async with async_session() as db:
  5836. threshold_str = await get_setting(db, "bed_cooled_threshold")
  5837. threshold = float(threshold_str) if threshold_str else 35.0
  5838. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  5839. async with async_session() as db:
  5840. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  5841. if providers:
  5842. _bed_cool_waiters[printer_id] = {
  5843. "threshold": threshold,
  5844. "filename": filename or subtask_name or "",
  5845. "registered_at": time.time(),
  5846. }
  5847. logger.info(
  5848. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  5849. printer_id,
  5850. threshold,
  5851. )
  5852. else:
  5853. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  5854. except Exception as e:
  5855. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  5856. # Capture the slicer estimate before usage tracking runs. The tracker may
  5857. # update archive.cost with this run's measured cost; billing partial runs
  5858. # against that already-partial value would discount the charge twice.
  5859. billing_planned_grams: float | None = None
  5860. billing_base_cost: float | None = None
  5861. if archive_id:
  5862. try:
  5863. async with async_session() as db:
  5864. from backend.app.models.archive import PrintArchive
  5865. billing_archive = await db.get(PrintArchive, archive_id)
  5866. if billing_archive:
  5867. billing_path = (
  5868. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  5869. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  5870. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  5871. billing_archive,
  5872. billing_path,
  5873. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  5874. )
  5875. except Exception as e:
  5876. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  5877. # --- Track filament consumption (must run before archive_id early-return so usage
  5878. # is recorded even when auto-archive is disabled) ---
  5879. usage_results: list[dict] = []
  5880. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  5881. stored_ams_mapping = data.get("ams_mapping")
  5882. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  5883. if not stored_ams_mapping and archive_id:
  5884. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  5885. # Always drain the plate_id register on completion — the session already
  5886. # consumed it at print-start injection; leaving it would leak into the next
  5887. # print on the same archive_id (rare but possible with reprints) (#1697).
  5888. # Capture the popped value so the completion notification can scope the
  5889. # archive-level (summed-across-plates per #1593) filament + time totals
  5890. # down to the single plate that was actually printed (#1785).
  5891. notify_plate_id: int | None = None
  5892. if archive_id:
  5893. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  5894. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  5895. try:
  5896. async with async_session() as db:
  5897. from backend.app.api.routes.settings import get_setting
  5898. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5899. if not _spoolman_on or _spoolman_on.lower() != "true":
  5900. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  5901. async with async_session() as db:
  5902. usage_results = await usage_on_print_complete(
  5903. printer_id,
  5904. data,
  5905. printer_manager,
  5906. db,
  5907. archive_id=archive_id,
  5908. ams_mapping=stored_ams_mapping,
  5909. )
  5910. if usage_results:
  5911. await ws_manager.broadcast(
  5912. {
  5913. "type": "spool_usage_logged",
  5914. "printer_id": printer_id,
  5915. "usage": usage_results,
  5916. }
  5917. )
  5918. log_timing("Usage tracker")
  5919. except Exception as e:
  5920. logger.warning("Usage tracker on_print_complete failed: %s", e)
  5921. # Drop the print-start context unconditionally — the Spoolman branch above
  5922. # skips the internal tracker entirely, so nothing else would clear what
  5923. # print start captured, and a row surviving its print would be restored
  5924. # onto the next one after a restart.
  5925. try:
  5926. from backend.app.services.usage_tracker import discard_session
  5927. async with async_session() as db:
  5928. await discard_session(db, printer_id)
  5929. except Exception as e:
  5930. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  5931. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  5932. if archive_id:
  5933. if data.get("status") == "completed":
  5934. try:
  5935. await _report_spoolman_usage(printer_id, archive_id)
  5936. log_timing("Spoolman usage report")
  5937. except Exception as e:
  5938. logger.warning("Spoolman usage reporting failed: %s", e)
  5939. else:
  5940. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  5941. try:
  5942. async with async_session() as db:
  5943. await _cleanup_spoolman_tracking(
  5944. printer_id,
  5945. archive_id,
  5946. db,
  5947. last_layer_num=data.get("last_layer_num"),
  5948. last_progress=data.get("last_progress"),
  5949. )
  5950. except Exception as e:
  5951. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  5952. log_timing("Filament usage tracking")
  5953. if not archive_id:
  5954. # The printer's own calibration run has no archive by design, so this
  5955. # arrives here every time one finishes. Returning before the no-archive
  5956. # notification is not just noise control: that path attributes an
  5957. # unmatched completion to any queue item this printer finished in the
  5958. # last five minutes, which for a calibration that runs alongside a real
  5959. # print means emailing its owner that their print is done, twice and
  5960. # early. Everything above this point has already run — the plate-clear
  5961. # gate, the queue reconciliation, the SD-card cleanup — so only the
  5962. # notification is skipped.
  5963. if is_internal_printer_job(filename, subtask_name):
  5964. logger.info(
  5965. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  5966. filename,
  5967. subtask_name,
  5968. )
  5969. return
  5970. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  5971. # Still send print-complete/failed/stopped notifications even without an archive.
  5972. # Try to enrich with queue/library-file data so user-specific emails work too.
  5973. async def _notify_no_archive():
  5974. try:
  5975. async with async_session() as db:
  5976. from backend.app.models.library import LibraryFile
  5977. from backend.app.models.print_queue import PrintQueueItem
  5978. from backend.app.models.printer import Printer
  5979. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5980. printer_obj = result.scalar_one_or_none()
  5981. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  5982. # Try to find the most-recent queue item for this printer so we can
  5983. # recover created_by_id and estimated print time.
  5984. # NOTE: By the time this task runs the queue item status has already
  5985. # been updated to a terminal state (completed/failed/cancelled), so
  5986. # we look for recently-completed items (within the last 5 minutes).
  5987. no_archive_data: dict | None = None
  5988. try:
  5989. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  5990. q_result = await db.execute(
  5991. select(PrintQueueItem)
  5992. .where(PrintQueueItem.printer_id == printer_id)
  5993. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  5994. .where(PrintQueueItem.completed_at >= cutoff)
  5995. .order_by(PrintQueueItem.completed_at.desc())
  5996. .limit(1)
  5997. )
  5998. queue_item = q_result.scalar_one_or_none()
  5999. if queue_item:
  6000. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6001. # Pull estimated time from library file when available
  6002. if queue_item.library_file_id:
  6003. lib_result = await db.execute(
  6004. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6005. )
  6006. lib_file = lib_result.scalar_one_or_none()
  6007. if lib_file and lib_file.print_time_seconds:
  6008. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6009. except Exception as lookup_err:
  6010. logger.debug(
  6011. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6012. )
  6013. # Enrich with usage tracker results (captured in enclosing scope)
  6014. if usage_results:
  6015. if no_archive_data is None:
  6016. no_archive_data = {}
  6017. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6018. if total_from_usage > 0:
  6019. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6020. no_archive_data["usage_results"] = usage_results
  6021. # Try MQTT remaining_time for print duration when no queue/library data
  6022. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6023. mqtt_remaining = data.get("remaining_time")
  6024. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  6025. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  6026. ps = data.get("status", "completed")
  6027. logger.info(
  6028. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  6029. )
  6030. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6031. await notification_service.on_print_complete(
  6032. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  6033. )
  6034. else:
  6035. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6036. # Send user-specific email if we have a created_by_id
  6037. if no_archive_data and no_archive_data.get("created_by_id"):
  6038. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6039. await _dispatch_user_print_email(
  6040. ps,
  6041. no_archive_data["created_by_id"],
  6042. p_name,
  6043. raw_filename,
  6044. db,
  6045. )
  6046. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  6047. except Exception as e:
  6048. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  6049. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  6050. return
  6051. log_timing("Archive lookup")
  6052. # Update archive status
  6053. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  6054. try:
  6055. async with async_session() as db:
  6056. service = ArchiveService(db)
  6057. status = data.get("status", "completed")
  6058. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  6059. if hms_errors:
  6060. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  6061. failure_reason = derive_failure_reason(status, hms_errors)
  6062. if data.get("_reconciled"):
  6063. # A reconciled completion closes out a stale archive at
  6064. # reconnect — it is not a user action, so don't mislabel it
  6065. # "userCancelled". It shares the stale-cleanup path's key
  6066. # (issue #2974) and records that the real end time is unknown,
  6067. # which is also why its logged duration is 0 (#2592).
  6068. failure_reason = "noStatusUpdate"
  6069. if failure_reason:
  6070. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  6071. elif status == "failed" and hms_errors:
  6072. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  6073. await service.update_archive_status(
  6074. archive_id,
  6075. status=status,
  6076. completed_at=(
  6077. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  6078. ),
  6079. failure_reason=failure_reason,
  6080. )
  6081. logger.info(
  6082. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  6083. )
  6084. await ws_manager.send_archive_updated(
  6085. {
  6086. "id": archive_id,
  6087. "status": status,
  6088. }
  6089. )
  6090. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  6091. # MQTT relay - publish archive updated
  6092. try:
  6093. await mqtt_relay.on_archive_updated(
  6094. archive_id=archive_id,
  6095. print_name=filename or subtask_name,
  6096. status=status,
  6097. )
  6098. except Exception:
  6099. pass # Don't fail if MQTT fails
  6100. except Exception as e:
  6101. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  6102. # Continue with other operations even if archive update fails
  6103. log_timing("Archive status update")
  6104. # Apply finance wallet charge or release reservations once. For all partial
  6105. # terminal states (failed, aborted at the printer display, or cancelled via
  6106. # Bambuddy) use this run's measured spool delta, falling back to the last
  6107. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  6108. # estimate and therefore cannot represent an interrupted run.
  6109. try:
  6110. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  6111. async with async_session() as db:
  6112. from backend.app.models.archive import PrintArchive
  6113. from backend.app.services.finance_billing import apply_print_charge_for_archive
  6114. archive = await db.get(PrintArchive, archive_id)
  6115. if archive and billing_run_id is None:
  6116. billing_run_id = getattr(archive, "billing_run_id", None)
  6117. if archive and archive.created_by_id is None and _print_user_info:
  6118. archive.created_by_id = _print_user_info.get("user_id")
  6119. await db.flush()
  6120. run_status = data.get("status", "completed")
  6121. last_progress = data.get("last_progress")
  6122. if last_progress is None:
  6123. last_progress = data.get("progress")
  6124. actual_run_grams = _compute_run_filament_grams(
  6125. run_status,
  6126. billing_planned_grams,
  6127. last_progress,
  6128. usage_results,
  6129. )
  6130. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  6131. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  6132. charged = await apply_print_charge_for_archive(
  6133. db,
  6134. archive_id,
  6135. charged_user_id=billing_user_id,
  6136. cost_center_id=(
  6137. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  6138. ),
  6139. print_queue_id=queue_item_id,
  6140. print_run_id=billing_run_id,
  6141. base_cost_override=billing_base_cost,
  6142. filament_usage=filament_usage,
  6143. )
  6144. await db.commit()
  6145. if charged:
  6146. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  6147. except Exception as e:
  6148. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  6149. printer_info = printer_manager.get_printer(printer_id)
  6150. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  6151. billing_filename = filename or subtask_name or "Unknown"
  6152. billing_error = str(e)
  6153. try:
  6154. await ws_manager.broadcast(
  6155. {
  6156. "type": "billing_charge_failed",
  6157. "printer_id": printer_id,
  6158. "printer_name": billing_printer_name,
  6159. "filename": billing_filename,
  6160. "archive_id": archive_id,
  6161. }
  6162. )
  6163. except Exception as notification_error:
  6164. logger.error(
  6165. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  6166. archive_id,
  6167. notification_error,
  6168. )
  6169. async def _notify_billing_charge_failed() -> None:
  6170. try:
  6171. async with async_session() as notification_db:
  6172. await notification_service.on_billing_charge_failed(
  6173. printer_id,
  6174. billing_printer_name,
  6175. billing_filename,
  6176. archive_id,
  6177. billing_error,
  6178. notification_db,
  6179. )
  6180. except Exception as provider_error:
  6181. logger.error(
  6182. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  6183. archive_id,
  6184. provider_error,
  6185. exc_info=True,
  6186. )
  6187. spawn_background_task(
  6188. _notify_billing_charge_failed(),
  6189. name=f"billing-charge-failed-{archive_id}",
  6190. )
  6191. log_timing("Finance charge update")
  6192. # Write independent print log entry (separate table, never touches archives)
  6193. try:
  6194. async with async_session() as db:
  6195. from backend.app.models.archive import PrintArchive
  6196. from backend.app.services.print_log import write_log_entry
  6197. archive = await db.get(PrintArchive, archive_id)
  6198. if archive:
  6199. # Back-fill created_by_id on reprint (#730): reprint reuses the
  6200. # source archive row rather than creating a new one, so an
  6201. # archive that was auto-created from a printer-initiated
  6202. # print (created_by_id=NULL) would otherwise stay unattributed
  6203. # forever. When we have a print-session user AND the archive
  6204. # has no attribution yet, credit the current user. Never
  6205. # overwrite an existing attribution — the original uploader
  6206. # keeps ownership.
  6207. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  6208. if archive.created_by_id is None and _print_user_id is not None:
  6209. archive.created_by_id = _print_user_id
  6210. p_info = printer_manager.get_printer(printer_id)
  6211. # Per-run actuals — written to PrintLogEntry so stats reflect
  6212. # what THIS print actually used, not the source archive's
  6213. # first-run values (#1378). Helper handles the partial-print
  6214. # math (failed / cancelled / stopped get scaled to progress
  6215. # or to tracked spool deltas).
  6216. _run_status = data.get("status", "completed")
  6217. # #2614: scope the per-run estimate to the printed plate. For a
  6218. # multi-plate 3MF dispatched one plate at a time, the archive's
  6219. # filament/cost are the whole-file totals; the PrintLogEntry must
  6220. # reflect only this plate. No effect on single-plate archives (the
  6221. # plate estimate equals the whole-file value) or on the tracker
  6222. # path (measured spool deltas win in _compute_run_filament_grams).
  6223. _est_full_path = (
  6224. app_settings.base_dir / archive.file_path if archive.file_path else None
  6225. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6226. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  6227. _run_grams = _compute_run_filament_grams(
  6228. _run_status,
  6229. _est_grams,
  6230. data.get("last_progress", data.get("progress")),
  6231. usage_results,
  6232. )
  6233. # Per-run cost — prefer usage_results sum. For partial prints
  6234. # we deliberately skip the topup-to-estimate logic in
  6235. # usage_tracker (which assumes the print completed); the raw
  6236. # tracked-spool sum is closer to what THIS run actually cost.
  6237. _run_cost: float | None = None
  6238. if usage_results:
  6239. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  6240. if _run_cost is None and _run_status == "completed":
  6241. _run_cost = _est_cost
  6242. await write_log_entry(
  6243. db,
  6244. archive_id=archive.id,
  6245. # Captured by _update_queue_status above; None for
  6246. # printer-initiated prints with no queue row. Batch
  6247. # cost/energy roll-up joins on it (#342).
  6248. queue_item_id=queue_item_id,
  6249. status=_run_status,
  6250. print_name=archive.print_name,
  6251. printer_name=p_info.name if p_info else None,
  6252. printer_id=printer_id,
  6253. started_at=archive.started_at,
  6254. completed_at=archive.completed_at,
  6255. filament_type=archive.filament_type,
  6256. filament_color=archive.filament_color,
  6257. filament_used_grams=_run_grams,
  6258. cost=_run_cost,
  6259. failure_reason=archive.failure_reason,
  6260. thumbnail_path=archive.thumbnail_path,
  6261. created_by_id=archive.created_by_id,
  6262. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  6263. # Reconciled completions have an unknown real end time —
  6264. # log 0 duration instead of the whole disconnect gap (#2592).
  6265. reconciled=bool(data.get("_reconciled")),
  6266. )
  6267. await db.commit()
  6268. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  6269. except Exception as e:
  6270. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  6271. log_timing("Print log entry")
  6272. # Run slow operations as background tasks to avoid blocking the event loop
  6273. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  6274. async def _background_energy_calculation():
  6275. """Calculate and save energy usage in background.
  6276. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  6277. backend restart no longer loses per-print energy data).
  6278. """
  6279. try:
  6280. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  6281. async with async_session() as db:
  6282. from backend.app.models.archive import PrintArchive
  6283. archive = await db.get(PrintArchive, archive_id)
  6284. if archive is None:
  6285. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  6286. return
  6287. starting_kwh = archive.energy_start_kwh
  6288. if starting_kwh is None:
  6289. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  6290. return
  6291. candidates = await energy_plug_candidates(db, printer_id)
  6292. if not candidates:
  6293. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  6294. return
  6295. # Same ordering as the start reading, so the delta below is
  6296. # against the counter that produced `starting_kwh` (#2859).
  6297. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  6298. if selected is None:
  6299. logger.warning(
  6300. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  6301. printer_id,
  6302. ", ".join(plug.name for plug in candidates),
  6303. )
  6304. return
  6305. plug, energy = selected
  6306. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  6307. energy_used = round(energy["total"] - starting_kwh, 4)
  6308. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  6309. if energy_used < 0:
  6310. logger.warning(
  6311. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  6312. archive_id,
  6313. starting_kwh,
  6314. energy["total"],
  6315. )
  6316. return
  6317. from backend.app.api.routes.settings import get_setting
  6318. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  6319. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  6320. energy_cost_value = round(energy_used * cost_per_kwh, 3)
  6321. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  6322. # reprint doesn't visually clobber the source archive's energy data
  6323. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  6324. from sqlalchemy import func
  6325. from backend.app.models.print_log import PrintLogEntry
  6326. existing_runs = await db.scalar(
  6327. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  6328. )
  6329. if (existing_runs or 0) <= 1:
  6330. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  6331. # we just wrote for THIS print. Either way it's the first run.
  6332. archive.energy_kwh = energy_used
  6333. archive.energy_cost = energy_cost_value
  6334. # Backfill the latest PrintLogEntry for this archive with energy
  6335. # (write_log_entry above ran before this background task completed,
  6336. # so energy fields are still NULL on that row).
  6337. latest_run = await db.execute(
  6338. select(PrintLogEntry)
  6339. .where(PrintLogEntry.archive_id == archive_id)
  6340. .order_by(PrintLogEntry.id.desc())
  6341. .limit(1)
  6342. )
  6343. run_row = latest_run.scalar_one_or_none()
  6344. if run_row is not None:
  6345. run_row.energy_kwh = energy_used
  6346. run_row.energy_cost = energy_cost_value
  6347. await db.commit()
  6348. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  6349. except Exception as e:
  6350. logger.warning("[ENERGY-BG] Failed: %s", e)
  6351. async def _background_finish_photo() -> str | None:
  6352. """Capture finish photo in background. Returns photo filename if captured."""
  6353. # #2547: set once this function has raised the plate itself (the
  6354. # timelapse path, where the moment producer returned without doing it).
  6355. # Declared out here so the `finally` can lower it again no matter where
  6356. # the capture below fails.
  6357. plate_restored_z: float | None = None
  6358. try:
  6359. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  6360. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  6361. # Read phase: settings + printer + archive in a short session, released
  6362. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  6363. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  6364. # tens of seconds; holding this session across it pinned one pooled
  6365. # connection idle-in-transaction per finishing print (issue #2572).
  6366. async with async_session() as db:
  6367. from backend.app.api.routes.settings import get_setting
  6368. from backend.app.models.archive import PrintArchive
  6369. from backend.app.models.printer import Printer
  6370. capture_enabled = await get_setting(db, "capture_finish_photo")
  6371. if capture_enabled is not None and capture_enabled.lower() != "true":
  6372. return None
  6373. if not archive_id:
  6374. return None
  6375. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  6376. archive = (
  6377. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6378. ).scalar_one_or_none()
  6379. if not printer or not archive:
  6380. return None
  6381. import uuid
  6382. from datetime import datetime
  6383. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  6384. if not archive.file_path:
  6385. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  6386. archive_dir = resolve_archive_dir(archive)
  6387. photo_filename = None
  6388. # Prefer the timelapse last-frame source when a timelapse was
  6389. # recording — it captures the moment after the toolhead parks
  6390. # but before the bed drops, which the live-camera grab below
  6391. # would miss (#1397). Skipped for external cameras (those have
  6392. # their own framing and don't see a Bambu timelapse). Only
  6393. # runs when the USER explicitly enabled timelapse for this
  6394. # print — #1721 removed Bambuddy's force-on at dispatch
  6395. # because it caused per-layer nozzle parking on Smooth-mode
  6396. # slicer profiles.
  6397. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  6398. printer.external_camera_enabled and printer.external_camera_url
  6399. )
  6400. timelapse_still_pending = False
  6401. if prefer_timelapse_source:
  6402. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  6403. archive_id=archive_id,
  6404. archive_dir=archive_dir,
  6405. rotation=getattr(printer, "camera_rotation", 0),
  6406. )
  6407. # #1721: replacement framing path — on_finish_photo_moment
  6408. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  6409. # parked, bed not yet dropped) and cached the JPEG bytes in
  6410. # _stage22_finish_frames. Consume them now so the saved photo
  6411. # has the better framing instead of the post-bed-drop angle
  6412. # the live-camera fallback below would give.
  6413. if not photo_filename:
  6414. # #1790: on the FINISH-state fallback path the producer
  6415. # task is dispatched back-to-back with this consumer, so
  6416. # a bare pop would race past with an empty result and
  6417. # the RTSP fallback below would collide with the
  6418. # producer's still-in-flight grab (single-client RTSP
  6419. # on Bambu printers). Wait for the producer to finish
  6420. # or give up before touching the cache.
  6421. #
  6422. # #2547: 20s was enough when the producer only ever grabbed a
  6423. # frame. It now also raises the plate first, which costs the
  6424. # settle window before the grab even starts — so the budget has
  6425. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  6426. # under the notification's own photo wait below.
  6427. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  6428. if in_flight is not None:
  6429. try:
  6430. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  6431. except asyncio.TimeoutError:
  6432. logger.warning(
  6433. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  6434. printer_id,
  6435. )
  6436. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  6437. if cached_frame:
  6438. # Already rotated by the producer (#2708) — rotating again
  6439. # here would undo the fix on the banked-frame path, whose
  6440. # bytes reach the cache having been rotated once already.
  6441. photos_dir = archive_dir / "photos"
  6442. photos_dir.mkdir(parents=True, exist_ok=True)
  6443. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6444. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6445. photo_path = photos_dir / photo_filename
  6446. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  6447. logger.info(
  6448. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  6449. photo_filename,
  6450. len(cached_frame),
  6451. )
  6452. # #2547: the timelapse path reaches the live grab below whenever the
  6453. # video hasn't landed in time — the documented usual outcome on
  6454. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  6455. # returned early for those prints without raising the plate, so
  6456. # without this the photo that actually ships in the notification is
  6457. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  6458. # asked us to fix. The archive still gets the better video frame
  6459. # later; this is about the image the user is sent.
  6460. #
  6461. # Gated on `timelapse_was_active` precisely because that is the
  6462. # condition under which the producer skipped. On every other path it
  6463. # has already raised and lowered the plate, and repeating that here
  6464. # would be a second pointless round trip.
  6465. if (
  6466. not photo_filename
  6467. and data.get("timelapse_was_active")
  6468. and not print_dispatch_context.end_gcode_injected(printer_id)
  6469. ):
  6470. try:
  6471. async with async_session() as db:
  6472. from backend.app.api.routes.settings import get_setting
  6473. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6474. if restore_setting is None or restore_setting.lower() == "true":
  6475. max_z = await _max_z_for_current_print(printer_id, data, logger)
  6476. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  6477. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  6478. plate_restored_z = max_z
  6479. except Exception as e:
  6480. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  6481. # Fallback chain: external camera → buffered live frame →
  6482. # fresh RTSP capture. Only runs if the timelapse path above
  6483. # didn't already produce a photo.
  6484. if not photo_filename:
  6485. if printer.external_camera_enabled and printer.external_camera_url:
  6486. logger.info("[PHOTO-BG] Using external camera")
  6487. from backend.app.api.routes.camera import live_frame_for_capture
  6488. from backend.app.services.external_camera import capture_frame
  6489. # #2707: the second half of the finish-photo failure — the
  6490. # pre-capture and this fallback both collided with the live
  6491. # view. None here continues down the fallback chain.
  6492. defer, buffered = live_frame_for_capture(printer_id)
  6493. if defer:
  6494. frame_data = buffered
  6495. else:
  6496. frame_data = await capture_frame(
  6497. printer.external_camera_url,
  6498. printer.external_camera_type or "mjpeg",
  6499. snapshot_url=printer.external_camera_snapshot_url,
  6500. )
  6501. if frame_data:
  6502. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  6503. photos_dir = archive_dir / "photos"
  6504. photos_dir.mkdir(parents=True, exist_ok=True)
  6505. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6506. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6507. photo_path = photos_dir / photo_filename
  6508. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  6509. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  6510. else:
  6511. # Check if camera stream is active - use buffered frame to avoid freeze
  6512. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  6513. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  6514. active_chamber_for_printer = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  6515. buffered_frame = get_buffered_frame(printer_id)
  6516. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  6517. # Use frame from active stream
  6518. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  6519. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  6520. photos_dir = archive_dir / "photos"
  6521. photos_dir.mkdir(parents=True, exist_ok=True)
  6522. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6523. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6524. photo_path = photos_dir / photo_filename
  6525. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  6526. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  6527. else:
  6528. # No active stream - capture new frame
  6529. from backend.app.services.camera import capture_finish_photo
  6530. photo_filename = await capture_finish_photo(
  6531. printer_id=printer_id,
  6532. ip_address=printer.ip_address,
  6533. access_code=printer.access_code,
  6534. model=printer.model,
  6535. archive_dir=archive_dir,
  6536. rotation=getattr(printer, "camera_rotation", 0),
  6537. )
  6538. # Write phase: attach the photo in a fresh short-lived session.
  6539. if photo_filename:
  6540. async with async_session() as db:
  6541. from backend.app.models.archive import PrintArchive
  6542. arch = await db.get(PrintArchive, archive_id)
  6543. if arch is not None:
  6544. photos = arch.photos or []
  6545. photos.append(photo_filename)
  6546. arch.photos = photos
  6547. await db.commit()
  6548. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  6549. # The short wait above is bounded so a slow printer can't hold up
  6550. # the print-complete notification, which is what the caller is
  6551. # blocking on. When it ran out with the video still on its way,
  6552. # keep waiting off to the side and add the better frame to the
  6553. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  6554. # users, whose videos routinely take minutes to transfer, never get
  6555. # the pre-bed-drop framing this path exists to provide.
  6556. #
  6557. # Spawned here rather than at the point the wait gave up: both this
  6558. # function and the upgrade do a read-modify-write on `photos`, and
  6559. # the live-camera fallback above can take tens of seconds. Starting
  6560. # the upgrade before that write means the two can interleave and one
  6561. # silently drops the other's entry, leaving a JPEG on disk that the
  6562. # gallery never lists.
  6563. if timelapse_still_pending:
  6564. spawn_background_task(
  6565. _upgrade_finish_photo_from_timelapse(
  6566. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  6567. ),
  6568. name=f"finish-photo-upgrade-{archive_id}",
  6569. )
  6570. return photo_filename
  6571. except Exception as e:
  6572. logger.warning("[PHOTO-BG] Failed: %s", e)
  6573. return None
  6574. finally:
  6575. # #2547: we raised the plate, so we owe the move back down — even if
  6576. # the capture in between threw. Otherwise the user finds the print
  6577. # pinned under the nozzle.
  6578. if plate_restored_z is not None:
  6579. try:
  6580. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  6581. except Exception as e:
  6582. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6583. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  6584. # Photo capture task - result will be used by notifications
  6585. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  6586. log_timing("Background tasks scheduled (energy, photo)")
  6587. # Also run smart plug, notifications, and maintenance as background tasks
  6588. print_status = data.get("status", "completed")
  6589. async def _background_smart_plug():
  6590. """Handle smart plug automation in background."""
  6591. try:
  6592. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  6593. async with async_session() as db:
  6594. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  6595. logger.info("[AUTO-OFF-BG] Completed")
  6596. except Exception as e:
  6597. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  6598. async def _background_notifications(finish_photo_filename: str | None = None):
  6599. """Send print complete notifications in background."""
  6600. try:
  6601. logger.info(
  6602. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  6603. )
  6604. async with async_session() as db:
  6605. from backend.app.models.archive import PrintArchive
  6606. from backend.app.models.printer import Printer
  6607. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6608. printer = result.scalar_one_or_none()
  6609. printer_name = printer.name if printer else f"Printer {printer_id}"
  6610. archive_data = None
  6611. if archive_id:
  6612. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6613. archive = archive_result.scalar_one_or_none()
  6614. if archive:
  6615. # Actual elapsed time from started_at/completed_at when both are
  6616. # populated (every terminal status sets completed_at after #1198).
  6617. # Falls back to None so the notification path can decide whether to
  6618. # render the slicer estimate as a last resort.
  6619. actual_time_seconds = None
  6620. if archive.started_at and archive.completed_at:
  6621. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  6622. if elapsed > 0:
  6623. actual_time_seconds = int(elapsed)
  6624. archive_data = {
  6625. "print_time_seconds": archive.print_time_seconds,
  6626. "actual_time_seconds": actual_time_seconds,
  6627. "actual_filament_grams": archive.filament_used_grams,
  6628. "failure_reason": archive.failure_reason,
  6629. "created_by_id": archive.created_by_id,
  6630. }
  6631. # Scale filament usage for partial prints
  6632. if print_status != "completed" and archive.filament_used_grams:
  6633. progress = data.get("progress") or 0
  6634. scale = _partial_progress_scale(progress)
  6635. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  6636. archive_data["progress"] = progress
  6637. # Pass per-slot data from archive.extra_data
  6638. if archive.extra_data and archive.extra_data.get("filament_slots"):
  6639. slots = archive.extra_data["filament_slots"]
  6640. if print_status != "completed":
  6641. scale = _partial_progress_scale(data.get("progress"))
  6642. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  6643. archive_data["filament_slots"] = slots
  6644. # Scope project-summed totals down to the plate that was
  6645. # actually printed — see _scope_notification_archive_data_to_plate
  6646. # for the why (#1785).
  6647. archive_data = _scope_notification_archive_data_to_plate(
  6648. archive_data,
  6649. archive.file_path,
  6650. notify_plate_id,
  6651. print_status,
  6652. data.get("progress"),
  6653. app_settings.base_dir,
  6654. )
  6655. # Enrich filament_grams from usage_results when archive has no 3MF data
  6656. if not archive_data.get("actual_filament_grams") and usage_results:
  6657. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6658. if total_from_usage > 0:
  6659. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6660. # Pass usage tracker results for AMS slot info in notifications
  6661. if usage_results:
  6662. archive_data["usage_results"] = usage_results
  6663. # Add finish photo URL and image bytes if available
  6664. if finish_photo_filename:
  6665. from backend.app.api.routes.settings import get_setting
  6666. external_url = await get_setting(db, "external_url")
  6667. if external_url:
  6668. external_url = external_url.rstrip("/")
  6669. archive_data["finish_photo_url"] = (
  6670. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6671. )
  6672. else:
  6673. # Fallback to relative URL (won't work for external services)
  6674. archive_data["finish_photo_url"] = (
  6675. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  6676. )
  6677. # Read finish photo bytes for image attachment (e.g. Pushover)
  6678. try:
  6679. from backend.app.utils.archive_paths import find_archive_photo
  6680. photo_path = find_archive_photo(archive, finish_photo_filename)
  6681. if photo_path is not None:
  6682. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  6683. if len(photo_bytes) <= 2_500_000:
  6684. archive_data["image_data"] = photo_bytes
  6685. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  6686. else:
  6687. logger.warning(
  6688. f"[NOTIFY-BG] Finish photo too large for attachment: "
  6689. f"{len(photo_bytes)} bytes"
  6690. )
  6691. except Exception as e:
  6692. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  6693. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6694. await notification_service.on_print_complete(
  6695. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  6696. )
  6697. else:
  6698. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6699. # Send user-specific email notification
  6700. if archive_data:
  6701. created_by_id = archive_data.get("created_by_id")
  6702. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6703. await _dispatch_user_print_email(
  6704. print_status,
  6705. created_by_id,
  6706. printer_name,
  6707. raw_filename,
  6708. db,
  6709. )
  6710. logger.info("[NOTIFY-BG] Completed")
  6711. except Exception as e:
  6712. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  6713. async def _background_maintenance_check():
  6714. """Check for maintenance due in background."""
  6715. if print_status != "completed":
  6716. return
  6717. try:
  6718. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  6719. async with async_session() as db:
  6720. from backend.app.models.printer import Printer
  6721. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6722. printer = result.scalar_one_or_none()
  6723. printer_name = printer.name if printer else f"Printer {printer_id}"
  6724. await ensure_default_types(db)
  6725. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  6726. items_needing_attention = [
  6727. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  6728. for item in overview.maintenance_items
  6729. if item.enabled and (item.is_due or item.is_warning)
  6730. ]
  6731. if items_needing_attention:
  6732. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  6733. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  6734. # MQTT relay - publish maintenance alerts
  6735. for item in items_needing_attention:
  6736. try:
  6737. await mqtt_relay.on_maintenance_alert(
  6738. printer_id=printer_id,
  6739. printer_name=printer_name,
  6740. maintenance_type=item["name"],
  6741. current_value=0, # Not easily available here
  6742. threshold=0, # Not easily available here
  6743. )
  6744. except Exception:
  6745. pass # Don't fail if MQTT fails
  6746. else:
  6747. logger.info("[MAINT-BG] Completed (no items need attention)")
  6748. except Exception as e:
  6749. logger.warning("[MAINT-BG] Failed: %s", e)
  6750. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  6751. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  6752. # Notification task waits for photo capture to complete first (with timeout).
  6753. # When a timelapse was recording, photo sourcing polls the per-print
  6754. # timelapse for up to 60s (#1397) — extend the budget so the notification
  6755. # carries the correct bed-up photo instead of falling through to the
  6756. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  6757. #
  6758. # #2547: both budgets now have to cover a plate restore as well.
  6759. #
  6760. # Without timelapse, the wait is on the moment producer, which raises the
  6761. # plate before its grab — so this has to outlast that producer's own budget.
  6762. #
  6763. # With timelapse, the capture polls up to
  6764. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  6765. # falls back to a live grab, which is the case that raises the plate. At the
  6766. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  6767. # restore would have moved the plate for a photo nobody waited for.
  6768. photo_wait_timeout = (
  6769. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  6770. if data.get("timelapse_was_active")
  6771. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  6772. )
  6773. async def _photo_then_notify():
  6774. """Wait for photo capture, then send notification with photo URL."""
  6775. finish_photo = None
  6776. try:
  6777. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  6778. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  6779. except TimeoutError:
  6780. logger.warning(
  6781. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  6782. photo_wait_timeout,
  6783. )
  6784. except Exception as e:
  6785. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  6786. try:
  6787. await _background_notifications(finish_photo)
  6788. except Exception as e:
  6789. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  6790. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  6791. # Stitch external camera layer timelapse if session was active
  6792. print_status = data.get("status", "completed")
  6793. async def _background_layer_timelapse():
  6794. """Stitch layer timelapse and attach to archive."""
  6795. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  6796. try:
  6797. if print_status == "completed":
  6798. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  6799. timelapse_path = await tl_complete(printer_id)
  6800. if timelapse_path and archive_id:
  6801. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6802. async with async_session() as db:
  6803. service = ArchiveService(db)
  6804. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6805. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  6806. # Clean up the temp file
  6807. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6808. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6809. elif timelapse_path:
  6810. # Timelapse created but no archive - just clean up
  6811. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6812. else:
  6813. # Print failed or cancelled - cancel timelapse session
  6814. cancel_session(printer_id)
  6815. logger.info(
  6816. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  6817. )
  6818. except Exception as e:
  6819. logger.warning("[LAYER-TL] Failed: %s", e)
  6820. # Try to cancel session on error
  6821. try:
  6822. cancel_session(printer_id)
  6823. except Exception:
  6824. pass # Best-effort timelapse session cancellation on error
  6825. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  6826. log_timing("All background tasks scheduled")
  6827. # Auto-scan for timelapse if recording was active during the print
  6828. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  6829. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  6830. # Schedule timelapse scan as background task with retries
  6831. # The printer needs time to encode the video after print completion
  6832. baseline = _timelapse_baselines.pop(printer_id, None)
  6833. spawn_background_task(
  6834. _scan_for_timelapse_with_retries(archive_id, baseline),
  6835. name=f"scan-timelapse-{archive_id}",
  6836. )
  6837. log_timing("Timelapse scan scheduled")
  6838. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  6839. # AMS sensor history recording
  6840. _ams_history_task: asyncio.Task | None = None
  6841. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  6842. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  6843. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  6844. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  6845. _ams_alarm_cooldown: dict[str, datetime] = {}
  6846. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  6847. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  6848. """Temperature at which the AMS alarm fires, falling back to the display band.
  6849. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  6850. when a notification was sent as well, which is why a room above it made the
  6851. alarm fire once an hour for as long as the weather lasted -- and the only way
  6852. to stop that was to raise the display band and lose the colour that says the
  6853. unit is warm (#2905).
  6854. Unset resolves to the fair threshold, so an install that never sets one is
  6855. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  6856. so that arrives here as a string and is handled by the same branch as any
  6857. other unparseable value -- there is no separate sentinel to keep in sync.
  6858. A non-positive value is refused rather than honoured: zero would alarm
  6859. permanently, and it is far more likely to be a cleared field than a
  6860. deliberate choice.
  6861. """
  6862. if raw_alarm_value is None:
  6863. return fair_threshold
  6864. try:
  6865. value = float(raw_alarm_value)
  6866. except (TypeError, ValueError):
  6867. return fair_threshold
  6868. if not math.isfinite(value) or value <= 0:
  6869. return fair_threshold
  6870. return value
  6871. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  6872. # through a cycle and the cool-down after it (#1802). Stored in the settings
  6873. # table rather than alongside _ams_alarm_cooldown above, because a restart
  6874. # partway through a cool-down would otherwise resume alarming about heat the
  6875. # user asked for — the same internal-timestamp-row pattern as
  6876. # support.py's debug_logging_enabled_at.
  6877. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  6878. # Upper bound on that suppression. The latch normally clears as soon as the unit
  6879. # reads at or below the threshold; see utils.ams_drying for why this cap only
  6880. # matters when it never does.
  6881. AMS_DRYING_GRACE_MINUTES = 120
  6882. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  6883. """Read the persisted per-AMS drying latch, dropping entries out of window.
  6884. Anything older than the grace cap would expire on its next visit anyway, so
  6885. discarding it here costs nothing and stops rows for deleted printers from
  6886. accumulating.
  6887. Stamps ahead of now get two defences, because a box whose clock jumps
  6888. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  6889. ones are discarded outright, and the rest are clamped to now. Without the
  6890. clamp the cap would measure from a moment that has not happened yet and hold
  6891. the alarm quiet for the skew on top of the cap. One unnecessary notification
  6892. after a clock jump is a far better failure than an alarm silently disabled
  6893. for hours.
  6894. """
  6895. from backend.app.models.settings import Settings
  6896. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6897. setting = result.scalar_one_or_none()
  6898. if not setting or not setting.value:
  6899. return {}
  6900. try:
  6901. raw = json.loads(setting.value)
  6902. except (ValueError, TypeError):
  6903. return {} # Corrupted row → no latch, alarms behave as they did before
  6904. if not isinstance(raw, dict):
  6905. return {}
  6906. now = datetime.now(timezone.utc)
  6907. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  6908. latch: dict[str, datetime] = {}
  6909. for key, value in raw.items():
  6910. try:
  6911. stamp = datetime.fromisoformat(str(value))
  6912. except (ValueError, TypeError):
  6913. continue
  6914. if stamp.tzinfo is None:
  6915. stamp = stamp.replace(tzinfo=timezone.utc)
  6916. if not (now - window <= stamp <= now + window):
  6917. continue
  6918. # Nothing may sit in the future: suppression is measured as now minus
  6919. # the stamp, so a stamp ahead of now would extend it by the skew on top
  6920. # of the cap. Clamping the survivors keeps the cap an actual cap.
  6921. latch[str(key)] = min(stamp, now)
  6922. return latch
  6923. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  6924. """Persist the latch, writing only when it actually changed.
  6925. Adds the session change but does not commit — the caller's own commit
  6926. carries it, so the latch lands in the same transaction as the sensor rows
  6927. that produced it.
  6928. """
  6929. from backend.app.models.settings import Settings
  6930. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  6931. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  6932. setting = result.scalar_one_or_none()
  6933. if setting is None:
  6934. # Don't create the row on installs that never dry anything.
  6935. if payload != "{}":
  6936. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  6937. elif setting.value != payload:
  6938. setting.value = payload
  6939. def _ams_has_filament(ams_data: dict) -> bool:
  6940. """True if this AMS unit has at least one tray slot holding filament.
  6941. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  6942. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  6943. still report sensor readings, but those readings are ambient and not
  6944. actionable: no filament to dry, no humidity to push down. #1619 — gate
  6945. humidity/temperature alarms on this check so empty units don't generate
  6946. hourly noise. Sensor history still records regardless so the UI charts
  6947. stay continuous.
  6948. Fallback path inspects the `tray` array's `tray_type` fields for setups
  6949. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  6950. """
  6951. bits = ams_data.get("tray_exist_bits")
  6952. if isinstance(bits, str) and bits.strip():
  6953. try:
  6954. return int(bits, 16) > 0
  6955. except ValueError:
  6956. pass
  6957. trays = ams_data.get("tray")
  6958. if isinstance(trays, list):
  6959. return any(
  6960. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  6961. )
  6962. return False
  6963. async def record_ams_history():
  6964. """Background task to record AMS humidity and temperature data."""
  6965. logger = logging.getLogger(__name__)
  6966. # Wait a short time for MQTT connections to establish on startup
  6967. await asyncio.sleep(10)
  6968. while True:
  6969. try:
  6970. from backend.app.models.ams_history import AMSSensorHistory
  6971. from backend.app.models.printer import Printer
  6972. from backend.app.models.settings import Settings
  6973. async with async_session() as db:
  6974. # Get all active printers
  6975. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  6976. printers = result.scalars().all()
  6977. # Get alarm thresholds from settings
  6978. humidity_threshold = 60.0 # Default: fair threshold
  6979. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  6980. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  6981. setting = result.scalar_one_or_none()
  6982. if setting:
  6983. try:
  6984. humidity_threshold = float(setting.value)
  6985. except (ValueError, TypeError):
  6986. pass # Keep default threshold if stored value is invalid
  6987. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  6988. setting = result.scalar_one_or_none()
  6989. if setting:
  6990. try:
  6991. temp_fair_threshold = float(setting.value)
  6992. except (ValueError, TypeError):
  6993. pass # Keep default threshold if stored value is invalid
  6994. # The alarm gets its own threshold, seeded from the resolved fair
  6995. # value so an install that has never set one behaves exactly as
  6996. # it did before (#2905). ams_temp_fair decides when the card turns
  6997. # amber; 35 C is a reasonable place to change a colour and not a
  6998. # reasonable place to page someone. A room above it makes the
  6999. # alarm fire once an hour for as long as the weather lasts, and
  7000. # the only way to stop it was to raise the display band and lose
  7001. # the colour that says the unit is warm.
  7002. #
  7003. # An unset value is stored as the literal "None", which the except
  7004. # below swallows the same way it swallows garbage -- so the
  7005. # fallback costs nothing and needs no sentinel of its own.
  7006. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  7007. setting = result.scalar_one_or_none()
  7008. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  7009. temp_fair_threshold, setting.value if setting else None
  7010. )
  7011. # Per-filament humidity threshold overrides (#1605) — resolved
  7012. # per-AMS below from the loaded tray types. Reuses the same
  7013. # resolver as the auto-drying scheduler so behavior stays in
  7014. # lockstep across both consumers.
  7015. from backend.app.services.print_scheduler import PrintScheduler
  7016. per_type_humidity_thresholds: dict[str, int] = {}
  7017. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  7018. setting = result.scalar_one_or_none()
  7019. if setting and setting.value:
  7020. try:
  7021. raw = json.loads(setting.value)
  7022. if isinstance(raw, dict):
  7023. for k, v in raw.items():
  7024. try:
  7025. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  7026. v
  7027. )
  7028. except (TypeError, ValueError):
  7029. continue
  7030. except (ValueError, TypeError):
  7031. pass # Invalid JSON → no overrides, fall through to global threshold
  7032. # Per-AMS drying latch (#1802), loaded once per pass and written
  7033. # back below only if a unit changed it.
  7034. drying_latch = await _load_ams_drying_latch(db)
  7035. drying_latch_before = dict(drying_latch)
  7036. recorded_count = 0
  7037. for printer in printers:
  7038. # Get current state from printer manager
  7039. state = printer_manager.get_status(printer.id)
  7040. if not state or not state.connected or not state.raw_data:
  7041. continue # Skip disconnected printers - don't use stale data
  7042. raw_data = state.raw_data
  7043. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  7044. continue
  7045. # Record data for each AMS unit
  7046. for ams_data in raw_data["ams"]:
  7047. ams_id = int(ams_data.get("id", 0))
  7048. # Get humidity (prefer humidity_raw)
  7049. humidity_raw = ams_data.get("humidity_raw")
  7050. humidity_idx = ams_data.get("humidity")
  7051. humidity = None
  7052. if humidity_raw is not None:
  7053. try:
  7054. humidity = float(humidity_raw)
  7055. except (ValueError, TypeError):
  7056. pass # Skip unparseable humidity; will try fallback
  7057. if humidity is None and humidity_idx is not None:
  7058. try:
  7059. humidity = float(humidity_idx)
  7060. except (ValueError, TypeError):
  7061. pass # Skip unparseable humidity index value
  7062. # Get temperature
  7063. temperature = None
  7064. temp_str = ams_data.get("temp")
  7065. if temp_str is not None:
  7066. try:
  7067. temperature = float(temp_str)
  7068. except (ValueError, TypeError):
  7069. pass # Skip unparseable temperature value
  7070. # Skip if no data
  7071. if humidity is None and temperature is None:
  7072. continue
  7073. # Record the data point
  7074. history = AMSSensorHistory(
  7075. printer_id=printer.id,
  7076. ams_id=ams_id,
  7077. humidity=humidity,
  7078. humidity_raw=float(humidity_raw) if humidity_raw else None,
  7079. temperature=temperature,
  7080. )
  7081. db.add(history)
  7082. recorded_count += 1
  7083. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  7084. is_ams_ht = ams_id >= 128
  7085. if is_ams_ht:
  7086. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  7087. else:
  7088. ams_label = f"AMS-{chr(65 + ams_id)}"
  7089. # Skip alarm dispatch for empty AMS units — humidity /
  7090. # temperature readings are ambient with no filament to
  7091. # protect, and the hourly notification just becomes
  7092. # noise. Sensor history was already recorded above so
  7093. # the UI charts stay continuous (#1619). Per-AMS check
  7094. # so a multi-AMS setup with one loaded + one empty
  7095. # still alarms on the loaded unit.
  7096. if not _ams_has_filament(ams_data):
  7097. continue
  7098. # Resolve per-filament humidity threshold for this AMS
  7099. # unit (#1605). Falls back to the global ams_humidity_fair
  7100. # when no per-type overrides are configured.
  7101. trays = ams_data.get("tray", []) or []
  7102. effective_humidity_threshold = float(
  7103. PrintScheduler.resolve_humidity_threshold(
  7104. trays, per_type_humidity_thresholds, int(humidity_threshold)
  7105. )
  7106. )
  7107. # Check humidity alarm (only if above threshold)
  7108. if humidity is not None and humidity > effective_humidity_threshold:
  7109. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  7110. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7111. now = datetime.now(timezone.utc)
  7112. if (
  7113. last_alarm is None
  7114. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7115. ):
  7116. _ams_alarm_cooldown[cooldown_key] = now
  7117. logger.info(
  7118. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  7119. )
  7120. try:
  7121. # Call different notification method based on AMS type
  7122. if is_ams_ht:
  7123. await notification_service.on_ams_ht_humidity_high(
  7124. printer.id,
  7125. printer.name,
  7126. ams_label,
  7127. humidity,
  7128. effective_humidity_threshold,
  7129. db,
  7130. )
  7131. else:
  7132. await notification_service.on_ams_humidity_high(
  7133. printer.id,
  7134. printer.name,
  7135. ams_label,
  7136. humidity,
  7137. effective_humidity_threshold,
  7138. db,
  7139. )
  7140. except Exception as e:
  7141. logger.warning("Failed to send humidity alarm: %s", e)
  7142. # A drying cycle heats the unit far past ams_temp_fair on
  7143. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  7144. # AMS-HT, against a 35 C default — so the alarm fired
  7145. # once an hour for the whole cycle and kept firing while
  7146. # the unit cooled back down (#1802). Latch on the
  7147. # firmware's own drying state and hold until the reading
  7148. # returns to normal. Humidity is deliberately left alone:
  7149. # it falls during drying, which is the whole point.
  7150. latch_key = f"{printer.id}:{ams_id}"
  7151. # The latch releases at `threshold`, so it takes the alarm
  7152. # number too. Handing it the display band would strand the
  7153. # latch on any unit that settles back above it -- a room
  7154. # where the AMS rests at 37.7 C never returns under a 35 C
  7155. # band, so the latch could only expire on the grace cap
  7156. # rather than releasing when the unit had actually cooled.
  7157. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  7158. drying_active=is_drying_active(ams_data),
  7159. temperature=temperature,
  7160. threshold=temp_alarm_threshold,
  7161. latched_at=drying_latch.get(latch_key),
  7162. now=datetime.now(timezone.utc),
  7163. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  7164. )
  7165. if new_latch is None:
  7166. drying_latch.pop(latch_key, None)
  7167. else:
  7168. drying_latch[latch_key] = new_latch
  7169. # Check temperature alarm (only if above threshold)
  7170. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  7171. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  7172. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  7173. now = datetime.now(timezone.utc)
  7174. if (
  7175. last_alarm is None
  7176. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  7177. ):
  7178. _ams_alarm_cooldown[cooldown_key] = now
  7179. logger.info(
  7180. f"Sending temperature alarm for {printer.name} {ams_label}: "
  7181. f"{temperature}°C > {temp_alarm_threshold}°C"
  7182. )
  7183. try:
  7184. # Call different notification method based on AMS type
  7185. if is_ams_ht:
  7186. # The reported threshold has to be the one
  7187. # that fired, or the message says "> 35 °C"
  7188. # while firing at 45.
  7189. await notification_service.on_ams_ht_temperature_high(
  7190. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7191. )
  7192. else:
  7193. await notification_service.on_ams_temperature_high(
  7194. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  7195. )
  7196. except Exception as e:
  7197. logger.warning("Failed to send temperature alarm: %s", e)
  7198. if drying_latch != drying_latch_before:
  7199. await _save_ams_drying_latch(db, drying_latch)
  7200. await db.commit()
  7201. if recorded_count > 0:
  7202. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  7203. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  7204. global _ams_cleanup_counter
  7205. _ams_cleanup_counter += 1
  7206. if _ams_cleanup_counter >= 288:
  7207. _ams_cleanup_counter = 0
  7208. # Get retention days from settings
  7209. from backend.app.models.settings import Settings
  7210. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  7211. setting = result.scalar_one_or_none()
  7212. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  7213. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7214. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  7215. await db.commit()
  7216. if result.rowcount > 0:
  7217. logger.info(
  7218. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  7219. )
  7220. # Wait until next recording interval
  7221. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  7222. except asyncio.CancelledError:
  7223. break
  7224. except Exception as e:
  7225. logger.warning("AMS history recording failed: %s", e)
  7226. await asyncio.sleep(60) # Wait a bit before retrying
  7227. def start_ams_history_recording():
  7228. """Start the AMS history recording background task."""
  7229. global _ams_history_task
  7230. if _ams_history_task is None:
  7231. _ams_history_task = asyncio.create_task(record_ams_history())
  7232. logging.getLogger(__name__).info("AMS history recording started")
  7233. def stop_ams_history_recording():
  7234. """Stop the AMS history recording background task."""
  7235. global _ams_history_task
  7236. if _ams_history_task:
  7237. _ams_history_task.cancel()
  7238. _ams_history_task = None
  7239. logging.getLogger(__name__).info("AMS history recording stopped")
  7240. # Printer sensor history recording (nozzle / bed / chamber)
  7241. _printer_sensor_history_task: asyncio.Task | None = None
  7242. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  7243. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  7244. _printer_sensor_cleanup_counter = 0
  7245. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  7246. # MQTT parser writes, so we don't need to handle per-model field aliases here
  7247. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  7248. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  7249. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  7250. _SENSOR_TARGET_KEYS = {
  7251. "nozzle": "nozzle_target",
  7252. "nozzle_2": "nozzle_2_target",
  7253. "bed": "bed_target",
  7254. "chamber": "chamber_target",
  7255. }
  7256. async def record_printer_sensor_history():
  7257. """Background task to record nozzle / bed / chamber readings.
  7258. Pulls from `state.temperatures` (already normalised across all printer
  7259. models by the MQTT parser) rather than re-parsing raw_data, so we get
  7260. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  7261. """
  7262. logger = logging.getLogger(__name__)
  7263. await asyncio.sleep(10)
  7264. while True:
  7265. try:
  7266. from backend.app.models.printer import Printer
  7267. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  7268. from backend.app.models.settings import Settings
  7269. async with async_session() as db:
  7270. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7271. printers = result.scalars().all()
  7272. recorded_count = 0
  7273. for printer in printers:
  7274. state = printer_manager.get_status(printer.id)
  7275. if not state or not state.connected:
  7276. continue
  7277. temps = getattr(state, "temperatures", None) or {}
  7278. if not isinstance(temps, dict):
  7279. continue
  7280. for kind in _SENSOR_KINDS:
  7281. if kind not in temps:
  7282. continue
  7283. try:
  7284. value = float(temps[kind])
  7285. except (ValueError, TypeError):
  7286. continue
  7287. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  7288. target_val: float | None = None
  7289. if target_raw is not None:
  7290. try:
  7291. target_val = float(target_raw)
  7292. except (ValueError, TypeError):
  7293. target_val = None
  7294. db.add(
  7295. PrinterSensorHistory(
  7296. printer_id=printer.id,
  7297. sensor_kind=kind,
  7298. value=value,
  7299. target=target_val,
  7300. )
  7301. )
  7302. recorded_count += 1
  7303. await db.commit()
  7304. if recorded_count > 0:
  7305. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  7306. # Periodic cleanup — once every ~24h at this interval.
  7307. global _printer_sensor_cleanup_counter
  7308. _printer_sensor_cleanup_counter += 1
  7309. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  7310. if _printer_sensor_cleanup_counter >= cleanup_every:
  7311. _printer_sensor_cleanup_counter = 0
  7312. result = await db.execute(
  7313. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  7314. )
  7315. setting = result.scalar_one_or_none()
  7316. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  7317. cutoff = utcnow_naive() - timedelta(days=retention_days)
  7318. cleanup = await db.execute(
  7319. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  7320. )
  7321. await db.commit()
  7322. if cleanup.rowcount > 0:
  7323. logger.info(
  7324. "Cleaned up %s old printer sensor history entries (older than %s days)",
  7325. cleanup.rowcount,
  7326. retention_days,
  7327. )
  7328. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  7329. except asyncio.CancelledError:
  7330. break
  7331. except Exception as e:
  7332. logger.warning("Printer sensor history recording failed: %s", e)
  7333. await asyncio.sleep(60)
  7334. def start_printer_sensor_history_recording():
  7335. global _printer_sensor_history_task
  7336. if _printer_sensor_history_task is None:
  7337. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  7338. logging.getLogger(__name__).info("Printer sensor history recording started")
  7339. def stop_printer_sensor_history_recording():
  7340. global _printer_sensor_history_task
  7341. if _printer_sensor_history_task:
  7342. _printer_sensor_history_task.cancel()
  7343. _printer_sensor_history_task = None
  7344. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  7345. # Printer runtime tracking
  7346. _runtime_tracking_task: asyncio.Task | None = None
  7347. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  7348. async def track_printer_runtime():
  7349. """Background task to track printer active runtime (RUNNING state only).
  7350. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  7351. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  7352. which track mechanical wear. Pause time has no motion and no wear, so
  7353. counting it inflates maintenance warnings (#1521).
  7354. """
  7355. logger = logging.getLogger(__name__)
  7356. # Wait for MQTT connections to establish on startup
  7357. await asyncio.sleep(15)
  7358. while True:
  7359. try:
  7360. from backend.app.models.printer import Printer
  7361. # Fetch printer IDs in a short-lived read-only session
  7362. async with async_session() as db:
  7363. result = await db.execute(
  7364. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  7365. Printer.is_active.is_(True)
  7366. )
  7367. )
  7368. printer_rows = result.all()
  7369. now = datetime.now(timezone.utc)
  7370. updated_count = 0
  7371. # Update each printer in its own short session to minimise write-lock
  7372. # hold time and avoid blocking critical commits like queue status
  7373. # updates (#897).
  7374. for pid, pname, runtime_secs, last_update in printer_rows:
  7375. state = printer_manager.get_status(pid)
  7376. if not state:
  7377. logger.debug("[%s] Runtime tracking: no state available", pname)
  7378. continue
  7379. if not state.connected:
  7380. logger.debug("[%s] Runtime tracking: not connected", pname)
  7381. continue
  7382. needs_commit = False
  7383. new_runtime = runtime_secs
  7384. new_last_update = last_update
  7385. if state.state == "RUNNING":
  7386. if last_update:
  7387. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  7388. elapsed = (now - lu).total_seconds()
  7389. if elapsed > 0:
  7390. new_runtime = runtime_secs + int(elapsed)
  7391. updated_count += 1
  7392. needs_commit = True
  7393. logger.debug(
  7394. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  7395. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  7396. )
  7397. else:
  7398. needs_commit = True
  7399. logger.debug("[%s] Runtime tracking: first active detection", pname)
  7400. new_last_update = now
  7401. else:
  7402. if last_update is not None:
  7403. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  7404. new_last_update = None
  7405. needs_commit = True
  7406. if needs_commit:
  7407. try:
  7408. async with async_session() as db:
  7409. result = await db.execute(select(Printer).where(Printer.id == pid))
  7410. printer = result.scalar_one_or_none()
  7411. if printer:
  7412. printer.runtime_seconds = new_runtime
  7413. printer.last_runtime_update = new_last_update
  7414. await db.commit()
  7415. except Exception as e:
  7416. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  7417. if updated_count > 0:
  7418. logger.debug("Updated runtime for %s printer(s)", updated_count)
  7419. except asyncio.CancelledError:
  7420. logger.info("Runtime tracking cancelled")
  7421. break
  7422. except Exception as e:
  7423. logger.warning("Runtime tracking failed: %s", e)
  7424. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  7425. def start_runtime_tracking():
  7426. """Start the printer runtime tracking background task."""
  7427. global _runtime_tracking_task
  7428. if _runtime_tracking_task is None:
  7429. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  7430. logging.getLogger(__name__).info("Printer runtime tracking started")
  7431. def stop_runtime_tracking():
  7432. """Stop the printer runtime tracking background task."""
  7433. global _runtime_tracking_task
  7434. if _runtime_tracking_task:
  7435. _runtime_tracking_task.cancel()
  7436. _runtime_tracking_task = None
  7437. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  7438. # SpoolBuddy device watchdog
  7439. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  7440. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  7441. async def _spoolbuddy_watchdog_loop():
  7442. """Periodic check for SpoolBuddy devices that have gone offline."""
  7443. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  7444. while True:
  7445. try:
  7446. await spoolbuddy_watchdog()
  7447. except asyncio.CancelledError:
  7448. break
  7449. except Exception as e:
  7450. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  7451. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  7452. def start_spoolbuddy_watchdog():
  7453. global _spoolbuddy_watchdog_task
  7454. if _spoolbuddy_watchdog_task is None:
  7455. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  7456. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  7457. def stop_spoolbuddy_watchdog():
  7458. global _spoolbuddy_watchdog_task
  7459. if _spoolbuddy_watchdog_task:
  7460. _spoolbuddy_watchdog_task.cancel()
  7461. _spoolbuddy_watchdog_task = None
  7462. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  7463. # Dead-MQTT-session recovery
  7464. #
  7465. # check_staleness() covers the "connected but silent" half-broken session. It
  7466. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  7467. # is the only thing left watching at that point. When paho stops making
  7468. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  7469. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  7470. # offline with the UI open the whole time, recovered only when something
  7471. # happened to nudge it.
  7472. #
  7473. # This loop is that backstop. It only touches printers that had a working
  7474. # session and lost it, and only when the MQTT port still answers — a printer
  7475. # that is simply switched off is left to paho, since rebuilding a client
  7476. # against an unreachable host achieves nothing and would fill the log every
  7477. # night.
  7478. _connection_watchdog_task: asyncio.Task | None = None
  7479. CONNECTION_WATCHDOG_INTERVAL = 60
  7480. # How long a printer must have been silent before we stop trusting paho.
  7481. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  7482. # so a session that is recovering on its own is never interrupted.
  7483. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  7484. # Per-printer floor between rebuild attempts.
  7485. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  7486. _connection_watchdog_last_attempt: dict[int, float] = {}
  7487. async def _recover_dead_printer_sessions() -> int:
  7488. """Rebuild MQTT clients that have been offline too long to still be trying.
  7489. Returns the number of printers a rebuild was attempted for (for tests and
  7490. for the caller's logging). Never raises: one unreachable printer must not
  7491. stop the sweep for the rest of the farm.
  7492. """
  7493. logger = logging.getLogger(__name__)
  7494. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  7495. now = time.monotonic()
  7496. recovered = 0
  7497. for printer_id, client in list(printer_manager._clients.items()):
  7498. try:
  7499. if client.state.connected:
  7500. _connection_watchdog_last_attempt.pop(printer_id, None)
  7501. continue
  7502. # Time since the last inbound message is the age of the last known
  7503. # good session — no extra bookkeeping needed, and it is the same
  7504. # clock is_stale() reads. 0 means this client has never had one:
  7505. # that is the initial-connect path, where paho retrying is the
  7506. # correct and only behaviour, so leave it be.
  7507. last_msg = client._last_message_time
  7508. if not last_msg:
  7509. continue
  7510. offline_for = time.time() - last_msg
  7511. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  7512. continue
  7513. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  7514. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  7515. continue
  7516. if not await check_port(client.ip_address, PORT_MQTT):
  7517. # Switched off, unplugged, or off the network. Paho's retry is
  7518. # the right handler; say so at debug level and move on.
  7519. logger.debug(
  7520. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  7521. "— leaving the reconnect to paho",
  7522. printer_id,
  7523. offline_for,
  7524. )
  7525. _connection_watchdog_last_attempt[printer_id] = now
  7526. continue
  7527. _connection_watchdog_last_attempt[printer_id] = now
  7528. recovered += 1
  7529. logger.warning(
  7530. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  7531. "rebuilding the client with a fresh session (last connect error: %s)",
  7532. printer_id,
  7533. offline_for,
  7534. PORT_MQTT,
  7535. client.last_connect_error or "none recorded",
  7536. )
  7537. # Async context, so this takes the hard-reset path: fresh client_id,
  7538. # paho's QoS 1 queue dropped. That matters — a project_file left
  7539. # unacked on the dead session would otherwise replay into the new
  7540. # one and trip 0500_4003 on the printer (#1136).
  7541. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  7542. except Exception as e:
  7543. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  7544. return recovered
  7545. async def _connection_watchdog_loop():
  7546. logger = logging.getLogger(__name__)
  7547. # Let the initial connects settle before judging anyone offline.
  7548. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  7549. while True:
  7550. try:
  7551. await _recover_dead_printer_sessions()
  7552. except asyncio.CancelledError:
  7553. break
  7554. except Exception as e:
  7555. logger.warning("Connection watchdog sweep failed: %s", e)
  7556. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  7557. def start_connection_watchdog():
  7558. global _connection_watchdog_task
  7559. if _connection_watchdog_task is None:
  7560. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  7561. logging.getLogger(__name__).info("Printer connection watchdog started")
  7562. def stop_connection_watchdog():
  7563. global _connection_watchdog_task
  7564. if _connection_watchdog_task:
  7565. _connection_watchdog_task.cancel()
  7566. _connection_watchdog_task = None
  7567. _connection_watchdog_last_attempt.clear()
  7568. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  7569. # Camera stream orphan cleanup
  7570. _camera_cleanup_task: asyncio.Task | None = None
  7571. CAMERA_CLEANUP_INTERVAL = 60
  7572. async def _camera_cleanup_loop():
  7573. """Periodically clean up orphaned ffmpeg processes."""
  7574. from backend.app.api.routes.camera import cleanup_orphaned_streams
  7575. while True:
  7576. try:
  7577. await cleanup_orphaned_streams()
  7578. except asyncio.CancelledError:
  7579. break
  7580. except Exception as e:
  7581. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  7582. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  7583. def start_camera_cleanup():
  7584. global _camera_cleanup_task
  7585. if _camera_cleanup_task is None:
  7586. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  7587. logging.getLogger(__name__).info("Camera stream cleanup started")
  7588. def stop_camera_cleanup():
  7589. global _camera_cleanup_task
  7590. if _camera_cleanup_task:
  7591. _camera_cleanup_task.cancel()
  7592. _camera_cleanup_task = None
  7593. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  7594. # ---------------------------------------------------------------------------
  7595. # Expected-print TTL eviction
  7596. # ---------------------------------------------------------------------------
  7597. def _evict_stale_expected_prints() -> None:
  7598. """Remove entries from _expected_prints / _expected_print_creators that are
  7599. older than _EXPECTED_PRINT_TTL_SECONDS.
  7600. This prevents unbounded growth when a print is registered (via
  7601. register_expected_print) but on_print_start never fires — e.g. because the
  7602. printer disconnects, the app restarts, or the print is started directly from
  7603. the printer panel without going through the queue.
  7604. """
  7605. # Use monotonic time so the TTL is unaffected by system clock adjustments
  7606. # (e.g. NTP sync, DST changes).
  7607. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  7608. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  7609. if not stale_keys:
  7610. return
  7611. evicted_archive_ids: set[int] = set()
  7612. for key in stale_keys:
  7613. archive_id = _expected_prints.pop(key, None)
  7614. if archive_id is not None:
  7615. evicted_archive_ids.add(archive_id)
  7616. _expected_print_creators.pop(key, None)
  7617. _expected_print_registered_at.pop(key, None)
  7618. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  7619. # that have no remaining live keys in _expected_prints (all variants
  7620. # were just evicted).
  7621. live_archive_ids = set(_expected_prints.values())
  7622. for archive_id in evicted_archive_ids:
  7623. if archive_id not in live_archive_ids:
  7624. _print_ams_mappings.pop(archive_id, None)
  7625. _print_cost_center_ids.pop(archive_id, None)
  7626. _print_plate_ids.pop(archive_id, None)
  7627. logging.getLogger(__name__).info(
  7628. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  7629. )
  7630. async def _expected_prints_cleanup_loop() -> None:
  7631. """Background task: periodically evict stale expected-print entries."""
  7632. while True:
  7633. try:
  7634. _evict_stale_expected_prints()
  7635. except asyncio.CancelledError:
  7636. raise
  7637. except Exception as e:
  7638. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  7639. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  7640. def start_expected_prints_cleanup() -> None:
  7641. global _expected_prints_cleanup_task
  7642. if _expected_prints_cleanup_task is None:
  7643. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  7644. logging.getLogger(__name__).info("Expected prints cleanup started")
  7645. def stop_expected_prints_cleanup() -> None:
  7646. global _expected_prints_cleanup_task
  7647. if _expected_prints_cleanup_task:
  7648. _expected_prints_cleanup_task.cancel()
  7649. _expected_prints_cleanup_task = None
  7650. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  7651. # ---------------------------------------------------------------------------
  7652. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  7653. # ---------------------------------------------------------------------------
  7654. _auth_cleanup_task: asyncio.Task | None = None
  7655. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  7656. async def _run_auth_cleanup() -> None:
  7657. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  7658. from backend.app.core.database import async_session
  7659. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  7660. from backend.app.models.user_totp import UserTOTP
  7661. now = datetime.now(timezone.utc)
  7662. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  7663. try:
  7664. async with async_session() as db:
  7665. stale_cutoff = now - timedelta(hours=1)
  7666. result = await db.execute(
  7667. select(UserTOTP).where(
  7668. UserTOTP.is_enabled.is_(False),
  7669. UserTOTP.created_at < stale_cutoff,
  7670. )
  7671. )
  7672. stale_records = result.scalars().all()
  7673. if stale_records:
  7674. for rec in stale_records:
  7675. await db.delete(rec)
  7676. await db.commit()
  7677. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  7678. except Exception as e:
  7679. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  7680. # Remove expired revoked-JTI entries (they are no longer needed once the
  7681. # original token's exp has passed — the token would be rejected by JWT
  7682. # signature verification regardless).
  7683. try:
  7684. async with async_session() as db:
  7685. await db.execute(
  7686. delete(AuthEphemeralToken).where(
  7687. AuthEphemeralToken.token_type == "revoked_jti",
  7688. AuthEphemeralToken.expires_at < now,
  7689. )
  7690. )
  7691. await db.commit()
  7692. except Exception as e:
  7693. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  7694. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  7695. # Events outside this window can never affect rate-limit decisions — they only
  7696. # consume DB space. Use the same window constant as the rate limiter so the
  7697. # two are always in sync.
  7698. try:
  7699. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  7700. async with async_session() as db:
  7701. await db.execute(
  7702. delete(AuthRateLimitEvent).where(
  7703. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  7704. )
  7705. )
  7706. await db.commit()
  7707. except Exception as e:
  7708. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  7709. async def _auth_cleanup_loop() -> None:
  7710. """Periodic background task: run auth cleanup every hour."""
  7711. while True:
  7712. try:
  7713. await _run_auth_cleanup()
  7714. except asyncio.CancelledError:
  7715. break
  7716. except Exception as e:
  7717. logging.warning("Auth cleanup loop error: %s", e)
  7718. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  7719. def start_auth_cleanup() -> None:
  7720. global _auth_cleanup_task
  7721. if _auth_cleanup_task is None:
  7722. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  7723. logging.getLogger(__name__).info("Auth periodic cleanup started")
  7724. def stop_auth_cleanup() -> None:
  7725. global _auth_cleanup_task
  7726. if _auth_cleanup_task:
  7727. _auth_cleanup_task.cancel()
  7728. _auth_cleanup_task = None
  7729. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  7730. @asynccontextmanager
  7731. async def lifespan(app: FastAPI):
  7732. # Startup
  7733. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  7734. # anything else can spawn tasks that might trip it.
  7735. from backend.app.core.asyncio_handlers import install_proactor_reset_filter
  7736. install_proactor_reset_filter()
  7737. await init_db()
  7738. # Browser download tokens expire after five minutes. Remove abandoned
  7739. # prepared ZIPs at startup as well as before each new preparation so a
  7740. # quiet appliance cannot retain an unusable bundle indefinitely.
  7741. try:
  7742. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  7743. await prune_stale_printer_file_bundles()
  7744. except Exception as exc:
  7745. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  7746. # After migrations, so the is_env_managed column exists. Never raises --
  7747. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  7748. # startup (see apply_env_oidc_provider).
  7749. from backend.app.core.oidc_env import apply_env_oidc_provider
  7750. async with async_session() as oidc_db:
  7751. await apply_env_oidc_provider(oidc_db)
  7752. # Close out batches that finished before `completed` was a reachable status
  7753. # (#342). Without this the Batches tab opens on every batch created since
  7754. # the feature shipped, all still marked active. Never blocks startup.
  7755. try:
  7756. from backend.app.services.print_batch import backfill_batch_statuses
  7757. async with async_session() as batch_db:
  7758. await backfill_batch_statuses(batch_db)
  7759. except Exception as exc:
  7760. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  7761. # Register an app-scoped httpx client for Bambu Cloud services so
  7762. # per-request BambuCloudService instances reuse the same connection pool
  7763. # (important for routes like /cloud/filament-info that chain many
  7764. # get_setting_detail calls). The shared client stores no region/token
  7765. # state, so the per-request ownership pattern that fixed the region-bleed
  7766. # bug is preserved.
  7767. import httpx as _httpx
  7768. from backend.app.services.bambu_cloud import set_shared_http_client
  7769. from backend.app.services.makerworld import (
  7770. set_shared_http_client as set_shared_makerworld_http_client,
  7771. )
  7772. from backend.app.services.orca_cloud import (
  7773. set_shared_http_client as set_shared_orca_http_client,
  7774. )
  7775. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  7776. set_shared_http_client(_shared_cloud_http_client)
  7777. # Reuse the same connection pool for MakerWorld — different host, same
  7778. # keep-alive pool saves a TLS handshake per request.
  7779. set_shared_makerworld_http_client(_shared_cloud_http_client)
  7780. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  7781. # each spun up (and never closed) its own client, leaking sockets.
  7782. set_shared_orca_http_client(_shared_cloud_http_client)
  7783. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  7784. # This can happen when a print was cancelled mid-print on versions before this fix.
  7785. try:
  7786. async with async_session() as db:
  7787. from backend.app.models.print_queue import PrintQueueItem
  7788. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  7789. aborted_items = result.scalars().all()
  7790. if aborted_items:
  7791. for item in aborted_items:
  7792. item.status = "cancelled"
  7793. await db.commit()
  7794. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  7795. except Exception as e:
  7796. logging.warning("Failed to fix aborted queue items: %s", e)
  7797. # Restore debug logging state from previous session
  7798. await init_debug_logging()
  7799. # Set up printer manager callbacks
  7800. loop = asyncio.get_event_loop()
  7801. printer_manager.set_event_loop(loop)
  7802. printer_manager.set_status_change_callback(on_printer_status_change)
  7803. printer_manager.set_print_start_callback(on_print_start)
  7804. printer_manager.set_print_complete_callback(on_print_complete)
  7805. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  7806. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  7807. printer_manager.set_ams_change_callback(on_ams_change)
  7808. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  7809. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  7810. await printer_manager.load_awaiting_plate_clear_from_db()
  7811. # Layer change callback for external camera timelapse
  7812. async def on_layer_change(printer_id: int, layer_num: int):
  7813. """Capture timelapse frame on layer change + first layer notification."""
  7814. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  7815. await tl_layer_change(printer_id, layer_num)
  7816. # #1867: bank a recent in-print frame so the finish-photo path has a
  7817. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  7818. # #2547 added `on_print_progress` as a second driver — this one alone
  7819. # stops firing once the final layer begins.
  7820. await _maybe_bank_inprint_frame(printer_id, layer_num)
  7821. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  7822. # Gate on actual printing state — Bambu firmware ticks layer_num during
  7823. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  7824. # nozzle clean), so a bare layer_num check can fire minutes before the
  7825. # first real extrusion. We require gcode_state == RUNNING and
  7826. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  7827. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  7828. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  7829. # edge fires later; _first_layer_notified stays clear until we actually send
  7830. # so a deferred re-evaluation can win. See issue #1837.
  7831. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  7832. client = printer_manager.get_client(printer_id)
  7833. state = client.state if client else None
  7834. if not state or state.state != "RUNNING":
  7835. return
  7836. if state.mc_print_sub_stage not in (None, 0):
  7837. return
  7838. _first_layer_notified[printer_id] = True
  7839. try:
  7840. async with async_session() as db:
  7841. from backend.app.models.printer import Printer
  7842. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7843. printer = result.scalar_one_or_none()
  7844. if not printer:
  7845. return
  7846. printer_name = printer.name
  7847. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  7848. total_layers = state.total_layers if state else 0
  7849. image_data = await _capture_snapshot_for_notification(
  7850. printer_id, printer, logging.getLogger(__name__)
  7851. )
  7852. await notification_service.on_first_layer_complete(
  7853. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  7854. )
  7855. except Exception as e:
  7856. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  7857. printer_manager.set_layer_change_callback(on_layer_change)
  7858. async def on_print_progress(printer_id: int, percent: int):
  7859. """#2547: keep the in-print frame bank fresh through the final layer.
  7860. `on_layer_change` stops the moment the last layer starts, which on the
  7861. H2C capture that closed #2547 left the bank stale for the three minutes
  7862. that layer took. Progress is the only field that keeps advancing there,
  7863. and it freezes before the End G-code runs — so banking on it stays
  7864. inside the print and never sees a swapped plate.
  7865. """
  7866. client = printer_manager.get_client(printer_id)
  7867. state = client.state if client else None
  7868. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  7869. printer_manager.set_print_progress_callback(on_print_progress)
  7870. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  7871. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  7872. waiter = _bed_cool_waiters.get(printer_id)
  7873. if not waiter:
  7874. return
  7875. threshold = waiter["threshold"]
  7876. if bed_temp > threshold:
  7877. return
  7878. # Bed is at or below threshold — fire notification and remove waiter
  7879. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  7880. if not waiter_info:
  7881. return # Another callback already handled it
  7882. bed_cool_logger = logging.getLogger(__name__)
  7883. bed_cool_logger.info(
  7884. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  7885. bed_temp,
  7886. printer_id,
  7887. threshold,
  7888. )
  7889. try:
  7890. printer_info = printer_manager.get_printer(printer_id)
  7891. p_name = printer_info.name if printer_info else "Unknown"
  7892. async with async_session() as db:
  7893. await notification_service.on_bed_cooled(
  7894. printer_id=printer_id,
  7895. printer_name=p_name,
  7896. bed_temp=bed_temp,
  7897. threshold=threshold,
  7898. filename=waiter_info["filename"],
  7899. db=db,
  7900. )
  7901. except Exception as e:
  7902. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  7903. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  7904. async def on_drying_complete(printer_id: int, ams_id: int):
  7905. """Smart-plug auto-off-after-drying trigger (#1349).
  7906. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  7907. manager walks all plugs linked to this printer and turns off only
  7908. the ones with ``auto_off_after_drying`` enabled, after their
  7909. per-plug delay. Multiple AMS units finishing close together (e.g. a
  7910. dual-AMS dry that ends within the same MQTT push) call this once
  7911. per unit — the manager's ``_cancel_pending_off`` collapses
  7912. repeated scheduling on the same plug to one timer, so duplicate
  7913. fires are safe.
  7914. """
  7915. try:
  7916. async with async_session() as db:
  7917. await smart_plug_manager.on_drying_complete(printer_id, db)
  7918. except Exception as e:
  7919. logging.getLogger(__name__).warning(
  7920. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  7921. printer_id,
  7922. ams_id,
  7923. e,
  7924. )
  7925. printer_manager.set_drying_complete_callback(on_drying_complete)
  7926. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  7927. """Surface the read-back result of a spool assignment to the UI (#2582).
  7928. The MQTT client confirms (or fails to confirm) that the tray telemetry
  7929. echoed back the filament id we pushed. We relay that as a websocket
  7930. event so the frontend can toast "loaded" / "assignment didn't take"
  7931. instead of the historic silent fire-and-forget, which made the
  7932. AMS→Studio hand-off feel random to users.
  7933. """
  7934. try:
  7935. from backend.app.services.spool_assignment_notifications import (
  7936. _slot_label_from_global_tray,
  7937. )
  7938. if ams_id == 255:
  7939. global_id = 254 + tray_id
  7940. elif ams_id >= 128:
  7941. global_id = ams_id
  7942. else:
  7943. global_id = ams_id * 4 + tray_id
  7944. slot_label = _slot_label_from_global_tray(global_id)
  7945. printer_info = printer_manager.get_printer(printer_id)
  7946. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7947. await ws_manager.broadcast(
  7948. {
  7949. "type": "spool_assignment_verified",
  7950. "printer_id": printer_id,
  7951. "printer_name": printer_name,
  7952. "ams_id": ams_id,
  7953. "tray_id": tray_id,
  7954. "slot": slot_label,
  7955. "verified": verified,
  7956. # Present on success: False means the filament setting landed
  7957. # but the K-profile (cali_idx) did not — the reporter's exact
  7958. # "loaded but no flow profile" symptom.
  7959. "kprofile_applied": detail.get("kprofile_applied", True),
  7960. # Present on failure: whether any tray telemetry was seen in
  7961. # the window (distinguishes "printer silent" from "printer
  7962. # stored something else").
  7963. "saw_tray": detail.get("saw_tray", False),
  7964. }
  7965. )
  7966. except Exception as e:
  7967. logging.getLogger(__name__).warning(
  7968. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  7969. printer_id,
  7970. ams_id,
  7971. tray_id,
  7972. e,
  7973. )
  7974. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  7975. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  7976. """Persist a mid-print tray change for completion-time attribution.
  7977. AMS filament backup switches trays without telling the slicer, so the
  7978. tray-change log is the only record of which spool fed which layers.
  7979. Keeping it only in memory meant a restart mid-print charged everything
  7980. to the tray that finished the job.
  7981. """
  7982. try:
  7983. from backend.app.services.usage_tracker import record_tray_change
  7984. async with async_session() as db:
  7985. await record_tray_change(db, printer_id, tray_global, layer_num)
  7986. except Exception as e:
  7987. logging.getLogger(__name__).warning(
  7988. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  7989. printer_id,
  7990. tray_global,
  7991. layer_num,
  7992. e,
  7993. )
  7994. printer_manager.set_tray_change_callback(on_tray_change)
  7995. # Initialize MQTT relay from settings
  7996. async with async_session() as db:
  7997. from backend.app.api.routes.settings import get_setting
  7998. mqtt_settings = {
  7999. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  8000. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  8001. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  8002. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  8003. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  8004. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  8005. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  8006. }
  8007. await mqtt_relay.configure(mqtt_settings)
  8008. # Restore MQTT smart plug subscriptions
  8009. if mqtt_settings.get("mqtt_enabled"):
  8010. from backend.app.models.smart_plug import SmartPlug
  8011. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  8012. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  8013. mqtt_plugs = result.scalars().all()
  8014. restored = 0
  8015. for plug in mqtt_plugs:
  8016. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  8017. restored += 1
  8018. if restored:
  8019. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  8020. # Connect to all active printers
  8021. async with async_session() as db:
  8022. await init_printer_connections(db)
  8023. # Auto-connect to Spoolman if enabled
  8024. async with async_session() as db:
  8025. from backend.app.api.routes.settings import get_setting
  8026. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  8027. spoolman_url = await get_setting(db, "spoolman_url")
  8028. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  8029. try:
  8030. client = await init_spoolman_client(spoolman_url)
  8031. if await client.health_check():
  8032. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  8033. # Ensure the 'tag' extra field exists for RFID/UUID storage
  8034. field_ok = await client.ensure_tag_extra_field()
  8035. if not field_ok:
  8036. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  8037. # Register the BambuStudio slicer-preset fields used by the
  8038. # spool-edit / assign flow. Spoolman rejects PATCHes with
  8039. # unknown extra keys, so these must exist before any update
  8040. # that touches them.
  8041. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  8042. if not await client.ensure_extra_field(field_name):
  8043. logging.warning(
  8044. "Spoolman extra field %r registration failed — "
  8045. "spool slicer-preset edits will return 502",
  8046. field_name,
  8047. )
  8048. else:
  8049. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  8050. except Exception as e:
  8051. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  8052. # Start the print scheduler
  8053. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  8054. # Start the smart plug scheduler for time-based on/off
  8055. smart_plug_manager.start_scheduler()
  8056. # Start the Home Assistant sensor poller (#1148)
  8057. ha_sensor_manager.start()
  8058. location_ha_sensor_manager.start()
  8059. # Resume any pending auto-offs that were interrupted by restart
  8060. await smart_plug_manager.resume_pending_auto_offs()
  8061. # Start the notification digest scheduler
  8062. notification_service.start_digest_scheduler()
  8063. # Start the GitHub backup scheduler
  8064. await github_backup_service.start_scheduler()
  8065. # Start the local backup scheduler
  8066. await local_backup_service.start_scheduler()
  8067. await obico_detection_service.start()
  8068. # Start the library trash sweeper (#1008)
  8069. await library_trash_service.start_scheduler()
  8070. # Start the archive auto-purge sweeper (#1008 follow-up)
  8071. await archive_purge_service.start_scheduler()
  8072. # Start AMS history recording
  8073. start_ams_history_recording()
  8074. # Start printer sensor (nozzle / bed / chamber) history recording
  8075. start_printer_sensor_history_recording()
  8076. # Start printer runtime tracking
  8077. start_runtime_tracking()
  8078. # Start SpoolBuddy device watchdog
  8079. start_spoolbuddy_watchdog()
  8080. # Start camera stream orphan cleanup
  8081. start_camera_cleanup()
  8082. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  8083. start_connection_watchdog()
  8084. # One-shot sweep for timelapse session directories orphaned by a crash
  8085. # or restart that happened mid-print (in-memory session tracking can't
  8086. # survive that, and nothing else reaps the leftover frames/output file)
  8087. try:
  8088. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  8089. removed = cleanup_orphaned_timelapse_sessions()
  8090. if removed:
  8091. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  8092. except Exception as e:
  8093. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  8094. # Start expected-print TTL eviction (prevents memory leak when prints are
  8095. # registered but on_print_start never fires)
  8096. start_expected_prints_cleanup()
  8097. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  8098. start_auth_cleanup()
  8099. from backend.app.services.printer_media import start_printer_download_cleanup
  8100. start_printer_download_cleanup()
  8101. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  8102. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  8103. from backend.app.services.loop_watchdog import start_loop_watchdog
  8104. start_loop_watchdog()
  8105. # Initialize virtual printer manager and sync from DB
  8106. from backend.app.services.virtual_printer import virtual_printer_manager
  8107. virtual_printer_manager.set_session_factory(async_session)
  8108. virtual_printer_manager.set_printer_manager(printer_manager)
  8109. try:
  8110. await virtual_printer_manager.sync_from_db()
  8111. logging.info("Virtual printer manager synced from database")
  8112. except Exception as e:
  8113. logging.warning("Failed to sync virtual printers: %s", e)
  8114. yield
  8115. # Shutdown
  8116. print_scheduler.stop()
  8117. smart_plug_manager.stop_scheduler()
  8118. ha_sensor_manager.stop()
  8119. location_ha_sensor_manager.stop()
  8120. notification_service.stop_digest_scheduler()
  8121. github_backup_service.stop_scheduler()
  8122. local_backup_service.stop_scheduler()
  8123. library_trash_service.stop_scheduler()
  8124. archive_purge_service.stop_scheduler()
  8125. obico_detection_service.stop()
  8126. stop_ams_history_recording()
  8127. stop_printer_sensor_history_recording()
  8128. stop_runtime_tracking()
  8129. stop_spoolbuddy_watchdog()
  8130. stop_camera_cleanup()
  8131. stop_connection_watchdog()
  8132. from backend.app.services.loop_watchdog import stop_loop_watchdog
  8133. stop_loop_watchdog()
  8134. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  8135. # cleanly rather than waiting on a queue that nothing will ever fill.
  8136. try:
  8137. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  8138. await shutdown_all_broadcasters()
  8139. except Exception as e:
  8140. logging.warning("Failed to shut down camera broadcasters: %s", e)
  8141. stop_expected_prints_cleanup()
  8142. stop_auth_cleanup()
  8143. from backend.app.services.printer_media import stop_printer_download_cleanup
  8144. await stop_printer_download_cleanup()
  8145. printer_manager.disconnect_all()
  8146. await close_spoolman_client()
  8147. # Stop all virtual printer services
  8148. await virtual_printer_manager.stop_all()
  8149. await mqtt_smart_plug_service.disconnect(timeout=2)
  8150. await mqtt_relay.disconnect(timeout=2)
  8151. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  8152. set_shared_http_client(None)
  8153. set_shared_makerworld_http_client(None)
  8154. set_shared_orca_http_client(None)
  8155. await _shared_cloud_http_client.aclose()
  8156. # Checkpoint WAL (SQLite only) and close all database connections
  8157. from backend.app.core.db_dialect import is_sqlite
  8158. if is_sqlite():
  8159. try:
  8160. async with engine.begin() as conn:
  8161. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  8162. logging.info("WAL checkpoint completed")
  8163. except Exception as e:
  8164. logging.warning("WAL checkpoint failed: %s", e)
  8165. await engine.dispose()
  8166. app = FastAPI(
  8167. title=app_settings.app_name,
  8168. description="Archive and manage Bambu Lab 3MF files",
  8169. version=APP_VERSION,
  8170. lifespan=lifespan,
  8171. )
  8172. # =============================================================================
  8173. # Authentication Middleware - Secures ALL API routes by default
  8174. # =============================================================================
  8175. # Public routes that don't require authentication even when auth is enabled
  8176. PUBLIC_API_ROUTES = {
  8177. # Auth routes needed before/during login
  8178. "/api/v1/auth/status",
  8179. "/api/v1/auth/login",
  8180. "/api/v1/auth/setup", # Needed for initial setup and recovery
  8181. # Advanced auth status needed for login page
  8182. "/api/v1/auth/advanced-auth/status",
  8183. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  8184. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  8185. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  8186. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  8187. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  8188. # OIDC routes that must be reachable without a JWT
  8189. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  8190. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  8191. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  8192. # Version check for updates (no sensitive data)
  8193. "/api/v1/updates/version",
  8194. # Metrics endpoint handles its own prometheus_token authentication
  8195. "/api/v1/metrics",
  8196. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  8197. # this BEFORE a JWT is available to pick up the firstboot wizard's
  8198. # hostname / timezone / locale and the chrony NTP-gate state. The
  8199. # response contains user-set defaults and a public sync flag — no
  8200. # secrets. Without this entry the global auth middleware returns 401
  8201. # before the route handler runs, regardless of the route's own
  8202. # "no auth required" intent.
  8203. "/api/v1/system/appliance",
  8204. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  8205. # authenticates with a long-lived ``camwall``-scoped token in the query
  8206. # string — exactly like the camera streams two lists below, and for the same
  8207. # reason (no header to put a JWT in). "Public" here only means the middleware
  8208. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  8209. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  8210. # plain ``camera_stream`` token does NOT open this door.
  8211. "/api/v1/camwall/printers",
  8212. }
  8213. # Route prefixes that are public (for routes with dynamic segments)
  8214. PUBLIC_API_PREFIXES = [
  8215. # WebSocket connections handle their own auth
  8216. "/api/v1/ws",
  8217. # OIDC authorize redirects — include provider_id in path
  8218. "/api/v1/auth/oidc/authorize/",
  8219. ]
  8220. # Route patterns that are public (read-only display data)
  8221. # These are checked with "in path" - needed because browsers load images/videos
  8222. # via <img src> and <video src> which don't include Authorization headers
  8223. PUBLIC_API_PATTERNS = [
  8224. # Thumbnails
  8225. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  8226. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  8227. # Images and media
  8228. "/photos/", # /archives/{id}/photos/{filename}
  8229. "/project-image/", # /archives/{id}/project-image/{path}
  8230. "/qrcode", # /archives/{id}/qrcode
  8231. "/timelapse", # /archives/{id}/timelapse (video)
  8232. "/cover", # /printers/{id}/cover
  8233. "/icon", # /external-links/{id}/icon
  8234. # Camera (streams loaded via <img> tag)
  8235. "/camera/stream", # /printers/{id}/camera/stream
  8236. "/camera/snapshot", # /printers/{id}/camera/snapshot
  8237. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  8238. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  8239. # string (same reasoning as the camera streams above — no header to carry a
  8240. # JWT). "Public" only means the middleware steps aside; the route still runs
  8241. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  8242. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  8243. "/overlay-status", # /printers/{id}/overlay-status
  8244. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  8245. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  8246. # download token in the URL path instead.
  8247. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  8248. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  8249. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  8250. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  8251. ]
  8252. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  8253. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  8254. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  8255. Format: comma-separated list of ``scheme://host[:port]`` origins.
  8256. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  8257. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  8258. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  8259. Invalid entries are dropped with a warning rather than failing startup, so
  8260. a typo in one origin doesn't take the whole deployment down.
  8261. """
  8262. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  8263. if not raw:
  8264. return ()
  8265. valid: list[str] = []
  8266. for item in raw.split(","):
  8267. candidate = item.strip()
  8268. if not candidate:
  8269. continue
  8270. try:
  8271. parsed = urlparse(candidate)
  8272. except ValueError as e:
  8273. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  8274. continue
  8275. if parsed.scheme not in ("http", "https"):
  8276. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  8277. continue
  8278. if not parsed.netloc:
  8279. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  8280. continue
  8281. if parsed.path and parsed.path != "/":
  8282. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  8283. continue
  8284. if parsed.query or parsed.fragment:
  8285. _security_headers_logger.warning(
  8286. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  8287. )
  8288. continue
  8289. if "*" in parsed.netloc:
  8290. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  8291. continue
  8292. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  8293. if valid:
  8294. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  8295. return tuple(valid)
  8296. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  8297. def _frame_ancestors(default_value: str) -> str:
  8298. """Compose the ``frame-ancestors`` CSP directive (#1191).
  8299. ``default_value`` is the strict directive used when the operator has not
  8300. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  8301. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  8302. Settings URL builder's preview). When trusted origins
  8303. are configured, ``'self'`` is always included so same-origin embedding never
  8304. breaks even if an operator forgets to add their own origin to the list.
  8305. """
  8306. if _TRUSTED_FRAME_ORIGINS:
  8307. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  8308. return f"frame-ancestors {default_value};"
  8309. @app.middleware("http")
  8310. async def security_headers_middleware(request, call_next):
  8311. """Add standard HTTP security headers to every response."""
  8312. # Per-request nonce stamped into `script-src` (#1460). On its own this
  8313. # changes nothing for Bambuddy's own pages — index.html has no inline
  8314. # scripts since the SW registration moved to /sw-register.js. The reason
  8315. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  8316. # script injected into the HTML on the edge, with a fresh hash on every
  8317. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  8318. # it clones the same nonce onto its injected <script>, and the inline
  8319. # script passes the policy without us needing 'unsafe-inline'. See
  8320. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  8321. csp_nonce = secrets.token_urlsafe(16)
  8322. response = await call_next(request)
  8323. response.headers["X-Content-Type-Options"] = "nosniff"
  8324. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  8325. # browsers honour CSP frame-ancestors instead, and the legacy
  8326. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  8327. # When operators have explicitly allowlisted trusted frame origins (#1191
  8328. # — typically Home Assistant on a different port), drop X-Frame-Options
  8329. # and let the CSP-side frame-ancestors directive govern embedding.
  8330. if not _TRUSTED_FRAME_ORIGINS:
  8331. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  8332. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  8333. # Content-Security-Policy for the React SPA.
  8334. # Notes:
  8335. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  8336. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  8337. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  8338. # - media-src blob:: timelapse video player uses Blob URLs.
  8339. # - font-src data:: some icon fonts are embedded as data URIs.
  8340. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  8341. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  8342. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  8343. # default CSP would render a blank page.
  8344. response.headers["Content-Security-Policy"] = (
  8345. "default-src 'self'; "
  8346. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  8347. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  8348. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  8349. "connect-src 'self'; "
  8350. "font-src 'self' data: https://fonts.gstatic.com; "
  8351. "worker-src 'self' blob:; "
  8352. "object-src 'none'; "
  8353. "base-uri 'self'; " + _frame_ancestors("'none'")
  8354. )
  8355. else:
  8356. # The streaming overlay is embedded same-origin by the URL builder's
  8357. # preview in Settings (#1422), so this branch allows 'self'.
  8358. # Embedding from anywhere else is still refused: 'self'
  8359. # only permits a framer on this origin, which is Bambuddy's own UI, so
  8360. # a clickjacking page on another host is blocked exactly as before.
  8361. # (The overlay draws status over a camera feed and its only interactive
  8362. # element is the logo link, so there is nothing to bait a click into
  8363. # even from a same-origin framer.) Cross-origin embedding of the
  8364. # overlay — Home Assistant on another port — remains what
  8365. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  8366. # allowlist in.
  8367. embeddable_same_origin = request.url.path.startswith("/overlay/")
  8368. response.headers["Content-Security-Policy"] = (
  8369. "default-src 'self'; "
  8370. f"script-src 'self' 'nonce-{csp_nonce}'; "
  8371. "style-src 'self' 'unsafe-inline'; "
  8372. "img-src 'self' data: blob:; "
  8373. "media-src 'self' blob:; "
  8374. "connect-src 'self' ws: wss:; "
  8375. "font-src 'self' data:; "
  8376. "object-src 'none'; "
  8377. "base-uri 'self'; "
  8378. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  8379. )
  8380. if request.url.scheme == "https":
  8381. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  8382. return response
  8383. @app.middleware("http")
  8384. async def auth_middleware(request, call_next):
  8385. """Enforce authentication on all API routes when auth is enabled.
  8386. This middleware provides defense-in-depth by checking auth at the API gateway level,
  8387. regardless of whether individual routes have auth dependencies.
  8388. """
  8389. from starlette.responses import JSONResponse
  8390. path = request.url.path
  8391. # Only apply to API routes
  8392. if not path.startswith("/api/"):
  8393. return await call_next(request)
  8394. # Allow public routes
  8395. if path in PUBLIC_API_ROUTES:
  8396. return await call_next(request)
  8397. # Allow public prefixes
  8398. for prefix in PUBLIC_API_PREFIXES:
  8399. if path.startswith(prefix):
  8400. return await call_next(request)
  8401. # Allow public patterns (read-only display data like thumbnails)
  8402. for pattern in PUBLIC_API_PATTERNS:
  8403. if pattern in path:
  8404. return await call_next(request)
  8405. # Check if auth is enabled. Fail CLOSED on any exception during the
  8406. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  8407. # an attacker who could force a DB exception (e.g. file-descriptor
  8408. # exhaustion via login flood) bypass auth on every protected endpoint.
  8409. try:
  8410. async with async_session() as db:
  8411. from backend.app.core.auth import is_auth_enabled
  8412. auth_enabled = await is_auth_enabled(db)
  8413. if not auth_enabled:
  8414. # Auth disabled, allow all requests
  8415. return await call_next(request)
  8416. except Exception:
  8417. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  8418. return JSONResponse(
  8419. status_code=503,
  8420. content={"detail": "Authentication service temporarily unavailable"},
  8421. )
  8422. # Auth is enabled - require valid token
  8423. auth_header = request.headers.get("Authorization")
  8424. x_api_key = request.headers.get("X-API-Key")
  8425. # Check for API key auth first
  8426. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  8427. # API key authentication - let the request through to be validated by route handler
  8428. # API keys are validated per-route since they have different permission levels
  8429. return await call_next(request)
  8430. # Check for JWT auth
  8431. if not auth_header or not auth_header.startswith("Bearer "):
  8432. return JSONResponse(
  8433. status_code=401,
  8434. content={"detail": "Authentication required"},
  8435. headers={"WWW-Authenticate": "Bearer"},
  8436. )
  8437. # Validate JWT token
  8438. import jwt
  8439. try:
  8440. from backend.app.core.auth import (
  8441. ALGORITHM,
  8442. SECRET_KEY,
  8443. _is_token_fresh,
  8444. get_user_by_username,
  8445. is_jti_revoked,
  8446. )
  8447. token = auth_header.replace("Bearer ", "")
  8448. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  8449. username = payload.get("sub")
  8450. if not username:
  8451. raise ValueError("No username in token")
  8452. jti = payload.get("jti")
  8453. if not jti:
  8454. raise ValueError("No jti in token")
  8455. iat = payload.get("iat")
  8456. # Verify user exists, is active, and token is still fresh (L-R8-A).
  8457. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  8458. # this session so the gateway adds a single pooled checkout, not two (#2572).
  8459. async with async_session() as db:
  8460. if await is_jti_revoked(jti, db):
  8461. return JSONResponse(
  8462. status_code=401,
  8463. content={"detail": "Token has been revoked"},
  8464. headers={"WWW-Authenticate": "Bearer"},
  8465. )
  8466. user = await get_user_by_username(db, username)
  8467. if not user or not user.is_active:
  8468. return JSONResponse(
  8469. status_code=401,
  8470. content={"detail": "User not found or inactive"},
  8471. headers={"WWW-Authenticate": "Bearer"},
  8472. )
  8473. if not _is_token_fresh(iat, user):
  8474. return JSONResponse(
  8475. status_code=401,
  8476. content={"detail": "Token no longer valid"},
  8477. headers={"WWW-Authenticate": "Bearer"},
  8478. )
  8479. except jwt.ExpiredSignatureError:
  8480. return JSONResponse(
  8481. status_code=401,
  8482. content={"detail": "Token has expired"},
  8483. headers={"WWW-Authenticate": "Bearer"},
  8484. )
  8485. except (jwt.InvalidTokenError, ValueError, Exception):
  8486. return JSONResponse(
  8487. status_code=401,
  8488. content={"detail": "Invalid token"},
  8489. headers={"WWW-Authenticate": "Bearer"},
  8490. )
  8491. return await call_next(request)
  8492. @app.middleware("http")
  8493. async def trace_id_middleware(request, call_next):
  8494. """Stamp every HTTP request with a trace ID and echo it back.
  8495. Decorated AFTER auth_middleware on purpose: Starlette stacks
  8496. @app.middleware decorators LIFO, so the last-decorated runs first
  8497. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  8498. which means auth-middleware log lines (and every line emitted on the
  8499. way down to and back from the route handler) all carry the same
  8500. trace ID. If we put it before auth, auth's logs would be stamped
  8501. with the *previous* request's ID — useless for correlation.
  8502. Honours an inbound ``X-Trace-Id`` header so callers running their
  8503. own tracing can correlate their span IDs with our log lines, but
  8504. only if the value passes the whitelist gate in
  8505. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  8506. rejected (too long, contains control chars, etc.) silently triggers
  8507. a freshly minted server-side ID rather than failing the request.
  8508. The minted (or echoed) ID is set on a ContextVar so that every log
  8509. record emitted during the request — application logs *and* uvicorn's
  8510. access log — carries it via TraceIDFilter, and is also written to
  8511. the ``X-Trace-Id`` response header so clients can pin a server-side
  8512. log search to the exact request they made.
  8513. """
  8514. from backend.app.core.trace import (
  8515. generate_trace_id,
  8516. normalise_inbound_trace_id,
  8517. trace_id_var,
  8518. )
  8519. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  8520. trace_id = inbound if inbound is not None else generate_trace_id()
  8521. token = trace_id_var.set(trace_id)
  8522. try:
  8523. response = await call_next(request)
  8524. finally:
  8525. # Reset the ContextVar so a record emitted in a totally
  8526. # unrelated background task that just happens to inherit this
  8527. # context doesn't keep referencing this request's ID forever.
  8528. # In practice ContextVar.reset is best-effort under asyncio
  8529. # task-spawn semantics, but the cost is one attribute write so
  8530. # we may as well do it.
  8531. trace_id_var.reset(token)
  8532. response.headers["X-Trace-Id"] = trace_id
  8533. return response
  8534. # API routes
  8535. app.include_router(auth.router, prefix=app_settings.api_prefix)
  8536. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  8537. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  8538. app.include_router(users.router, prefix=app_settings.api_prefix)
  8539. app.include_router(groups.router, prefix=app_settings.api_prefix)
  8540. app.include_router(printers.router, prefix=app_settings.api_prefix)
  8541. app.include_router(archives.router, prefix=app_settings.api_prefix)
  8542. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  8543. app.include_router(finance.router, prefix=app_settings.api_prefix)
  8544. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  8545. app.include_router(labels.router, prefix=app_settings.api_prefix)
  8546. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  8547. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  8548. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  8549. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  8550. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  8551. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  8552. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  8553. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  8554. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  8555. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  8556. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  8557. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  8558. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  8559. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  8560. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  8561. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  8562. app.include_router(updates.router, prefix=app_settings.api_prefix)
  8563. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  8564. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  8565. app.include_router(camera.router, prefix=app_settings.api_prefix)
  8566. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  8567. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  8568. app.include_router(projects.router, prefix=app_settings.api_prefix)
  8569. app.include_router(library.router, prefix=app_settings.api_prefix)
  8570. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  8571. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  8572. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  8573. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  8574. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  8575. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  8576. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  8577. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  8578. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  8579. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  8580. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  8581. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  8582. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  8583. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  8584. app.include_router(system.router, prefix=app_settings.api_prefix)
  8585. app.include_router(support.router, prefix=app_settings.api_prefix)
  8586. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  8587. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  8588. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  8589. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  8590. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  8591. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  8592. app.include_router(obico.router, prefix=app_settings.api_prefix)
  8593. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  8594. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  8595. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  8596. # Serve static files (React build)
  8597. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  8598. app.mount(
  8599. "/assets",
  8600. StaticFiles(directory=app_settings.static_dir / "assets"),
  8601. name="assets",
  8602. )
  8603. if (app_settings.static_dir / "img").exists():
  8604. app.mount(
  8605. "/img",
  8606. StaticFiles(directory=app_settings.static_dir / "img"),
  8607. name="img",
  8608. )
  8609. if (app_settings.static_dir / "icons").exists():
  8610. app.mount(
  8611. "/icons",
  8612. StaticFiles(directory=app_settings.static_dir / "icons"),
  8613. name="icons",
  8614. )
  8615. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  8616. # falls through to the SPA catch-all and returns index.html, which the
  8617. # browser's font sanitizer rejects ("downloadable font: rejected by
  8618. # sanitizer").
  8619. if (app_settings.static_dir / "fonts").exists():
  8620. app.mount(
  8621. "/fonts",
  8622. StaticFiles(directory=app_settings.static_dir / "fonts"),
  8623. name="fonts",
  8624. )
  8625. @app.get("/")
  8626. async def serve_frontend():
  8627. """Serve the React frontend."""
  8628. index_file = app_settings.static_dir / "index.html"
  8629. if index_file.exists():
  8630. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8631. return {
  8632. "message": "Bambuddy API",
  8633. "docs": "/docs",
  8634. "frontend": "Build and place React app in /static directory",
  8635. }
  8636. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  8637. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  8638. # forever, but the HTML wrapping it is the only file that knows which hash
  8639. # is current. Without explicit cache-control headers Chromium decides
  8640. # heuristically (typically 10% of the time since Last-Modified) and on
  8641. # long-running kiosks happily serves stale HTML across browser restarts.
  8642. # That stale HTML references an old bundle hash, the old bundle is also
  8643. # in the disk cache, and the user ends up running pre-update JS forever
  8644. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  8645. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  8646. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  8647. @app.get("/health")
  8648. async def health_check():
  8649. """Health check endpoint."""
  8650. return {"status": "healthy"}
  8651. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  8652. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  8653. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  8654. # in deployment debugging.
  8655. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  8656. async def serve_manifest():
  8657. """Serve PWA manifest."""
  8658. manifest_file = app_settings.static_dir / "manifest.json"
  8659. if manifest_file.exists():
  8660. return FileResponse(manifest_file, media_type="application/manifest+json")
  8661. return {"error": "Manifest not found"}
  8662. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  8663. async def serve_service_worker():
  8664. """Serve service worker."""
  8665. sw_file = app_settings.static_dir / "sw.js"
  8666. if sw_file.exists():
  8667. return FileResponse(
  8668. sw_file,
  8669. media_type="application/javascript",
  8670. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  8671. )
  8672. return {"error": "Service worker not found"}
  8673. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  8674. async def serve_sw_register():
  8675. """Serve the service-worker registration bootstrap script.
  8676. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  8677. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  8678. """
  8679. reg_file = app_settings.static_dir / "sw-register.js"
  8680. if reg_file.exists():
  8681. return FileResponse(reg_file, media_type="application/javascript")
  8682. return {"error": "sw-register.js not found"}
  8683. # ── GCode viewer static files ────────────────────────────────────────────────
  8684. # Catch-all route for React Router (must be last)
  8685. @app.get("/{full_path:path}")
  8686. async def serve_spa(full_path: str):
  8687. """Serve React app for client-side routing."""
  8688. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  8689. if full_path.startswith("api/"):
  8690. from fastapi import HTTPException
  8691. raise HTTPException(status_code=404, detail="Not found")
  8692. index_file = app_settings.static_dir / "index.html"
  8693. if index_file.exists():
  8694. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  8695. return {"error": "Frontend not built"}