main.py 397 KB

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