main.py 466 KB

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