main.py 335 KB

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