main.py 436 KB

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