main.py 421 KB

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