main.py 442 KB

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