main.py 309 KB

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