main.py 338 KB

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