main.py 319 KB

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