main.py 330 KB

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