main.py 579 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from typing import cast
  15. from urllib.parse import urlparse
  16. from fastapi import FastAPI
  17. from fastapi.encoders import jsonable_encoder
  18. from fastapi.exceptions import RequestValidationError
  19. from fastapi.responses import FileResponse, JSONResponse
  20. from fastapi.staticfiles import StaticFiles
  21. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  22. from sqlalchemy.engine import CursorResult
  23. from sqlalchemy.exc import IntegrityError
  24. from sqlalchemy.orm.exc import StaleDataError
  25. from backend.app.api.routes import (
  26. ams_history,
  27. announcements,
  28. api_keys,
  29. archive_purge,
  30. archives,
  31. auth,
  32. bug_report,
  33. camera,
  34. camwall,
  35. cloud,
  36. connected_apps,
  37. discovery,
  38. external_links,
  39. filaments,
  40. finance,
  41. firmware,
  42. github_backup,
  43. groups,
  44. ha_sensors,
  45. inventory,
  46. kprofiles,
  47. labels,
  48. library,
  49. library_tags,
  50. library_trash,
  51. library_variants,
  52. local_backup,
  53. local_presets,
  54. location_ha_sensors,
  55. maintenance,
  56. makerworld,
  57. manyfold,
  58. metrics,
  59. mfa,
  60. notification_templates,
  61. notifications,
  62. obico,
  63. orca_cloud,
  64. overlay_branding,
  65. pending_uploads,
  66. pipeline_runs,
  67. print_log,
  68. print_queue,
  69. printer_locations,
  70. printer_sensor_history,
  71. printers,
  72. projects,
  73. scheduled_dryings,
  74. settings as settings_routes,
  75. slice_jobs,
  76. slicer_pipelines,
  77. slicer_presets,
  78. smart_plugs,
  79. sponsor_prompt,
  80. spoolbuddy,
  81. spoolman,
  82. spoolman_inventory,
  83. support,
  84. system,
  85. updates,
  86. user_notifications,
  87. users,
  88. virtual_printers,
  89. webhook,
  90. websocket,
  91. )
  92. from backend.app.api.routes.maintenance import (
  93. _get_printer_maintenance_internal,
  94. ensure_default_types,
  95. maintenance_alert_values,
  96. )
  97. from backend.app.api.routes.support import init_debug_logging
  98. from backend.app.core.config import APP_VERSION, settings as app_settings
  99. from backend.app.core.database import async_session, engine, init_db
  100. from backend.app.core.static_assets import AssetStaticFiles
  101. from backend.app.core.tasks import spawn_background_task
  102. from backend.app.core.websocket import ws_manager
  103. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  104. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  105. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  106. from backend.app.services.archive_cost_estimate import (
  107. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  108. )
  109. from backend.app.services.archive_purge import archive_purge_service
  110. from backend.app.services.bambu_ftp import (
  111. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  112. FileNotOnPrinterError,
  113. cache_3mf_download,
  114. clear_3mf_cache,
  115. download_file_async,
  116. download_file_try_paths_async,
  117. ftps_handshake_blocked,
  118. get_cached_3mf,
  119. get_ftp_retry_settings,
  120. normalize_3mf_name,
  121. with_ftp_retry,
  122. )
  123. from backend.app.services.bambu_mqtt import PrinterState
  124. from backend.app.services.camera_light import camera_light
  125. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  126. from backend.app.services.github_backup import github_backup_service
  127. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  128. from backend.app.services.library_trash import library_trash_service
  129. from backend.app.services.local_backup import local_backup_service
  130. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  131. from backend.app.services.mqtt_relay import mqtt_relay
  132. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  133. from backend.app.services.notification_service import notification_service
  134. from backend.app.services.notify_live_activities import notify_live_activities
  135. from backend.app.services.notify_widgets import notify_widgets
  136. from backend.app.services.obico_detection import obico_detection_service
  137. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  138. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  139. from backend.app.services.print_scheduler import scheduler as print_scheduler
  140. from backend.app.services.print_storage import (
  141. REASON_FTP_TRANSFER_FAILED,
  142. REASON_FTPS_COOLOFF,
  143. external_storage_present,
  144. ftp_probe_paths,
  145. print_file_reachable_over_ftp,
  146. )
  147. from backend.app.services.printer_manager import (
  148. init_printer_connections,
  149. parse_plate_id,
  150. printer_manager,
  151. printer_state_to_dict,
  152. resolve_plate_id,
  153. )
  154. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  155. from backend.app.services.slot_nozzle import (
  156. nozzle_diameter_for_extruder,
  157. nozzle_flow_for_extruder,
  158. )
  159. from backend.app.services.smart_plug_manager import smart_plug_manager
  160. from backend.app.services.spool_assignment_notifications import (
  161. notify_missing_spool_assignments_on_print_start,
  162. )
  163. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  164. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  165. from backend.app.services.spoolman_tracking import (
  166. cleanup_tracking as _cleanup_spoolman_tracking,
  167. release_archived_slot_rows as _release_archived_spoolman_slots,
  168. report_usage as _report_spoolman_usage,
  169. store_print_data as _store_spoolman_print_data,
  170. )
  171. from backend.app.services.telegram_reactions import telegram_reaction_poller
  172. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  173. from backend.app.utils.ams_humidity import ams_humidity_percent
  174. from backend.app.utils.filament_types import printer_filament_type
  175. from backend.app.utils.fts_routing import extruder_for_inlet
  176. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  177. from backend.app.utils.print_jobs import is_internal_printer_job
  178. # =============================================================================
  179. # Dependency Check - runs before other imports to give helpful error messages
  180. # =============================================================================
  181. def _start_error_server(missing_packages: list):
  182. """Start a minimal HTTP server to display dependency errors in browser."""
  183. import os
  184. import signal
  185. from http.server import BaseHTTPRequestHandler, HTTPServer
  186. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  187. html = f"""<!DOCTYPE html>
  188. <html>
  189. <head>
  190. <title>Bambuddy - Setup Required</title>
  191. <style>
  192. body {{
  193. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  194. background: #0f172a; color: #e2e8f0;
  195. display: flex; justify-content: center; align-items: center;
  196. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  197. }}
  198. .container {{
  199. background: #1e293b; border-radius: 12px; padding: 40px;
  200. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  201. }}
  202. h1 {{ color: #f87171; margin-bottom: 10px; }}
  203. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  204. .packages {{
  205. background: #0f172a; border-radius: 8px; padding: 20px;
  206. margin: 20px 0; text-align: left;
  207. }}
  208. .packages ul {{ margin: 0; padding-left: 20px; }}
  209. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  210. .command {{
  211. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  212. margin: 15px 0; font-family: monospace; color: #4ade80;
  213. text-align: left; overflow-x: auto;
  214. }}
  215. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  216. </style>
  217. </head>
  218. <body>
  219. <div class="container">
  220. <h1>Setup Required</h1>
  221. <h2>Missing Python packages</h2>
  222. <div class="packages"><ul>{packages_html}</ul></div>
  223. <p>To fix, run this command on your server:</p>
  224. <div class="command">pip install -r requirements.lock</div>
  225. <p>Or if using a virtual environment:</p>
  226. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  227. <p class="note">After installing, restart Bambuddy:<br>
  228. <code>sudo systemctl restart bambuddy</code></p>
  229. </div>
  230. </body>
  231. </html>"""
  232. class ErrorHandler(BaseHTTPRequestHandler):
  233. def do_GET(self):
  234. self.send_response(503)
  235. self.send_header("Content-type", "text/html")
  236. self.end_headers()
  237. self.wfile.write(html.encode())
  238. def log_message(self, format, *args):
  239. print(f"[Error Server] {args[0]}")
  240. port = int(os.environ.get("PORT", 8000))
  241. print(f"\nStarting error server on http://0.0.0.0:{port}")
  242. print("Visit this URL in your browser to see the error details.\n")
  243. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  244. def shutdown(signum, frame):
  245. print("\nShutting down error server...")
  246. raise SystemExit(0)
  247. signal.signal(signal.SIGTERM, shutdown)
  248. signal.signal(signal.SIGINT, shutdown)
  249. server.serve_forever()
  250. def check_dependencies():
  251. """Check that all required packages are installed."""
  252. missing = []
  253. # Map of import name -> package name (for pip install)
  254. required = {
  255. "jwt": "PyJWT",
  256. "fastapi": "fastapi",
  257. "uvicorn": "uvicorn",
  258. "sqlalchemy": "sqlalchemy",
  259. "aiosqlite": "aiosqlite",
  260. "pydantic": "pydantic",
  261. "paho.mqtt": "paho-mqtt",
  262. }
  263. for module, package in required.items():
  264. try:
  265. __import__(module)
  266. except ImportError:
  267. missing.append(package)
  268. if missing:
  269. print("\n" + "=" * 60)
  270. print("ERROR: Missing required Python packages!")
  271. print("=" * 60)
  272. print(f"\nMissing packages: {', '.join(missing)}")
  273. print("\nTo fix, run:")
  274. print(" pip install -r requirements.lock")
  275. print("\nOr if using a virtual environment:")
  276. print(" ./venv/bin/pip install -r requirements.lock")
  277. print("=" * 60 + "\n")
  278. _start_error_server(missing)
  279. check_dependencies()
  280. # =============================================================================
  281. # Import settings first for logging configuration
  282. # Configure logging based on settings
  283. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  284. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  285. log_level = getattr(logging, log_level_str, logging.INFO)
  286. # Trace ID column ([-] when no request scope is active — startup, MQTT
  287. # callbacks, scheduled tasks not chained from a request — so the column
  288. # stays visually aligned and missing values are obvious in grep). See
  289. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  290. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  291. # Create root logger
  292. root_logger = logging.getLogger()
  293. root_logger.setLevel(log_level)
  294. # Trace-ID injection: this filter populates record.trace_id from the
  295. # per-request ContextVar so the format string above can reference it.
  296. # Attached to each HANDLER (not the root logger) because Python's
  297. # logging semantics only invoke a logger's filters on records that
  298. # *originated* at that logger — records propagated up from child
  299. # loggers (every named logger in the app) never trigger root's filter.
  300. # Putting it on the handlers means every record any handler emits gets
  301. # trace_id injected just before the formatter runs, regardless of which
  302. # logger created the record. Without this, the formatter raises
  303. # KeyError on every child-logger record and the record is silently
  304. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  305. # partially" bug we hit. See backend/app/core/trace.py for the
  306. # ContextVar the filter reads.
  307. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  308. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  309. from backend.app.core.trace import TraceIDFilter
  310. _trace_id_filter = TraceIDFilter()
  311. # Console handler - always enabled
  312. console_handler = logging.StreamHandler()
  313. console_handler.setLevel(log_level)
  314. console_handler.setFormatter(logging.Formatter(log_format))
  315. console_handler.addFilter(_trace_id_filter)
  316. # A refused header's value (often a token) masked before the line is written.
  317. _refused_header_filter = RefusedHeaderRedactFilter()
  318. console_handler.addFilter(_refused_header_filter)
  319. root_logger.addHandler(console_handler)
  320. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  321. """Send uvicorn's own loggers to bambuddy.log as well.
  322. Neither reaches the root handler: uvicorn.access has propagate=False, and
  323. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  324. uvicorn.access is the record of which endpoint changed server state;
  325. uvicorn.error is where an unhandled route error is logged with its
  326. traceback ("Exception in ASGI application").
  327. """
  328. for name in ("uvicorn.access", "uvicorn.error"):
  329. logging.getLogger(name).addHandler(handler)
  330. # File handler - only in production or if explicitly enabled
  331. if app_settings.log_to_file:
  332. log_file = app_settings.log_dir / "bambuddy.log"
  333. file_handler = RotatingFileHandler(
  334. log_file,
  335. maxBytes=app_settings.log_max_bytes,
  336. backupCount=app_settings.log_backup_count,
  337. encoding="utf-8",
  338. )
  339. file_handler.setLevel(log_level)
  340. file_handler.setFormatter(logging.Formatter(log_format))
  341. file_handler.addFilter(_trace_id_filter)
  342. file_handler.addFilter(_refused_header_filter)
  343. root_logger.addHandler(file_handler)
  344. logging.info("Logging to file: %s", log_file)
  345. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  346. # access logger with propagate=False by default, so without this attach
  347. # there is no on-disk record of which endpoint triggered a server-state
  348. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  349. # for exactly this reason. Filtered to write methods only
  350. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  351. # frontend don't churn the rotation window faster than it's useful.
  352. from backend.app.core.logging_filters import (
  353. CancelledPoolNoiseFilter,
  354. WriteRequestsOnlyFilter,
  355. )
  356. _attach_file_handler_to_uvicorn(file_handler)
  357. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  358. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  359. # Uvicorn's access logger has propagate=False (its own default), so the
  360. # root-attached TraceIDFilter never sees these records. Attach a
  361. # second instance directly so HTTP access lines carry the same trace
  362. # ID column as the application logs they correlate with.
  363. uvicorn_access_logger.addFilter(TraceIDFilter())
  364. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  365. # BaseHTTPMiddleware cancelling the inner task scope on client
  366. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  367. # underlying transaction leak; this filter only suppresses the residual
  368. # log records that pre-existing pools still emit during their cleanup.
  369. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  370. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  371. # handler (console included), whether or not file logging is on.
  372. from backend.app.core.logging_filters import ( # noqa: E402
  373. QueryTokenRedactFilter,
  374. ShutdownCancelledRequestFilter,
  375. )
  376. # First, so the traceback of a stream cancelled at shutdown is dropped before
  377. # the filters below render it.
  378. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  379. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  380. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  381. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  382. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  383. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  384. # keys in the query). Same as the runtime log-level toggle in support.py.
  385. logging.getLogger("httpcore").setLevel(logging.WARNING)
  386. logging.getLogger("httpx").setLevel(logging.WARNING)
  387. # aiosqlite logs every statement with its parameters at DEBUG.
  388. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  389. # Reduce noise from third-party libraries in production
  390. if not app_settings.debug:
  391. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  392. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  393. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  394. # Track active prints: {(printer_id, filename): archive_id}
  395. _active_prints: dict[tuple[int, str], int] = {}
  396. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  397. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  398. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  399. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  400. # instead of running its own grab-now chain when present, so the finish photo
  401. # captures the better-framed pre-bed-drop moment without us having to force
  402. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  403. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  404. #
  405. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  406. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  407. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  408. # bank and the others are not — so the consumer can't tell them apart and
  409. # must not rotate again.
  410. _stage22_finish_frames: dict[int, bytes] = {}
  411. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  412. # `finally` block (whether it captured a frame or not). The consumer in
  413. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  414. # so the FINISH-state fallback path — where moment and completion are dispatched
  415. # back-to-back — doesn't race past the producer with an empty pop, and the
  416. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  417. # grab (Bambu printers allow only one RTSP client at a time).
  418. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  419. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  420. # layer-change and on print-progress advances (#2547) while the model is still
  421. # printing, then consumed by the FINISH-state finish-photo path when the
  422. # dispatcher recorded that it injected End G-code into this print. Bambu
  423. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  424. # plate-swap) has run, so a live grab there would capture the swapped/empty
  425. # plate.
  426. #
  427. # The load-bearing property: both drivers are print telemetry that stops before
  428. # the End G-code executes — no further layer_num increases, and mc_percent
  429. # freezes — so the last banked frame is always the finished print before the
  430. # swap. Anything added as a third driver must hold that same property.
  431. _inprint_frame_bank: dict[int, bytes] = {}
  432. # Monotonic timestamp of the last banked frame per printer — throttles banking
  433. # so tall prints don't add a camera grab on every layer.
  434. _inprint_frame_bank_ts: dict[int, float] = {}
  435. # Minimum seconds between banked frames, except the final object layer which
  436. # always refreshes for the best framing.
  437. _INPRINT_BANK_MIN_INTERVAL = 25.0
  438. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  439. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  440. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  441. # the first connected status update for that connection; transitions back
  442. # to False whenever we observe `state.connected = False` so the next
  443. # reconnect re-arms reconciliation. Keyed by printer_id.
  444. _printer_reconciled_since_connect: dict[int, bool] = {}
  445. # Same edge, same keying, for priming the printer's calibration table exactly
  446. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  447. # is otherwise filled only when someone opens the Profiles page or Configure
  448. # Slot, when a GitHub backup runs, or when the printer happens to answer
  449. # somebody else's query on the report topic. Until then the AMS slot card has
  450. # no K value to show on the printers whose trays carry none of their own
  451. # (#2854 — H2-series report cali_idx and nothing more).
  452. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  453. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  454. # {(printer_id, filename): archive_id}
  455. _expected_prints: dict[tuple[int, str], int] = {}
  456. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  457. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  458. # every print on_print_start archived, those started from Bambu Studio, Handy or
  459. # the printer's screen included, so it is no proof of ownership on its own.
  460. _owned_print_archive_ids: set[int] = set()
  461. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  462. # Used by usage tracker to map 3MF slots to physical AMS trays
  463. _print_ams_mappings: dict[int, list[int]] = {}
  464. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  465. _print_cost_center_ids: dict[int, int] = {}
  466. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  467. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  468. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  469. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  470. # for the queue path. Cleared on print completion or TTL eviction.
  471. _print_plate_ids: dict[int, int] = {}
  472. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  473. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  474. _last_progress_milestone: dict[int, int] = {}
  475. # Track whether first layer complete notification has been sent for current print
  476. _first_layer_notified: dict[int, bool] = {}
  477. # Track whether we already sent a kill-switch stop for the current unauthorized print
  478. _unauthorized_print_kill_sent: set[int] = set()
  479. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  480. # lookup briefly so an unknown active print does not query the database on
  481. # every status frame. A short TTL keeps settings changes responsive.
  482. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  483. _kill_switch_setting_cache: tuple[bool, float] | None = None
  484. # Provider notification started when the kill switch stops a print. The later
  485. # MQTT print-complete callback awaits this task and only sends its regular
  486. # provider notification when the immediate attempt failed.
  487. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  488. # HMS faults already notified, with when each was last seen:
  489. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  490. # fault that flickers beside a held notice was forgotten on every gap and
  491. # notified on every return (#3226). The window is long because the measured
  492. # gaps reach 64 s.
  493. _notified_hms_errors: dict[int, dict[str, float]] = {}
  494. _HMS_CLEAR_GRACE_SECONDS = 600.0
  495. # The print state each printer was last seen in, and the faults recorded before
  496. # it last changed, which are forgotten as soon as they are gone (see
  497. # _take_new_hms_faults).
  498. _hms_print_state: dict[int, str] = {}
  499. _hms_forget_when_gone: dict[int, set[str]] = {}
  500. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  501. # Used for snapshot-diff detection at print completion
  502. _timelapse_baselines: dict[int, set[str]] = {}
  503. # Track printers waiting for bed to cool after print completion.
  504. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  505. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  506. _bed_cool_waiters: dict[int, dict] = {}
  507. # Track printers where the user explicitly stopped the print from the queue UI.
  508. # When on_print_complete fires with status "failed" for these printers we treat it
  509. # as "cancelled" (stopped by user) so the correct notification email is sent.
  510. _user_stopped_printers: set[int] = set()
  511. # Printers whose running print the kill switch stopped. Their completion is a
  512. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  513. _kill_switch_stopped: set[int] = set()
  514. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  515. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  516. # holds the previous observation so we only fire on the True → False edge (a
  517. # False → False repeat doesn't notify; an initial False at startup doesn't
  518. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  519. # holds the per-printer pending asyncio task that fires the notification
  520. # after a debounce window — cancelled if the printer reconnects before the
  521. # window elapses, so transient MQTT blips don't flood the user.
  522. _printer_last_connected: dict[int, bool] = {}
  523. # Printers whose relay offline event went out, so the reconnect publishes the
  524. # matching online event and a blip shorter than the debounce publishes neither.
  525. _printer_offline_published: set[int] = set()
  526. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  527. # Debounce: a printer must stay offline this long before we notify. Sized
  528. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  529. # so a single stale-trigger cooldown isn't enough to fire — only a real
  530. # offline that survives one reconnect attempt notifies.
  531. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  532. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  533. # when status="failed" to label the print's failure_reason in archives.
  534. #
  535. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  536. # which is wrong on two counts:
  537. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  538. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  539. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  540. # the public wiki) as part of its user-cancel sequence. Matching on the module
  541. # alone caused user-cancellations to be archived as "Layer shift" failures.
  542. # We now match by full short code only — anything not in this map leaves
  543. # failure_reason=None rather than guessing.
  544. # Values are the canonical camelCase failure-reason keys, NOT display labels
  545. # (issue #2974). The vocabulary is enforced on writes by
  546. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  547. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  548. # Statistics breakdown. Storing a label here instead put a second spelling of
  549. # the same cause into one column: the Failure Analysis widget groups on the raw
  550. # value, so a print the backend classified and an identical one a user
  551. # classified counted as two different reasons, and the label form could never
  552. # be translated because there was no key for ``t()`` to resolve.
  553. _HMS_FAILURE_REASONS: dict[str, str] = {
  554. # Layer shift / step loss
  555. "0300_4057": "layerShift",
  556. "0300_4068": "layerShift",
  557. "0300_800C": "layerShift",
  558. # Filament runout (printer-side & per-AMS-slot)
  559. "0300_8004": "filamentRunout",
  560. "0700_8011": "filamentRunout",
  561. "0701_8011": "filamentRunout",
  562. "0702_8011": "filamentRunout",
  563. "0703_8011": "filamentRunout",
  564. "0704_8011": "filamentRunout",
  565. "0705_8011": "filamentRunout",
  566. "0706_8011": "filamentRunout",
  567. "0707_8011": "filamentRunout",
  568. "07FF_8011": "filamentRunout",
  569. # Clogged nozzle / extruder
  570. "0300_4006": "cloggedNozzle",
  571. "0300_8016": "cloggedNozzle",
  572. "0300_801C": "cloggedNozzle",
  573. "0700_8003": "cloggedNozzle",
  574. "0700_8007": "cloggedNozzle",
  575. "0700_8013": "cloggedNozzle",
  576. "0701_8003": "cloggedNozzle",
  577. "0701_8007": "cloggedNozzle",
  578. "0701_8013": "cloggedNozzle",
  579. "0702_8003": "cloggedNozzle",
  580. # AI print monitoring — spaghetti / the model coming off the plate.
  581. # `spaghettiDetached` is a key the archive editor already offers for this
  582. # failure mode, not a new one, so a derived reason opens the dropdown on
  583. # that option rather than blank — and survives the next save, which clears
  584. # any value the editor does not recognise.
  585. #
  586. # A module-0x0C row is safe here despite the warning above: that warning is
  587. # about matching on the module alone, and 0C00_8042 is a full short code
  588. # with a documented meaning ("The AI print monitor has detected a spaghetti
  589. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  590. # cannot collide.
  591. #
  592. # 0300_8003's own text ends "before continuing your print", but on an X2D
  593. # it arrives with the print already paused, offering only
  594. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  595. #
  596. # Two neighbours are left out on purpose, so this does not get re-derived:
  597. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  598. # reads as a warning about a print that is still running, not a halt.
  599. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  600. # the waste chute. That is not the print failing.
  601. #
  602. # That line is drawn from the text, not from `severity`, because severity
  603. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  604. # module/error word with no level in it, and bambu_mqtt.py gives every
  605. # print_error entry a flat severity=3. Matching on the short code alone is
  606. # the right shape for derive_failure_reason, not an omission.
  607. "0300_8003": "spaghettiDetached",
  608. "0C00_8042": "spaghettiDetached",
  609. }
  610. def _hms_short_code(attr: int, code: int | str) -> str:
  611. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  612. if isinstance(code, str):
  613. code_int = int(code.replace("0x", ""), 16) if code else 0
  614. else:
  615. code_int = int(code or 0)
  616. attr_int = int(attr or 0)
  617. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  618. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  619. """Derive the failure_reason key for an archived print.
  620. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  621. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  622. no HMS code matches (don't guess — null is honest). The keys are the
  623. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  624. translated at render time.
  625. """
  626. if status in ("aborted", "cancelled"):
  627. return "userCancelled"
  628. if status != "failed":
  629. return None
  630. for err in hms_errors or []:
  631. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  632. if short_code in _HMS_FAILURE_REASONS:
  633. return _HMS_FAILURE_REASONS[short_code]
  634. return None
  635. # Track created_by_id for expected prints so the user email can be sent even when
  636. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  637. # {(printer_id, filename): created_by_id}
  638. _expected_print_creators: dict[tuple[int, str], int] = {}
  639. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  640. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  641. # tag tuple changes for the slot. Cleared when the slot is reported empty
  642. # so remove + reinsert reliably re-prompts the UI.
  643. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  644. async def _broadcast_unknown_tag(
  645. *,
  646. printer_id: int,
  647. ams_id: int,
  648. tray_id: int,
  649. tag_uid: str,
  650. tray_uuid: str,
  651. tray_type: str | None = None,
  652. tray_color: str | None = None,
  653. tray_sub_brands: str | None = None,
  654. tray_count: int | None = None,
  655. ) -> None:
  656. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  657. _logger = logging.getLogger(__name__)
  658. slot_key = (ams_id, tray_id)
  659. tag_key = (tag_uid or "", tray_uuid or "")
  660. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  661. if per_printer.get(slot_key) == tag_key:
  662. _logger.debug(
  663. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  664. printer_id,
  665. ams_id,
  666. tray_id,
  667. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  668. )
  669. return
  670. _logger.info(
  671. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  672. printer_id,
  673. ams_id,
  674. tray_id,
  675. tray_type,
  676. tray_color,
  677. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  678. )
  679. # Broadcast first; only commit the dedup if the WS write succeeds.
  680. # If broadcast raises, the next MQTT push retries instead of being
  681. # permanently silenced by a poisoned dedup entry.
  682. await ws_manager.broadcast(
  683. {
  684. "type": "unknown_tag",
  685. "printer_id": printer_id,
  686. "ams_id": ams_id,
  687. "tray_id": tray_id,
  688. "tag_uid": tag_uid,
  689. "tray_uuid": tray_uuid,
  690. "tray_type": tray_type,
  691. "tray_color": tray_color,
  692. "tray_sub_brands": tray_sub_brands,
  693. "tray_count": tray_count,
  694. }
  695. )
  696. per_printer[slot_key] = tag_key
  697. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  698. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  699. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  700. if per_printer is None:
  701. return
  702. per_printer.pop((ams_id, tray_id), None)
  703. # TTL for expected-print entries: evict registrations older than this to prevent
  704. # unbounded growth when a print is registered but never starts (e.g. printer
  705. # disconnect, app restart, print started from the printer panel).
  706. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  707. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  708. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  709. # Cleanup loop interval
  710. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  711. _expected_prints_cleanup_task: asyncio.Task | None = None
  712. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  713. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  714. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  715. possible_keys: list[tuple[int, str]] = []
  716. filename = (state.gcode_file or state.current_print or "").strip()
  717. subtask_name = (state.subtask_name or "").strip()
  718. if subtask_name:
  719. possible_keys.append((printer_id, subtask_name))
  720. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  721. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  722. if filename:
  723. base_name = filename.rsplit("/", 1)[-1]
  724. if base_name.endswith(".gcode.3mf"):
  725. root_name = base_name[: -len(".gcode.3mf")]
  726. possible_keys.append((printer_id, root_name))
  727. possible_keys.append((printer_id, base_name))
  728. possible_keys.append((printer_id, f"{root_name}.gcode"))
  729. possible_keys.append((printer_id, f"{root_name}.3mf"))
  730. elif base_name.endswith(".3mf"):
  731. root_name = base_name[: -len(".3mf")]
  732. possible_keys.append((printer_id, root_name))
  733. possible_keys.append((printer_id, base_name))
  734. elif base_name.endswith(".gcode"):
  735. root_name = base_name[: -len(".gcode")]
  736. possible_keys.append((printer_id, root_name))
  737. possible_keys.append((printer_id, f"{root_name}.3mf"))
  738. possible_keys.append((printer_id, base_name))
  739. else:
  740. possible_keys.append((printer_id, base_name))
  741. possible_keys.append((printer_id, f"{base_name}.3mf"))
  742. return possible_keys
  743. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  744. """The id of who started the print, unless that user has been deleted since.
  745. Deleting a user forgets them in printer_manager, but a print that ended a
  746. moment before still holds them.
  747. """
  748. if not print_user or print_user.get("user_id") is None:
  749. return None
  750. from backend.app.models.user import User
  751. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  752. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  753. """Check the cheap, process-local print ownership signals."""
  754. if printer_manager.get_current_print_user(printer_id):
  755. return True
  756. return any(
  757. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  758. for key in _build_status_print_keys(printer_id, state)
  759. )
  760. def _bind_active_print(
  761. printer_id: int,
  762. archive_id: int,
  763. archive_filename: str | None,
  764. filename: str | None = None,
  765. subtask_name: str | None = None,
  766. ) -> None:
  767. """Track a running print under every name its completion may report.
  768. One set for every path that binds a print (new archive, expected print,
  769. restart resume, fallback): the archive's file name, the name the printer
  770. reported, and the subtask with and without ``.3mf``. Paths that registered
  771. fewer names lost the bound archive at completion, and with it the plate
  772. restore's height (#3240), whenever MQTT reported a name they had left out.
  773. """
  774. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  775. if name:
  776. _active_prints[(printer_id, name)] = archive_id
  777. def _mark_owned_if_dispatched(archive) -> None:
  778. """Remember a running print's archive as Bambuddy's when it carries a
  779. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  780. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  781. if archive.billing_run_id is not None or archive.created_by_id is not None:
  782. _owned_print_archive_ids.add(archive.id)
  783. async def _is_printer_kill_switch_enabled_cached() -> bool:
  784. """Return the kill-switch setting without querying on every MQTT frame."""
  785. global _kill_switch_setting_cache
  786. now = time.monotonic()
  787. if _kill_switch_setting_cache is not None:
  788. enabled, expires_at = _kill_switch_setting_cache
  789. if now < expires_at:
  790. return enabled
  791. async with async_session() as db:
  792. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  793. enabled = await is_printer_kill_switch_enabled(db)
  794. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  795. return enabled
  796. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  797. """Resolve whether the current print was started by Bambuddy.
  798. ``None`` means identity is not yet safe to decide. The kill switch must
  799. defer in that case: stopping a print is irreversible, and the first status
  800. frames after a restart may arrive before all subtask fields are populated.
  801. """
  802. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  803. return True
  804. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  805. # printer's screen) play gcode from its read-only system partition, where no
  806. # user file can be. Only that path counts: a calibration *name* proves
  807. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  808. # path, and any print can be given that name.
  809. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  810. return True
  811. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  812. # which nothing distinguishes from a user's file given that name, so it is
  813. # not exempt: with the kill switch on, calibrate on those printers with the
  814. # switch off.
  815. possible_keys = _build_status_print_keys(printer_id, state)
  816. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  817. # is on disk. subtask_id is minted per print and pins the answer to the job
  818. # actually running, rather than to an unrelated one that reuses a filename.
  819. raw_subtask_id = getattr(state, "subtask_id", None)
  820. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  821. if subtask_id == "":
  822. # Not reported yet: the first frames after a restart can lack it.
  823. return None
  824. from backend.app.models.archive import PrintArchive
  825. if subtask_id == "0":
  826. # A print started outside the cloud from Bambu Studio, Handy or the
  827. # printer's screen reports "0", so there is no id to match: one of
  828. # Bambuddy's printing archives on this printer under the name the
  829. # printer reports, compared as the printer echoes names (spaces become
  830. # underscores). Nothing reported to compare yet: wait.
  831. reported = {_normalise_subtask_name(name) for _pid, name in possible_keys} - {""}
  832. if not reported:
  833. return None
  834. dispatched = await db.execute(
  835. select(PrintArchive)
  836. .where(
  837. PrintArchive.printer_id == printer_id,
  838. PrintArchive.status == "printing",
  839. or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)),
  840. # An archive with a real id of its own is a print that reported
  841. # one: a "0" print is not it, even under the same name (one whose
  842. # completion was missed would otherwise cover it).
  843. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  844. )
  845. .order_by(PrintArchive.created_at.desc())
  846. )
  847. archive = next((a for a in dispatched.scalars() if _archive_name_forms(a) & reported), None)
  848. else:
  849. result = await db.execute(
  850. select(PrintArchive)
  851. .where(
  852. PrintArchive.printer_id == printer_id,
  853. PrintArchive.status == "printing",
  854. PrintArchive.subtask_id == subtask_id,
  855. )
  856. .order_by(PrintArchive.created_at.desc())
  857. .limit(1)
  858. )
  859. archive = result.scalar_one_or_none()
  860. # An archive row on its own proves nothing: `on_print_start` archives every
  861. # print it observes, including ones started from Bambu Studio or Handy, and
  862. # stamps them with the same status and subtask_id. Authorizing on its mere
  863. # existence would disable the kill switch the moment the 3MF finishes
  864. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  865. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  866. # (carried over from the queue item that started it).
  867. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  868. # Rehydrate the fast in-memory path for subsequent status frames. Include
  869. # both the archive filename and every normalized key reported by MQTT.
  870. _owned_print_archive_ids.add(archive.id)
  871. _active_prints[(printer_id, archive.filename)] = archive.id
  872. for key in possible_keys:
  873. _active_prints[key] = archive.id
  874. return True
  875. # No dispatch marker. Before calling this someone else's print, check whether
  876. # Bambuddy has a job of its own running on this printer: a library-file
  877. # dispatch has no archive at send time, and an archive created seconds later
  878. # by `on_print_start` carries neither marker. The queue row, which the
  879. # scheduler commits to status="printing" before the MQTT send, is the one
  880. # durable record every Bambuddy print has. It cannot be tied to this
  881. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  882. # print is irreversible, and refusing to act costs nothing but a log line.
  883. from backend.app.models.print_queue import PrintQueueItem
  884. dispatched_here = await db.scalar(
  885. select(PrintQueueItem.id)
  886. .where(
  887. PrintQueueItem.printer_id == printer_id,
  888. PrintQueueItem.status == "printing",
  889. )
  890. .limit(1)
  891. )
  892. if dispatched_here is not None:
  893. return None
  894. return False
  895. async def _send_kill_switch_provider_notification(
  896. printer_id: int,
  897. printer_name: str,
  898. data: dict,
  899. ) -> bool:
  900. """Send the immediate print-stopped provider notification.
  901. Returning a success flag lets the normal MQTT completion path retry when
  902. this early notification could not be delivered.
  903. """
  904. logger = logging.getLogger(__name__)
  905. try:
  906. async with async_session() as db:
  907. await notification_service.on_print_complete(
  908. printer_id,
  909. printer_name,
  910. "stopped",
  911. data,
  912. db,
  913. )
  914. return True
  915. except Exception as e:
  916. logger.warning(
  917. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  918. printer_id,
  919. e,
  920. )
  921. return False
  922. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  923. """Wait for an immediate kill-switch notification, if one was scheduled."""
  924. if task is None:
  925. return False
  926. try:
  927. return await task
  928. except Exception as e:
  929. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  930. return False
  931. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  932. """Capture the smart plug lifetime counter on the archive at print start.
  933. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  934. tracking survives a backend restart mid-print. The print-end handler reads
  935. this value back from the DB and computes the delta against the current
  936. plug counter.
  937. """
  938. _logger = logging.getLogger(__name__)
  939. try:
  940. candidates = await energy_plug_candidates(db, printer_id)
  941. if not candidates:
  942. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  943. return False
  944. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  945. if selected is None:
  946. # Naming the plugs matters here: with several linked to one printer
  947. # this is the difference between "the meter is offline" and "you
  948. # linked only accessories" (#2859).
  949. _logger.warning(
  950. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  951. printer_id,
  952. archive.id,
  953. ", ".join(plug.name for plug in candidates),
  954. )
  955. return False
  956. plug, energy = selected
  957. archive.energy_start_kwh = float(energy["total"])
  958. # With the plug's snapshots, what lets the cost follow the price over
  959. # the print rather than take the price at its end (#1251). A price that
  960. # can't be had must not cost the print its energy reading.
  961. archive.energy_start_at = utcnow_naive()
  962. archive.energy_start_plug_id = plug.id
  963. try:
  964. from backend.app.services.energy_price import current_price
  965. archive.energy_start_price = await current_price(db)
  966. except Exception as e:
  967. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  968. archive.energy_start_price = None
  969. await db.commit()
  970. _logger.info(
  971. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  972. f" ({context})" if context else "",
  973. archive.id,
  974. plug.name,
  975. energy["total"],
  976. )
  977. return True
  978. except Exception as e:
  979. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  980. return False
  981. def forget_print_creator(user_id: int) -> None:
  982. """The print-start emails of a deleted user's jobs go to nobody, not to
  983. whoever is given the id next (SQLite reuses it)."""
  984. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  985. del _expected_print_creators[key]
  986. async def forget_printer(printer_id: int) -> None:
  987. """Drop what is kept for a deleted printer's id, here and in the services.
  988. SQLite used to give the id to the next printer created, which inherited it
  989. all: the running print's owner (its prints passed the kill switch and were
  990. billed to that user), the plate-clear gate, pending and suppressed
  991. notifications, the camera feed, the plate references. Ids are no longer
  992. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  993. stay. Called after the delete is committed, and again by work that was in
  994. flight and wrote state back.
  995. Every printer-keyed map of this module is listed here or, with the reason,
  996. in tests/unit/test_forget_printer.py.
  997. """
  998. from backend.app.api.routes import camera
  999. from backend.app.services import (
  1000. bambu_ftp,
  1001. kprofile_drift,
  1002. layer_timelapse,
  1003. plate_detection,
  1004. print_dispatch_context,
  1005. usage_tracker,
  1006. )
  1007. from backend.app.services.notify_live_activities import notify_live_activities
  1008. from backend.app.services.obico_detection import obico_detection_service
  1009. from backend.app.services.printer_file_cache import printer_file_cache
  1010. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1011. archive_ids = set()
  1012. for tracked in (_active_prints, _expected_prints):
  1013. for key in [key for key in tracked if key[0] == printer_id]:
  1014. archive_ids.add(tracked.pop(key))
  1015. for archive_id in archive_ids:
  1016. _owned_print_archive_ids.discard(archive_id)
  1017. _print_ams_mappings.pop(archive_id, None)
  1018. _print_cost_center_ids.pop(archive_id, None)
  1019. _print_plate_ids.pop(archive_id, None)
  1020. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1021. for key in [key for key in tracked if key[0] == printer_id]:
  1022. del tracked[key]
  1023. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1024. _ams_index_only_logged.discard(key)
  1025. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1026. del _ams_alarm_cooldown[key]
  1027. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1028. # A kill-switch notice is about a stop that happened and is left to finish.
  1029. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1030. task = tasks.pop(printer_id, None)
  1031. if task is not None:
  1032. task.cancel()
  1033. for keyed in (
  1034. _stage22_finish_frames,
  1035. _stage22_finish_in_flight,
  1036. _inprint_frame_bank,
  1037. _inprint_frame_bank_ts,
  1038. _printer_reconciled_since_connect,
  1039. _printer_kprofiles_primed_since_connect,
  1040. _last_progress_milestone,
  1041. _first_layer_notified,
  1042. _kill_switch_notification_tasks,
  1043. _notified_hms_errors,
  1044. _hms_print_state,
  1045. _hms_forget_when_gone,
  1046. _timelapse_baselines,
  1047. _bed_cool_waiters,
  1048. _printer_last_connected,
  1049. _unknown_tag_last_broadcast,
  1050. _last_status_broadcast,
  1051. _connection_watchdog_last_attempt,
  1052. ):
  1053. keyed.pop(printer_id, None)
  1054. for marked in (
  1055. _unauthorized_print_kill_sent,
  1056. _user_stopped_printers,
  1057. _kill_switch_stopped,
  1058. _printer_offline_published,
  1059. _nozzle_count_updated,
  1060. _runtime_seen_connected,
  1061. ):
  1062. marked.discard(printer_id)
  1063. printer_manager.forget_printer(printer_id)
  1064. printer_file_cache.forget_printer(printer_id)
  1065. print_dispatch_context.clear(printer_id)
  1066. kprofile_drift.forget_printer(printer_id, deleted=True)
  1067. layer_timelapse.cancel_session(printer_id)
  1068. usage_tracker.forget_printer(printer_id)
  1069. obico_detection_service.forget_printer(printer_id)
  1070. bambu_ftp.clear_3mf_cache(printer_id)
  1071. await camera.forget_printer(printer_id)
  1072. printers.clear_cover_cache(printer_id)
  1073. print_scheduler.forget_printer(printer_id)
  1074. notify_live_activities.forget_printer(printer_id)
  1075. plate_detection.remove_printer_references(printer_id)
  1076. def register_expected_print(
  1077. printer_id: int,
  1078. filename: str,
  1079. archive_id: int,
  1080. ams_mapping: list[int] | None = None,
  1081. created_by_id: int | None = None,
  1082. cost_center_id: int | None = None,
  1083. plate_id: int | None = None,
  1084. ):
  1085. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1086. # Store with multiple filename variations to catch different naming patterns
  1087. _expected_prints[(printer_id, filename)] = archive_id
  1088. # Also store without .3mf extension if present
  1089. if filename.endswith(".3mf"):
  1090. base = filename[:-4]
  1091. _expected_prints[(printer_id, base)] = archive_id
  1092. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1093. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1094. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1095. # path attributes the whole file's filament total to the spool instead of just
  1096. # the printed plate (#1697). They describe this dispatch: one that has none
  1097. # drops what an earlier dispatch of the archive left (sent, never started),
  1098. # unless a plate of the archive is printing now and still needs them.
  1099. archive_printing = archive_id in set(_active_prints.values())
  1100. if ams_mapping is not None:
  1101. _print_ams_mappings[archive_id] = ams_mapping
  1102. elif not archive_printing:
  1103. _print_ams_mappings.pop(archive_id, None)
  1104. if cost_center_id is not None:
  1105. _print_cost_center_ids[archive_id] = cost_center_id
  1106. elif not archive_printing:
  1107. _print_cost_center_ids.pop(archive_id, None)
  1108. if plate_id is not None:
  1109. _print_plate_ids[archive_id] = plate_id
  1110. elif not archive_printing:
  1111. _print_plate_ids.pop(archive_id, None)
  1112. # Store created_by_id so the user start email can be sent even when the archive
  1113. # itself has no created_by_id (e.g. library-file-based queue prints)
  1114. if created_by_id is not None:
  1115. _expected_print_creators[(printer_id, filename)] = created_by_id
  1116. if filename.endswith(".3mf"):
  1117. base = filename[:-4]
  1118. _expected_print_creators[(printer_id, base)] = created_by_id
  1119. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1120. # Record registration time for TTL-based eviction
  1121. _registered_at = time.monotonic()
  1122. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1123. if filename.endswith(".3mf"):
  1124. base = filename[:-4]
  1125. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1126. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1127. logging.getLogger(__name__).info(
  1128. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1129. )
  1130. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1131. """Undo :func:`register_expected_print` when the print never went out.
  1132. Registration has to happen *before* the MQTT print command, because the
  1133. printer can report the print before the line after the send executes. So
  1134. every path that registers and then fails to send — a cancel winning the
  1135. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1136. between — leaves an expectation for a print that will never arrive.
  1137. The TTL sweep evicts those after two hours, which is far longer than it
  1138. takes a user to react to a failed dispatch by pressing print again: that
  1139. reprint would be folded into the *old* archive and take the stale
  1140. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1141. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1142. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1143. are keyed by archive, not by file, so they may only be dropped once no
  1144. live key still points at that archive.
  1145. """
  1146. keys = [(printer_id, filename)]
  1147. if filename.endswith(".3mf"):
  1148. base = filename[:-4]
  1149. keys.append((printer_id, base))
  1150. keys.append((printer_id, f"{base}.gcode"))
  1151. removed = False
  1152. for key in keys:
  1153. if _expected_prints.pop(key, None) is not None:
  1154. removed = True
  1155. _expected_print_creators.pop(key, None)
  1156. _expected_print_registered_at.pop(key, None)
  1157. # Still needed by another expected print of the archive, or a plate of it
  1158. # that is printing, as in the sweep.
  1159. if archive_id not in set(_expected_prints.values()) | set(_active_prints.values()):
  1160. _print_ams_mappings.pop(archive_id, None)
  1161. _print_cost_center_ids.pop(archive_id, None)
  1162. _print_plate_ids.pop(archive_id, None)
  1163. if removed:
  1164. logging.getLogger(__name__).info(
  1165. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1166. printer_id,
  1167. filename,
  1168. archive_id,
  1169. )
  1170. def _compute_run_filament_grams(
  1171. status: str,
  1172. archive_filament_used_grams: float | None,
  1173. progress: float | int | None,
  1174. usage_results: list[dict] | None,
  1175. ) -> float | None:
  1176. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1177. Priority for every status:
  1178. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1179. weight delta — same source that drives "Total Consumed" on the
  1180. Inventory page, so Stats and Inventory totals stay aligned).
  1181. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1182. back to the canonical "this print used X" value).
  1183. 3. For partial statuses: ``estimate * progress%``.
  1184. 4. ``None`` if nothing is known.
  1185. """
  1186. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1187. if tracked_grams > 0:
  1188. return round(tracked_grams, 1)
  1189. if status == "completed":
  1190. return archive_filament_used_grams
  1191. if archive_filament_used_grams:
  1192. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1193. if scale > 0:
  1194. return round(archive_filament_used_grams * scale, 1)
  1195. return None
  1196. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1197. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1198. stored_ams_mapping = data.get("ams_mapping")
  1199. if not stored_ams_mapping and archive_id:
  1200. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1201. return stored_ams_mapping
  1202. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1203. """Resolve plate_id for print start without consuming stored direct-Print state.
  1204. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1205. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1206. read it back at print-start without popping (the entry is popped on print
  1207. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1208. """
  1209. if archive_id is None:
  1210. return None
  1211. return _print_plate_ids.get(archive_id)
  1212. def _partial_progress_scale(progress: int | float | None) -> float:
  1213. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1214. Used by every site that multiplies a "would-have-used" slicer estimate
  1215. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1216. so the three sites in ``_background_notifications`` (and the per-plate
  1217. override helper) can't drift apart on the coercion shape.
  1218. """
  1219. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1220. def _scope_notification_archive_data_to_plate(
  1221. archive_data: dict,
  1222. archive_file_path: str | None,
  1223. plate_id: int | None,
  1224. print_status: str,
  1225. progress: int | float | None,
  1226. base_dir: Path,
  1227. ) -> dict:
  1228. """Override summed-across-plates totals in ``archive_data`` with the values
  1229. for ``plate_id`` so the completion notification reports what was actually
  1230. printed, not the whole project (#1785).
  1231. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1232. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1233. the archive card's "whole project" headline, wrong for the completion
  1234. notification of a single-plate print. The queue UI already re-reads the
  1235. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1236. notification payload (filament grams, time estimate, per-slot breakdown).
  1237. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1238. no per-plate values — in every fail case the original ``archive_data`` is
  1239. returned unchanged so the notification still sends.
  1240. """
  1241. if plate_id is None or not archive_file_path:
  1242. return archive_data
  1243. from backend.app.utils.threemf_tools import (
  1244. extract_filament_usage_from_3mf,
  1245. extract_print_time_from_3mf,
  1246. )
  1247. archive_path = base_dir / archive_file_path
  1248. if not archive_path.exists():
  1249. return archive_data
  1250. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1251. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1252. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1253. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1254. if plate_time:
  1255. archive_data["print_time_seconds"] = plate_time
  1256. # Gate both the grams headline AND the per-slot breakdown on the same
  1257. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1258. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1259. # to the project-level grams the archive columns already provide rather
  1260. # than ship a project-level headline next to an all-zero per-plate
  1261. # breakdown.
  1262. if plate_grams > 0:
  1263. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1264. archive_data["filament_slots"] = [
  1265. {
  1266. "slot_id": s.get("slot_id"),
  1267. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1268. "type": s.get("type", ""),
  1269. "color": s.get("color", ""),
  1270. }
  1271. for s in plate_slots
  1272. ]
  1273. return archive_data
  1274. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1275. """Best-effort filament metadata from the MQTT print-start snapshot.
  1276. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1277. file during print, see #1533) so the fallback PrintArchive still has
  1278. enough filament info to support the inventory views and AMS-expansion
  1279. planning the operator opens it for. Returns a dict with optional
  1280. ``filament_type`` and ``filament_color`` keys in the same
  1281. comma-separated format the 3MF extractor produces, so the rest of the
  1282. codebase treats the fallback archive identically to a normal one.
  1283. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1284. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1285. entries). When supplied, only the slots actually consumed by this
  1286. print contribute. Without it the function falls back to every loaded
  1287. AMS slot — less accurate but still useful.
  1288. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1289. that the unit tests pass directly, AND the on_print_start callback
  1290. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1291. bambu_mqtt service hands to main.py at runtime. The original
  1292. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1293. handled the inner shape and silently returned ``{}`` for every real
  1294. print start, leaving fallback archives' filament fields NULL — the
  1295. exact regression the fix was meant to close. Reported with a log
  1296. proving the AMS state was right there at
  1297. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1298. """
  1299. result: dict[str, str] = {}
  1300. # Look at the on_print_start wrapper first, then the inner shape.
  1301. raw_data = (data or {}).get("raw_data")
  1302. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1303. if not isinstance(ams_root, dict):
  1304. ams_root = (data or {}).get("ams") or {}
  1305. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1306. if not isinstance(ams_units, list) or not ams_units:
  1307. return result
  1308. from backend.app.services.print_scheduler import _global_tray_id
  1309. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1310. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1311. loaded: dict[int, tuple[str, str]] = {}
  1312. for unit in ams_units:
  1313. if not isinstance(unit, dict):
  1314. continue
  1315. try:
  1316. unit_id = int(unit.get("id", 0))
  1317. except (TypeError, ValueError):
  1318. continue
  1319. for tray in unit.get("tray") or []:
  1320. if not isinstance(tray, dict):
  1321. continue
  1322. try:
  1323. tray_id = int(tray.get("id", 0))
  1324. except (TypeError, ValueError):
  1325. continue
  1326. ttype = (tray.get("tray_type") or "").strip()
  1327. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1328. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1329. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1330. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1331. if not ttype:
  1332. continue # Empty / unloaded slot.
  1333. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1334. if not loaded:
  1335. return result
  1336. if ams_mapping:
  1337. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1338. filaments = [loaded[g] for g in used_ids if g in loaded]
  1339. if not filaments:
  1340. return result # Mapping points entirely at slots we have no data for.
  1341. else:
  1342. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1343. types_joined = ",".join(f[0] for f in filaments)
  1344. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1345. # Column limits per backend/app/models/archive.py: filament_type=50,
  1346. # filament_color=200.
  1347. if types_joined:
  1348. result["filament_type"] = types_joined[:50]
  1349. if colors_joined:
  1350. result["filament_color"] = colors_joined[:200]
  1351. return result
  1352. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1353. """Start a layer-timelapse session for *archive_id* when the printer has
  1354. an external camera configured. Returns True if a session was started.
  1355. Three call sites in on_print_start (expected-archive promotion, fallback
  1356. archive creation, fresh-archive creation) used to inline this same
  1357. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1358. on the first pass). Centralising the conditional + call here makes the
  1359. contract testable in isolation and keeps the three sites locked in step.
  1360. """
  1361. if not (printer.external_camera_enabled and printer.external_camera_url):
  1362. return False
  1363. from backend.app.services.layer_timelapse import start_session
  1364. start_session(
  1365. printer_id,
  1366. archive_id,
  1367. printer.external_camera_url,
  1368. printer.external_camera_type or "mjpeg",
  1369. snapshot_url=printer.external_camera_snapshot_url,
  1370. rotation=getattr(printer, "camera_rotation", 0),
  1371. )
  1372. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1373. return True
  1374. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1375. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1376. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1377. — since #2926 — the description the parser already resolved, which is preferred
  1378. when present so the queue's failure reason reads the same as the status
  1379. response. The short code still produces the bracketed label, and still
  1380. resolves the sentence for a caller whose entries predate the field. An entry
  1381. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1382. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1383. label when no description is on file. Returns None for an empty list so
  1384. callers can leave error_message unset.
  1385. """
  1386. if not hms_errors:
  1387. return None
  1388. from backend.app.services.hms_errors import get_error_description
  1389. parts: list[str] = []
  1390. for err in hms_errors:
  1391. try:
  1392. # `_hms_short_code` rather than a local derivation: this one used to
  1393. # format the error without masking it to 16 bits, so an `hms[]` entry
  1394. # whose code carries an alert-level group produced a five-digit label
  1395. # like "0500_3000A" — not a code the user can look up, and never a
  1396. # catalogue key, so the sentence was lost with it.
  1397. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1398. except (TypeError, ValueError):
  1399. continue
  1400. description = err.get("description") or get_error_description(short_code)
  1401. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1402. # groups and is not a code anyone can look up; its full code in the
  1403. # printer screen's four groups is (#2728).
  1404. full_code = str(err.get("full_code") or "")
  1405. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1406. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1407. return "; ".join(parts) if parts else None
  1408. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1409. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1410. print completes successfully. Gated to status=='completed': failed, cancelled
  1411. and aborted prints do not count as usage. Caller is responsible for committing
  1412. the session. No-op when the queue item has no linked library file (e.g. reprints
  1413. from an archive). See #1008."""
  1414. if queue_status != "completed" or item.library_file_id is None:
  1415. return
  1416. from backend.app.models.library import LibraryFile
  1417. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1418. if lib_file is None:
  1419. return
  1420. lib_file.print_count = (lib_file.print_count or 0) + 1
  1421. lib_file.last_printed_at = datetime.now(timezone.utc)
  1422. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1423. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1424. When on_print_complete fires with status 'failed' for a printer in this set we
  1425. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1426. rather than a 'print failed' notification.
  1427. """
  1428. _user_stopped_printers.add(printer_id)
  1429. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1430. _last_status_broadcast: dict[int, str] = {}
  1431. # Track printers where we've updated nozzle_count
  1432. _nozzle_count_updated: set[int] = set()
  1433. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1434. """Wait the debounce window then fire `on_printer_offline` if the printer
  1435. is still offline.
  1436. Scheduled by `on_printer_status_change` on the connected → disconnected
  1437. edge (#1752). Cancelled by the same handler if the printer reconnects
  1438. before the window elapses, so a single MQTT blip + recovery doesn't
  1439. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1440. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1441. route through the same status-change callback, so this covers both.
  1442. """
  1443. logger = logging.getLogger(__name__)
  1444. try:
  1445. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1446. still_offline = not printer_manager.is_connected(printer_id)
  1447. logger.info(
  1448. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1449. printer_id,
  1450. still_offline,
  1451. )
  1452. if not still_offline:
  1453. return
  1454. async with async_session() as db:
  1455. from backend.app.models.printer import Printer
  1456. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1457. printer = result.scalar_one_or_none()
  1458. if not printer:
  1459. logger.warning(
  1460. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1461. printer_id,
  1462. )
  1463. return
  1464. # Recorded only when the relay can publish it, so the reconnect's
  1465. # online event always has an offline before it.
  1466. if mqtt_relay.enabled and mqtt_relay.connected:
  1467. _printer_offline_published.add(printer_id)
  1468. try:
  1469. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1470. except Exception as e:
  1471. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1472. logger.info(
  1473. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1474. printer_id,
  1475. printer.name,
  1476. )
  1477. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1478. except asyncio.CancelledError:
  1479. raise
  1480. except Exception as e:
  1481. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1482. finally:
  1483. _printer_offline_notify_tasks.pop(printer_id, None)
  1484. def _hms_notify_key(error) -> str:
  1485. """What identifies a fault for notification de-duplication.
  1486. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1487. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1488. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1489. and -0006 together) shared a key and only the first was ever notified. An
  1490. entry without a full code falls back to attr and code together.
  1491. """
  1492. full_code = getattr(error, "full_code", "") or ""
  1493. if full_code:
  1494. return full_code.upper()
  1495. return f"{error.attr:08X}:{error.code}"
  1496. def _hms_fault_counts(error) -> bool:
  1497. """Whether a fault counts as a problem: the same rule the frontend's
  1498. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1499. It counts when Bambu publishes text for it or it offers action buttons, and
  1500. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1501. no actions does not count: those are things like "the top cover is open" or
  1502. "the chamber is hot, fan speed increased", which a printer can hold through
  1503. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1504. it always has; those are prompts such as "unable to start drying" (#2728).
  1505. """
  1506. if error.severity < 1:
  1507. return False
  1508. has_actions = bool(getattr(error, "actions", None))
  1509. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1510. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1511. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1512. """The new faults that count (see ``_hms_fault_counts``).
  1513. These go to the MQTT relay; the caller also needs a description before it
  1514. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1515. used to read ``severity >= 2`` when severity held the part byte; on the real
  1516. level that would drop the task-stopping errors (#2728).
  1517. """
  1518. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1519. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1520. """The faults on this printer not notified yet, and record them as notified.
  1521. Tracking is updated before anything is sent, so concurrent status callbacks
  1522. cannot notify the same fault twice. A notified fault is forgotten once it
  1523. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1524. and on is notified once (#3226), while one that clears and comes back much
  1525. later is notified again.
  1526. When ``print_state`` changes (a print resumed, started or finished), every
  1527. fault recorded so far is forgotten the first time it is gone, without the
  1528. wait: a runout fixed before resuming must be notified if it happens again a
  1529. few minutes later, while the printer sits paused. Not only the faults gone
  1530. at the change itself, because the update that flips the state can still
  1531. carry the old fault (a ``print_error`` entry stays until a payload brings
  1532. ``hms``).
  1533. """
  1534. now = time.time()
  1535. current = {_hms_notify_key(e) for e in errors}
  1536. seen = _notified_hms_errors.setdefault(printer_id, {})
  1537. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1538. if print_state is not None:
  1539. print_state = print_state.upper()
  1540. if _hms_print_state.get(printer_id, print_state) != print_state:
  1541. forget_when_gone.update(seen)
  1542. _hms_print_state[printer_id] = print_state
  1543. for key, last_seen in list(seen.items()):
  1544. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1545. del seen[key]
  1546. forget_when_gone.discard(key)
  1547. new = current - seen.keys()
  1548. for key in current:
  1549. seen[key] = now
  1550. if not seen:
  1551. _notified_hms_errors.pop(printer_id, None)
  1552. if not forget_when_gone:
  1553. _hms_forget_when_gone.pop(printer_id, None)
  1554. return _hms_errors_to_notify(errors, new)
  1555. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1556. # "Printing", -1 and 255 are "no stage" (#3211).
  1557. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1558. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1559. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1560. Records it as notified. Called only for a printing state with progress above 0.
  1561. Progress before the first layer is not progress through the print (#3211).
  1562. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1563. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1564. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1565. 75% notification together with Print Started, and since 75 was then on
  1566. record, 25 and 50 could never fire. So nothing counts while the printer
  1567. reports a layer count but has not started layer 1.
  1568. Without a layer count -- a print whose first frame carried no
  1569. ``total_layer_num``, until the pushall that asks for it is answered
  1570. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1571. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1572. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1573. reports neither keeps the old behaviour rather than never notifying.
  1574. """
  1575. if (state.layer_num or 0) < 1:
  1576. if (state.total_layers or 0) > 0:
  1577. return None
  1578. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1579. return None
  1580. progress = state.progress or 0
  1581. current_milestone = 0
  1582. if progress >= 75:
  1583. current_milestone = 75
  1584. elif progress >= 50:
  1585. current_milestone = 50
  1586. elif progress >= 25:
  1587. current_milestone = 25
  1588. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1589. _last_progress_milestone[printer_id] = current_milestone
  1590. return current_milestone
  1591. return None
  1592. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1593. """Handle printer status changes - broadcast via WebSocket."""
  1594. try:
  1595. notify_live_activities.observe(printer_id, state)
  1596. except Exception:
  1597. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1598. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1599. # transitions disconnected → connected — which covers both Bambuddy
  1600. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1601. # `reconcile_stale_active_prints` exactly once for this connection so
  1602. # any archive still in `status="printing"` that can't actually be
  1603. # running anymore (printer IDLE / different subtask / empty subtask)
  1604. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1605. # finished during a disconnect window + a smart-plug power cycle
  1606. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1607. # next boot. Reconciliation runs concurrently — it must not block the
  1608. # WebSocket dedup / broadcast logic below, and the connected edge is
  1609. # marked True BEFORE the await so concurrent status updates inside
  1610. # the same connection don't re-trigger reconciliation.
  1611. #
  1612. # Wait for a real push_status before reconciling (#1679): MQTT
  1613. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1614. # the connection, BEFORE `_request_push_all` round-trips. At that
  1615. # instant the `PrinterState` is still on construction defaults — most
  1616. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1617. # If reconcile spawns here, every in-flight archive falls through to
  1618. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1619. # creates a duplicate archive on the real PRINT COMPLETE and
  1620. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1621. # keeps the #1542 mechanism intact: once the first real push_status
  1622. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1623. # fires again with the flag still False — reconcile then runs against
  1624. # actual evidence.
  1625. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1626. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1627. _printer_reconciled_since_connect[printer_id] = True
  1628. spawn_background_task(
  1629. reconcile_stale_active_prints(printer_id),
  1630. name=f"reconcile-stale-prints-{printer_id}",
  1631. )
  1632. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1633. # Re-arm so the next reconnect triggers reconciliation again.
  1634. _printer_reconciled_since_connect[printer_id] = False
  1635. # Same edge, for the calibration table the AMS card reads its K values from.
  1636. #
  1637. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1638. # tables to ask for. A `state_known` gate alone is not enough: the first
  1639. # real push_status is what makes the state known, and the nozzle fields do
  1640. # not always arrive in it. Latching there would spend this connection's one
  1641. # attempt on a printer that could not yet say what was fitted.
  1642. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1643. if (
  1644. state.connected
  1645. and state_known
  1646. and nozzle_known
  1647. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1648. ):
  1649. _printer_kprofiles_primed_since_connect[printer_id] = True
  1650. spawn_background_task(
  1651. prime_kprofile_table(printer_id),
  1652. name=f"prime-kprofiles-{printer_id}",
  1653. )
  1654. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1655. _printer_kprofiles_primed_since_connect[printer_id] = False
  1656. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1657. # else in the AMS report changing -- a power cycle does it to every slot --
  1658. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1659. # while the printer is idle; needs_check is cheap and throttled per slot.
  1660. # Guarded: nothing here may stop the status broadcast below.
  1661. try:
  1662. if not state.connected:
  1663. kprofile_drift.forget_printer(printer_id)
  1664. elif kprofile_drift.needs_check(printer_id, state):
  1665. spawn_background_task(
  1666. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1667. name=f"reapply-kprofiles-{printer_id}",
  1668. )
  1669. except Exception:
  1670. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1671. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1672. # connected → disconnected. The "back online" channel is already covered
  1673. # by the print-failure notification (firmware reports gcode_state=FAILED
  1674. # on reconnect of an interrupted print), so there is no online
  1675. # notification. The MQTT relay gets both: offline after the debounce, and
  1676. # online on the reconnect that follows a published offline.
  1677. prev_connected = _printer_last_connected.get(printer_id)
  1678. _printer_last_connected[printer_id] = state.connected
  1679. if prev_connected is True and not state.connected:
  1680. existing = _printer_offline_notify_tasks.get(printer_id)
  1681. if existing is None or existing.done():
  1682. logging.getLogger(__name__).info(
  1683. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1684. printer_id,
  1685. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1686. )
  1687. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1688. _maybe_notify_printer_offline(printer_id),
  1689. name=f"printer-offline-notify-{printer_id}",
  1690. )
  1691. elif state.connected:
  1692. # Kept until the relay can actually send online: with its broker down
  1693. # now, the next status update after the reconnect sends it.
  1694. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1695. _printer_offline_published.discard(printer_id)
  1696. printer_info = printer_manager.get_printer(printer_id)
  1697. if printer_info:
  1698. try:
  1699. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1700. except Exception as e:
  1701. logging.getLogger(__name__).warning(
  1702. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1703. )
  1704. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1705. if pending is not None and not pending.done():
  1706. logging.getLogger(__name__).info(
  1707. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1708. printer_id,
  1709. )
  1710. pending.cancel()
  1711. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1712. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1713. temps = state.temperatures or {}
  1714. nozzle_temp = round(temps.get("nozzle", 0))
  1715. bed_temp = round(temps.get("bed", 0))
  1716. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1717. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1718. # Auto-detect dual-nozzle printers from MQTT temperature data
  1719. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1720. _nozzle_count_updated.add(printer_id)
  1721. # Update nozzle_count in database
  1722. async with async_session() as db:
  1723. from backend.app.models.printer import Printer
  1724. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1725. printer = result.scalar_one_or_none()
  1726. if printer and printer.nozzle_count != 2:
  1727. printer.nozzle_count = 2
  1728. await db.commit()
  1729. logging.getLogger(__name__).info(
  1730. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1731. )
  1732. # Include target temps for heating phase detection
  1733. bed_target = round(temps.get("bed_target", 0))
  1734. nozzle_target = round(temps.get("nozzle_target", 0))
  1735. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1736. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1737. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1738. #
  1739. # dry_countdown_stalled rides along because it is the one drying signal the
  1740. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1741. # dry_time stopped moving, so on the frame that flips it every other member
  1742. # of this key is identical and the push would be deduplicated away. Mid-print
  1743. # a temperature would eventually break the tie, but a parked command on an
  1744. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1745. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1746. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1747. ams_dry_key = (
  1748. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1749. if state.raw_data
  1750. else ()
  1751. )
  1752. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1753. #
  1754. # The filament identity fields are here because Configure Slot writes
  1755. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1756. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1757. # matched, this function returned before broadcasting, and the card kept
  1758. # showing the old filament until the 30s fallback poll or a page reload —
  1759. # even though the configure route asks the printer for a fresh pushall and
  1760. # that push does carry the new values. Reset always worked, because it
  1761. # clears tray_type.
  1762. #
  1763. # These fields only change when someone configures a slot or swaps a spool,
  1764. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1765. ams_tray_key = (
  1766. tuple(
  1767. (
  1768. t.get("id"),
  1769. t.get("tray_type", ""),
  1770. t.get("state"),
  1771. t.get("tray_color", ""),
  1772. t.get("tray_info_idx", ""),
  1773. t.get("tray_sub_brands", ""),
  1774. t.get("cali_idx"),
  1775. )
  1776. for a in (state.raw_data.get("ams") or [])
  1777. for t in a.get("tray", [])
  1778. )
  1779. if state.raw_data
  1780. else ()
  1781. )
  1782. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1783. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1784. # in the AMS change-hash (tray fields only, and widening that would fire
  1785. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1786. # screen changed no key at all and the card's inlet badges sat stale until a
  1787. # reload. Like the filament-backup flag, these only move when someone
  1788. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1789. fts_key = (
  1790. state.fila_switch.installed if state.fila_switch else False,
  1791. tuple(sorted(state.ams_switch_inlet.items())),
  1792. # Which hotend holds which slot. Unlike the two above this does move
  1793. # mid-print, on every filament change — but only between discrete slots,
  1794. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1795. # it live: it decides which hotend the Load dialog may offer and whether
  1796. # Unload has anything to act on.
  1797. tuple(
  1798. sorted(
  1799. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1800. # Sort on the extruder id alone: the other members are nullable
  1801. # and comparing None with an int raises.
  1802. key=lambda entry: entry[0],
  1803. )
  1804. ),
  1805. )
  1806. status_key = (
  1807. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1808. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1809. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1810. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1811. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1812. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1813. )
  1814. # Fields that change only when the machine does (a nozzle swap, a firmware
  1815. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1816. # but on an idle printer nothing else moves the key when they change.
  1817. machine_key = (
  1818. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1819. state.firmware_version,
  1820. state.developer_mode,
  1821. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1822. # Cooling/heating, switched on the printer's screen too: on an idle
  1823. # printer nothing else moves the key (PSF-4).
  1824. state.airduct_mode,
  1825. )
  1826. status_key = f"{status_key}:{machine_key}"
  1827. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1828. if not is_active_print:
  1829. _unauthorized_print_kill_sent.discard(printer_id)
  1830. elif printer_id in _unauthorized_print_kill_sent:
  1831. # stop_print() was already sent for this print; avoid all further
  1832. # ownership and settings work until the printer leaves an active state.
  1833. pass
  1834. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1835. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1836. _unauthorized_print_kill_sent.discard(printer_id)
  1837. else:
  1838. kill_switch_enabled = False
  1839. authorization: bool | None = None
  1840. status_logger = logging.getLogger(__name__)
  1841. try:
  1842. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1843. if kill_switch_enabled:
  1844. async with async_session() as db:
  1845. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1846. except Exception as e:
  1847. # Fail safe: a database/reconciliation error must never turn into an
  1848. # irreversible stop of a print whose ownership is still unknown.
  1849. authorization = None
  1850. status_logger.warning(
  1851. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1852. )
  1853. if not kill_switch_enabled or authorization is True:
  1854. _unauthorized_print_kill_sent.discard(printer_id)
  1855. elif authorization is None:
  1856. _unauthorized_print_kill_sent.discard(printer_id)
  1857. status_logger.debug(
  1858. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1859. printer_id,
  1860. )
  1861. else:
  1862. try:
  1863. stopped = printer_manager.stop_print(printer_id)
  1864. if stopped:
  1865. _unauthorized_print_kill_sent.add(printer_id)
  1866. _kill_switch_stopped.add(printer_id)
  1867. printer_info = printer_manager.get_printer(printer_id)
  1868. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1869. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1870. notification_data = {
  1871. "status": "stopped",
  1872. "filename": state.gcode_file or state.current_print or "",
  1873. "subtask_name": state.subtask_name or "",
  1874. "progress": state.progress,
  1875. "reason": "unauthorized_print",
  1876. }
  1877. status_logger.warning(
  1878. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1879. printer_id,
  1880. state.state,
  1881. )
  1882. try:
  1883. await ws_manager.broadcast(
  1884. {
  1885. "type": "kill_switch_triggered",
  1886. "printer_id": printer_id,
  1887. "printer_name": printer_name,
  1888. "filename": filename,
  1889. "reason": "unauthorized_print",
  1890. }
  1891. )
  1892. except Exception as e:
  1893. status_logger.warning(
  1894. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1895. )
  1896. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1897. if previous_task is not None and not previous_task.done():
  1898. previous_task.cancel()
  1899. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1900. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1901. name=f"kill-switch-notification-{printer_id}",
  1902. )
  1903. else:
  1904. status_logger.warning(
  1905. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1906. printer_id,
  1907. state.state,
  1908. )
  1909. except Exception as e:
  1910. status_logger.warning(
  1911. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1912. )
  1913. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1914. try:
  1915. printer_info = printer_manager.get_printer(printer_id)
  1916. if printer_info:
  1917. await mqtt_relay.on_printer_status(
  1918. printer_id,
  1919. state,
  1920. printer_info.name,
  1921. printer_info.serial_number,
  1922. printer_manager.is_awaiting_plate_clear(printer_id),
  1923. )
  1924. except Exception:
  1925. pass # Don't fail status callback if MQTT fails
  1926. if _last_status_broadcast.get(printer_id) == status_key:
  1927. return # No change, skip WebSocket broadcast
  1928. _last_status_broadcast[printer_id] = status_key
  1929. # Check for progress milestone notifications (25%, 50%, 75%)
  1930. progress = state.progress or 0
  1931. is_printing = state.state in ("RUNNING", "PRINTING")
  1932. if is_printing and progress > 0:
  1933. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1934. if current_milestone is not None:
  1935. try:
  1936. from backend.app.models.printer import Printer
  1937. # Read the printer in a short session and release the connection
  1938. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1939. # pinned a pooled connection per milestone, per printer (issue #2572).
  1940. async with async_session() as db:
  1941. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1942. printer = result.scalar_one_or_none()
  1943. printer_name = printer.name if printer else f"Printer {printer_id}"
  1944. filename = state.subtask_name or state.gcode_file or "Unknown"
  1945. # remaining_time is in minutes, convert to seconds for notification
  1946. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1947. # Capture camera snapshot for notification image attachment (no DB held).
  1948. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1949. # Notification send needs a session (provider/template lookups).
  1950. async with async_session() as db:
  1951. await notification_service.on_print_progress(
  1952. printer_id,
  1953. printer_name,
  1954. filename,
  1955. current_milestone,
  1956. db,
  1957. remaining_time_seconds,
  1958. image_data=image_data,
  1959. )
  1960. except Exception as e:
  1961. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1962. elif progress < 5:
  1963. # Reset milestone tracking when print restarts or new print begins
  1964. _last_progress_milestone[printer_id] = 0
  1965. _first_layer_notified[printer_id] = False
  1966. # HMS error codes that should not trigger notifications even though they
  1967. # have known descriptions (e.g. user-initiated actions, not real errors).
  1968. _HMS_NOTIFICATION_SUPPRESS = {
  1969. "0500_400E", # Printing was cancelled (user action, not an error)
  1970. }
  1971. # Check for new HMS errors and send notifications
  1972. current_hms_errors = getattr(state, "hms_errors", []) or []
  1973. if current_hms_errors:
  1974. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1975. if new_errors:
  1976. try:
  1977. from backend.app.models.printer import Printer
  1978. # Read the printer in a short session and release the connection
  1979. # BEFORE the ~15s camera snapshot below (issue #2572).
  1980. async with async_session() as db:
  1981. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1982. printer = result.scalar_one_or_none()
  1983. printer_name = printer.name if printer else f"Printer {printer_id}"
  1984. # Format error details for notification
  1985. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1986. module_names = {
  1987. 0x03: "Print/Task",
  1988. 0x05: "Nozzle/Extruder",
  1989. 0x07: "AMS/Filament",
  1990. 0x0C: "Motion Controller",
  1991. 0x12: "Chamber",
  1992. }
  1993. # Capture camera snapshot once for all error notifications (no DB held).
  1994. error_image_data = await _capture_snapshot_for_notification(
  1995. printer_id, printer, logging.getLogger(__name__)
  1996. )
  1997. # Notification sends need a session (provider/template lookups).
  1998. async with async_session() as db:
  1999. sent_count = 0
  2000. for error in new_errors:
  2001. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2002. # Build short code like "0700_8010"
  2003. # Mask to 16 bits to handle printers that send larger values
  2004. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2005. error_code_masked = error_code_int & 0xFFFF
  2006. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2007. # Only notify for errors Bambu publishes text for — printers
  2008. # send undocumented codes that aren't real errors, and Bambu
  2009. # lists some with empty text. Resolved at parse time (#2926);
  2010. # short_code is still needed for the suppression set below.
  2011. description = error.description
  2012. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2013. continue
  2014. error_type = f"{module_name} Error"
  2015. error_detail = description
  2016. await notification_service.on_printer_error(
  2017. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2018. )
  2019. sent_count += 1
  2020. if sent_count:
  2021. logging.getLogger(__name__).info(
  2022. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2023. )
  2024. # Also publish to MQTT relay (no DB): every new fault that
  2025. # counts, with or without text, the same set the UI counts.
  2026. printer_info = printer_manager.get_printer(printer_id)
  2027. if printer_info:
  2028. errors_data = [
  2029. {
  2030. "code": e.code,
  2031. "attr": e.attr,
  2032. "module": e.module,
  2033. "severity": e.severity,
  2034. }
  2035. for e in new_errors
  2036. ]
  2037. await mqtt_relay.on_printer_error(
  2038. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2039. )
  2040. except Exception as e:
  2041. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2042. else:
  2043. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2044. # across a print state change) are forgotten. Some codes, e.g. chamber
  2045. # temperature regulation during PETG prints, toggle every few seconds.
  2046. _take_new_hms_faults(printer_id, [], state.state)
  2047. await ws_manager.send_printer_status(
  2048. printer_id,
  2049. printer_state_to_dict(
  2050. state,
  2051. printer_id,
  2052. printer_manager.get_model(printer_id),
  2053. printer_manager.get_drying_targets(printer_id),
  2054. ),
  2055. )
  2056. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2057. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2058. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2059. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2060. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2061. K-profiles are per-nozzle and the printer's calibration table is numbered
  2062. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2063. switch's other inlet therefore silently invalidates every configured slot in
  2064. it: the index stays put and now resolves against the other nozzle's table.
  2065. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2066. and 0.020 on the right kept the left profile after the move, and a manual
  2067. RFID re-read only re-asserted the same wrong one.
  2068. Configuring a slot is a deliberate preparation step, so this re-selects
  2069. rather than re-configures: only the calibration binding moves, and only for
  2070. slots whose spool already has a stored profile for the new nozzle. A slot
  2071. Bambuddy knows nothing about is left exactly as the operator left it.
  2072. """
  2073. logger = logging.getLogger(__name__)
  2074. target_extruder = extruder_for_inlet(inlet)
  2075. if target_extruder is None:
  2076. return
  2077. client = printer_manager.get_client(printer_id)
  2078. state = printer_manager.get_status(printer_id)
  2079. if not client or not state or not state.raw_data:
  2080. return
  2081. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2082. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2083. # the nozzle width, which changes both the K profile to select and the
  2084. # preset the slot should carry.
  2085. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2086. ams_raw = state.raw_data.get("ams")
  2087. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2088. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2089. if not unit:
  2090. return
  2091. try:
  2092. async with async_session() as db:
  2093. for tray in unit.get("tray", []):
  2094. tray_id = int(tray.get("id", -1))
  2095. if tray_id < 0 or not tray.get("tray_type"):
  2096. continue
  2097. current_idx = tray.get("cali_idx")
  2098. profile = await find_slot_kprofile_for_extruder(
  2099. db,
  2100. printer_id,
  2101. ams_id,
  2102. tray_id,
  2103. target_extruder,
  2104. nozzle_diameter,
  2105. printer_manager.get_model(printer_id),
  2106. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2107. )
  2108. if profile is None or profile.cali_idx is None:
  2109. continue
  2110. if current_idx == profile.cali_idx:
  2111. continue # Already on the right one.
  2112. logger.info(
  2113. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2114. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2115. printer_id,
  2116. ams_id,
  2117. tray_id,
  2118. inlet,
  2119. target_extruder,
  2120. profile.name,
  2121. current_idx,
  2122. profile.cali_idx,
  2123. profile.k_value,
  2124. )
  2125. client.extrusion_cali_sel(
  2126. ams_id=ams_id,
  2127. tray_id=tray_id,
  2128. cali_idx=profile.cali_idx,
  2129. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2130. nozzle_diameter=nozzle_diameter,
  2131. )
  2132. except Exception as e:
  2133. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2134. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2135. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2136. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2137. from the delayed re-check -- which is why it takes the AMS data and print
  2138. state as arguments instead of reading them from the push (#3186).
  2139. """
  2140. logger = logging.getLogger(__name__)
  2141. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2142. # Auto-unlink spool assignments with stale fingerprints. Under the
  2143. # per-printer assignment lock since #3186: the held-removal re-check runs
  2144. # this outside any MQTT push, so it can now overlap one.
  2145. try:
  2146. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2147. from sqlalchemy.orm import selectinload
  2148. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2149. from backend.app.models.spool import Spool as _Spool
  2150. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2151. from backend.app.services.ams_slot_presence import spool_present
  2152. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2153. # Built-in assignments only. Since #2812 they survive a switch to
  2154. # Spoolman mode rather than being deleted by it, and this pass ends
  2155. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2156. # time as the AMS contents changed under the other mode, undoing the
  2157. # preservation more slowly but just as completely.
  2158. assignments = []
  2159. if not await spoolman_owns_assignments(db):
  2160. result = await db.execute(
  2161. select(SA)
  2162. .where(SA.printer_id == printer_id)
  2163. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2164. )
  2165. assignments = result.scalars().all()
  2166. # ``printing_now`` (top of this function) keeps a runout from
  2167. # unlinking the spool that fed the print — the next idle-time pass
  2168. # unlinks it if the user really did take it out.
  2169. stale = []
  2170. # Removals this pass is holding rather than unlinking (#3186).
  2171. held: set[tuple] = set()
  2172. for assignment in assignments:
  2173. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2174. if assignment.ams_id == 255:
  2175. ps = printer_manager.get_status(printer_id)
  2176. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2177. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2178. current_tray = None
  2179. for vt in vt_tray_raw:
  2180. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2181. current_tray = vt
  2182. break
  2183. if not current_tray:
  2184. # vt_tray data may not have arrived yet — keep assignment
  2185. continue
  2186. else:
  2187. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2188. if not current_tray:
  2189. if printing_now:
  2190. logger.info(
  2191. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2192. assignment.spool_id,
  2193. assignment.ams_id,
  2194. assignment.tray_id,
  2195. )
  2196. continue
  2197. # A whole AMS unit can drop out of one push and come back in
  2198. # the next; only a slot that stays gone is a removal (#3186).
  2199. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2200. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2201. held.add(hold_key)
  2202. logger.info(
  2203. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2204. "unlinking if it is still gone in %ds",
  2205. assignment.spool_id,
  2206. assignment.ams_id,
  2207. assignment.tray_id,
  2208. int(slot_unlink_grace.GRACE_SECONDS),
  2209. )
  2210. continue
  2211. logger.info(
  2212. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2213. assignment.spool_id,
  2214. assignment.ams_id,
  2215. assignment.tray_id,
  2216. )
  2217. stale.append(assignment) # Slot empty
  2218. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2219. # A Bambu Lab spool is in this slot — check if it's the same spool
  2220. # that's currently assigned. If yes, keep the assignment (avoids
  2221. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2222. # the printer's filament preset on every startup).
  2223. tray_uuid = current_tray.get("tray_uuid", "")
  2224. tag_uid = current_tray.get("tag_uid", "")
  2225. spool = assignment.spool
  2226. spool_matches = False
  2227. if spool:
  2228. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2229. spool.tag_uid
  2230. and tag_uid
  2231. and tag_uid != "0000000000000000"
  2232. and spool.tag_uid.upper() == tag_uid.upper()
  2233. ):
  2234. spool_matches = True
  2235. if spool_matches:
  2236. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2237. cur_color = current_tray.get("tray_color", "")
  2238. cur_type = current_tray.get("tray_type", "")
  2239. fp_color = assignment.fingerprint_color or ""
  2240. fp_type = assignment.fingerprint_type or ""
  2241. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2242. assignment.fingerprint_color = cur_color
  2243. assignment.fingerprint_type = cur_type
  2244. logger.debug(
  2245. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2246. assignment.spool_id,
  2247. assignment.ams_id,
  2248. assignment.tray_id,
  2249. )
  2250. continue
  2251. # Different BL spool or unrecognized — unlink so auto-assign can match
  2252. logger.info(
  2253. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2254. assignment.spool_id,
  2255. assignment.ams_id,
  2256. assignment.tray_id,
  2257. tray_uuid,
  2258. )
  2259. stale.append(assignment)
  2260. else:
  2261. cur_color = current_tray.get("tray_color", "")
  2262. cur_type = current_tray.get("tray_type", "")
  2263. cur_state = current_tray.get("state")
  2264. fp_color = assignment.fingerprint_color or ""
  2265. fp_type = assignment.fingerprint_type or ""
  2266. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2267. # the slot was empty when the user pre-assigned via SpoolBuddy
  2268. # (the firmware drops ams_filament_setting on empty slots, so
  2269. # MQTT was deferred). The moment any filament gets inserted
  2270. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2271. # reconfigured spool — fire the deferred configuration.
  2272. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2273. # extruder" code) OR, on firmwares that don't use the state
  2274. # enum meaningfully, a non-empty tray_type when state is
  2275. # NOT one of the firmware's explicit empty signals (9, 10).
  2276. # state-only was wrong for firmwares that never set 11 — A1
  2277. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2278. # always report state=3 — so the replay never fired for them
  2279. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2280. # explicit "empty" signals authoritative over any stale
  2281. # tray_type that might survive the relay's auto-clearing.
  2282. #
  2283. # tray_exist_bits comes first because that guard cannot tell
  2284. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2285. # writes state=9 when the bit is 0 and leaves it there when the
  2286. # bit returns. A non-RFID spool inserted into a pre-assigned
  2287. # slot brings no tray_type with it, so the stale 9 made this
  2288. # expression false forever and the deferred config never fired
  2289. # — the deadlock #1322 removed from the assign path, still in
  2290. # place here (#3084, #3100).
  2291. loaded = spool_present(current_tray) is True or (
  2292. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2293. )
  2294. if not fp_type.strip() and loaded and assignment.spool:
  2295. # The fingerprint ends this replay. Not recorded when nothing
  2296. # could be sent (no MQTT client while the printer reconnects),
  2297. # so the next AMS change tries again. An attempt that raised is
  2298. # recorded as before: it may have sent part of the commands and
  2299. # would raise again on every change, remain% steps included.
  2300. configured: bool | None = False
  2301. try:
  2302. from backend.app.api.routes.inventory import (
  2303. apply_spool_to_slot_via_mqtt,
  2304. )
  2305. configured = await apply_spool_to_slot_via_mqtt(
  2306. db=db,
  2307. current_user=None,
  2308. spool=assignment.spool,
  2309. printer_id=printer_id,
  2310. ams_id=assignment.ams_id,
  2311. tray_id=assignment.tray_id,
  2312. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2313. current_tray_type=cur_type,
  2314. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2315. )
  2316. except Exception:
  2317. logger.exception(
  2318. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2319. assignment.spool_id,
  2320. printer_id,
  2321. assignment.ams_id,
  2322. assignment.tray_id,
  2323. )
  2324. configured = None
  2325. if configured is False:
  2326. logger.warning(
  2327. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2328. "retrying on the next AMS change",
  2329. assignment.spool_id,
  2330. printer_id,
  2331. assignment.ams_id,
  2332. assignment.tray_id,
  2333. )
  2334. else:
  2335. if configured:
  2336. logger.info(
  2337. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2338. assignment.spool_id,
  2339. printer_id,
  2340. assignment.ams_id,
  2341. assignment.tray_id,
  2342. )
  2343. assignment.fingerprint_color = cur_color
  2344. assignment.fingerprint_type = cur_type
  2345. continue
  2346. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2347. # Blank tray data mid-print is a runout, not a swap: the
  2348. # firmware clears colour and type when it unloads a spool
  2349. # it just emptied. Unlinking here would erase the record
  2350. # of which spool fed the print so far.
  2351. if printing_now and not cur_color.strip() and not cur_type.strip():
  2352. logger.info(
  2353. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2354. "(runout?)",
  2355. assignment.spool_id,
  2356. assignment.ams_id,
  2357. assignment.tray_id,
  2358. )
  2359. continue
  2360. # Same reasoning off the print, on firmware's own say-so:
  2361. # a blank tray report from a slot whose tray_exist_bits
  2362. # bit is set describes a spool the AMS cannot identify —
  2363. # a non-RFID one, or one whose slot was reset — not a
  2364. # spool that was taken out. Deleting the assignment there
  2365. # threw away the identity the user had supplied, which is
  2366. # the only place it existed (#3100). A slot the bit calls
  2367. # empty, or one that carries no bit at all, still unlinks.
  2368. #
  2369. # Unless the slot was reported empty first: a removal
  2370. # already held means a spool came out and another went
  2371. # in, so the blank report keeps the hold running below
  2372. # rather than cancelling it (#3186).
  2373. if (
  2374. spool_present(current_tray) is True
  2375. and not cur_color.strip()
  2376. and not cur_type.strip()
  2377. and not slot_unlink_grace.is_held(
  2378. printer_id,
  2379. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2380. )
  2381. ):
  2382. logger.info(
  2383. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2384. "tray reports no filament data yet",
  2385. assignment.spool_id,
  2386. assignment.ams_id,
  2387. assignment.tray_id,
  2388. )
  2389. continue
  2390. # A blank report the presence bit does not vouch for is
  2391. # still only one push. An idle X1C cleared a whole AMS
  2392. # unit's bits, colour and type for a moment and lost
  2393. # four saved assignments that way (#3186); unlink only
  2394. # if the slot is still blank after the grace period.
  2395. if not cur_color.strip() and not cur_type.strip():
  2396. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2397. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2398. held.add(hold_key)
  2399. logger.info(
  2400. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2401. "unlinking if it is still blank in %ds",
  2402. assignment.spool_id,
  2403. assignment.ams_id,
  2404. assignment.tray_id,
  2405. int(slot_unlink_grace.GRACE_SECONDS),
  2406. )
  2407. continue
  2408. # Fingerprint mismatch — but check if tray now matches the
  2409. # assigned spool (e.g. auto-configure changed the tray).
  2410. # Both sides are reduced to the type the slot can carry
  2411. # before comparing: the assign path writes that rather
  2412. # than the spool's raw material (#2902), so a spool whose
  2413. # material is a product line — "PLA+", "HTPLA" — reports
  2414. # back as "PLA" and would otherwise fail this check and
  2415. # be auto-unlinked from the slot it was just assigned to.
  2416. # Reducing the printer's side too keeps slots configured
  2417. # by an older Bambuddy, still reporting "PLA+", matching.
  2418. spool = assignment.spool
  2419. if spool:
  2420. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2421. # Two ways the assign path can have arrived at the
  2422. # slot's type, so both count as "we wrote this".
  2423. # The material column is one; the spool's preset is
  2424. # the other, and it outranks the material when the
  2425. # spool has one -- a spool whose material says PLA
  2426. # and whose preset is "Bambu PLA Aero" puts
  2427. # PLA-AERO in the slot (#2902). Read from the stored
  2428. # preset name rather than resolving the preset,
  2429. # because this runs on every AMS push and a cloud
  2430. # lookup here would be both slow and unavailable on
  2431. # the unauthenticated replay path.
  2432. spool_types = {printer_filament_type(spool.material).upper()}
  2433. if spool.slicer_filament_name:
  2434. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2435. # An imported local preset stores its type outright,
  2436. # which is what the assign path used -- and the name
  2437. # above may be unset. One keyed read, and only on a
  2438. # mismatch, which is rare.
  2439. #
  2440. # slicer_filament is free text up to fifty characters,
  2441. # so the digits have to be checked against the range
  2442. # of the integer primary key they are about to be
  2443. # compared with. Postgres raises on an out-of-range
  2444. # integer rather than simply not matching, and that
  2445. # would poison this session and abandon the rest of
  2446. # the cleanup pass.
  2447. lp_ref = (spool.slicer_filament or "").strip()
  2448. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2449. from backend.app.models.local_preset import LocalPreset as _LP
  2450. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2451. if lp_type:
  2452. spool_types.add(printer_filament_type(lp_type).upper())
  2453. if (
  2454. _colors_similar(cur_color, spool_color)
  2455. and printer_filament_type(cur_type).upper() in spool_types
  2456. ):
  2457. logger.info(
  2458. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2459. assignment.spool_id,
  2460. assignment.ams_id,
  2461. assignment.tray_id,
  2462. )
  2463. assignment.fingerprint_color = cur_color
  2464. assignment.fingerprint_type = cur_type
  2465. continue
  2466. logger.info(
  2467. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2468. assignment.spool_id,
  2469. assignment.ams_id,
  2470. assignment.tray_id,
  2471. cur_color,
  2472. cur_type,
  2473. fp_color,
  2474. fp_type,
  2475. spool.rgba if spool else "?",
  2476. spool.material if spool else "?",
  2477. )
  2478. stale.append(assignment) # Spool changed
  2479. slot_unlink_grace.settle(printer_id, "inventory", held)
  2480. # Snapshot slots before delete — ORM attribute access after the
  2481. # commit would refresh against a deleted row.
  2482. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2483. for a in stale:
  2484. await db.delete(a)
  2485. if stale:
  2486. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2487. # Commit any changes (stale deletions and/or fingerprint updates)
  2488. await db.commit()
  2489. # Tell open browsers the assignment is gone (#2575). Only the manual
  2490. # REST assign/unassign endpoints broadcast this event; without it the
  2491. # frontend's spool-assignments cache keeps rendering the unlinked
  2492. # spool on the slot until an unrelated refetch — which reads exactly
  2493. # like "the fix didn't work" (reporter verified: a browser refresh
  2494. # after the swap showed the correct state all along).
  2495. for ams_id, tray_id in unlinked_slots:
  2496. await ws_manager.broadcast(
  2497. {
  2498. "type": "spool_assignment_changed",
  2499. "printer_id": printer_id,
  2500. "ams_id": ams_id,
  2501. "tray_id": tray_id,
  2502. }
  2503. )
  2504. except Exception as e:
  2505. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2506. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2507. """Delete Spoolman slot rows whose held removal has run its grace period.
  2508. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2509. talks to Spoolman for every tray; this only needs the local rows, so it
  2510. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2511. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2512. not in a slot the presence bit calls occupied -- and nothing else.
  2513. """
  2514. logger = logging.getLogger(__name__)
  2515. try:
  2516. async with async_session() as db:
  2517. from backend.app.api.routes.settings import get_setting
  2518. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2519. from backend.app.services.ams_slot_presence import spool_present
  2520. enabled = await get_setting(db, "spoolman_enabled")
  2521. if not enabled or enabled.lower() != "true":
  2522. return
  2523. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2524. if sync_mode and sync_mode != "auto":
  2525. return
  2526. trays: dict[tuple[int, int], dict] = {}
  2527. for ams_unit in ams_data or []:
  2528. if not isinstance(ams_unit, dict):
  2529. continue
  2530. for tray in ams_unit.get("tray", []):
  2531. if isinstance(tray, dict):
  2532. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2533. rows = (
  2534. (
  2535. await db.execute(
  2536. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2537. )
  2538. )
  2539. .scalars()
  2540. .all()
  2541. )
  2542. held: set[tuple] = set()
  2543. expired: list[tuple[int, int]] = []
  2544. for row in rows:
  2545. tray = trays.get((row.ams_id, row.tray_id))
  2546. if tray is None or printing_now:
  2547. continue
  2548. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2549. continue
  2550. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2551. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2552. continue
  2553. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2554. expired.append((row.ams_id, row.tray_id))
  2555. else:
  2556. held.add(hold_key)
  2557. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2558. if not expired:
  2559. return
  2560. # A statement rather than ORM deletes, like the sync pass: the two
  2561. # can overlap, and a row the other already removed must not fail
  2562. # this commit.
  2563. for ams_id, tray_id in expired:
  2564. await db.execute(
  2565. delete(SpoolmanSlotAssignment).where(
  2566. SpoolmanSlotAssignment.printer_id == printer_id,
  2567. SpoolmanSlotAssignment.ams_id == ams_id,
  2568. SpoolmanSlotAssignment.tray_id == tray_id,
  2569. )
  2570. )
  2571. await db.commit()
  2572. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2573. for ams_id, tray_id in expired:
  2574. await ws_manager.broadcast(
  2575. {
  2576. "type": "spool_assignment_changed",
  2577. "printer_id": printer_id,
  2578. "ams_id": ams_id,
  2579. "tray_id": tray_id,
  2580. }
  2581. )
  2582. except Exception as e:
  2583. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2584. async def _recheck_held_unlinks(printer_id: int) -> None:
  2585. """Re-run just the slot cleanup against the printer's current AMS state.
  2586. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2587. passes otherwise run only when the AMS hash changes, and a slot that went
  2588. empty and stayed empty may never change it again.
  2589. """
  2590. status = printer_manager.get_status(printer_id)
  2591. # A disconnected printer's state is its last report, not a new one: acting
  2592. # on it would "confirm" a removal nobody has seen for the whole grace
  2593. # period. Leave the holds; the first push after reconnecting decides.
  2594. if status is None or not status.connected:
  2595. return
  2596. ams_raw = status.raw_data.get("ams")
  2597. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2598. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2599. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2600. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2601. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2602. async def on_ams_change(printer_id: int, ams_data: list):
  2603. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2604. logger = logging.getLogger(__name__)
  2605. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2606. # still being charged, skip weight sync later. on_print_complete may pop
  2607. # _active_sessions during our awaits (#880).
  2608. from backend.app.services.usage_tracker import printer_is_charging
  2609. _print_active = printer_is_charging(printer_id)
  2610. # A slot that reports empty while a print is running is a filament runout,
  2611. # not a spool swap: the spool is still physically in the AMS, just
  2612. # consumed. Dropping either inventory backend's slot link there loses the
  2613. # only record of which spool fed the print, so the completion path can't
  2614. # charge the runout segment to anything. Both cleanup passes below consult
  2615. # this; computed once, up front, so neither depends on the other having run.
  2616. _unlink_state = printer_manager.get_status(printer_id)
  2617. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2618. # The session alone is not enough: a restart that finds a stale persisted
  2619. # session registers none for the print that is running.
  2620. _print_active = _print_active or printing_now
  2621. # MQTT relay - publish AMS change
  2622. try:
  2623. printer_info = printer_manager.get_printer(printer_id)
  2624. if printer_info:
  2625. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2626. except Exception:
  2627. pass # Don't fail AMS callback if MQTT fails
  2628. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2629. # This ensures frontend gets immediate updates when AMS slots are configured
  2630. try:
  2631. state = printer_manager.get_status(printer_id)
  2632. if state:
  2633. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2634. await ws_manager.send_printer_status(
  2635. printer_id,
  2636. printer_state_to_dict(
  2637. state,
  2638. printer_id,
  2639. printer_manager.get_model(printer_id),
  2640. printer_manager.get_drying_targets(printer_id),
  2641. ),
  2642. )
  2643. except Exception as e:
  2644. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2645. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2646. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2647. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2648. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2649. # "no existing assignment" for the same (printer, ams, tray) and race to
  2650. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2651. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2652. # bug stayed latent there. See services/ams_assignment_lock for details.
  2653. try:
  2654. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2655. from sqlalchemy.orm import selectinload
  2656. from backend.app.api.routes.settings import get_setting
  2657. from backend.app.models.spool import Spool
  2658. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2659. from backend.app.services.spool_tag_matcher import (
  2660. auto_assign_spool,
  2661. create_spool_from_tray,
  2662. find_matching_untagged_spool,
  2663. get_spool_by_tag,
  2664. is_bambu_tag,
  2665. is_valid_tag,
  2666. link_tag_to_inventory_spool,
  2667. tag_belongs_to_archived_spool,
  2668. )
  2669. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2670. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2671. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2672. if not _spoolman_on or _spoolman_on.lower() != "true":
  2673. for ams_unit in ams_data:
  2674. if not isinstance(ams_unit, dict):
  2675. continue
  2676. ams_id = int(ams_unit.get("id", 0))
  2677. for tray in ams_unit.get("tray", []):
  2678. if not isinstance(tray, dict):
  2679. continue
  2680. tray_id = int(tray.get("id", 0))
  2681. tag_uid = tray.get("tag_uid", "")
  2682. tray_uuid = tray.get("tray_uuid", "")
  2683. tray_info_idx = tray.get("tray_info_idx", "")
  2684. if not tray.get("tray_type"):
  2685. # Slot reported empty — drop any cached unknown-tag
  2686. # broadcast so reinserting the same spool re-prompts.
  2687. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2688. continue # Empty slot
  2689. # Check if assignment already exists for this slot
  2690. existing = await db.execute(
  2691. select(SA)
  2692. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2693. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2694. )
  2695. existing_assignment = existing.scalar_one_or_none()
  2696. if existing_assignment:
  2697. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2698. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2699. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2700. # Skip during active prints: the usage tracker handles deduction
  2701. # precisely via 3MF data on print completion. Without this guard the
  2702. # AMS remain% SET and the usage tracker ADD both fire from the same
  2703. # MQTT message, doubling the deduction (#880).
  2704. if _print_active:
  2705. continue
  2706. remain_raw = tray.get("remain")
  2707. if (
  2708. remain_raw is not None
  2709. and existing_assignment.spool
  2710. and not existing_assignment.spool.weight_locked
  2711. ):
  2712. try:
  2713. remain_val = int(remain_raw)
  2714. except (TypeError, ValueError):
  2715. remain_val = -1
  2716. if 1 <= remain_val <= 100:
  2717. lw = existing_assignment.spool.label_weight or 1000
  2718. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2719. current_used = existing_assignment.spool.weight_used or 0
  2720. if new_used > current_used + 1:
  2721. # Rechecked in the statement: the spool was loaded
  2722. # before this, and a weight set by hand (or weighed)
  2723. # and locked since then must stay (WL-6).
  2724. result = cast(
  2725. CursorResult,
  2726. await db.execute(
  2727. update(Spool)
  2728. .where(
  2729. Spool.id == existing_assignment.spool_id,
  2730. Spool.weight_locked.is_not(True),
  2731. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2732. )
  2733. .values(weight_used=new_used)
  2734. ),
  2735. )
  2736. await db.commit()
  2737. if result.rowcount:
  2738. logger.info(
  2739. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2740. existing_assignment.spool_id,
  2741. current_used,
  2742. new_used,
  2743. remain_val,
  2744. )
  2745. await ws_manager.broadcast({"type": "inventory_changed"})
  2746. # A K-profile the slot lost (the default K after a reset or
  2747. # power cycle) is put back by kprofile_drift on the next idle
  2748. # push; a different real profile was picked on purpose and
  2749. # stays (#3219, item 44).
  2750. continue
  2751. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2752. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2753. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2754. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2755. # An archived spool still in the AMS: the slot
  2756. # stays free rather than adopting its tag.
  2757. continue
  2758. if not spool:
  2759. # Try matching an untagged inventory spool (same material/color)
  2760. spool = await find_matching_untagged_spool(db, tray)
  2761. if spool:
  2762. await link_tag_to_inventory_spool(db, spool, tray)
  2763. elif _auto_add_unknown:
  2764. spool = await create_spool_from_tray(db, tray)
  2765. else:
  2766. # Auto-add disabled: surface the slot so the
  2767. # user can add it manually via the UI.
  2768. await _broadcast_unknown_tag(
  2769. printer_id=printer_id,
  2770. ams_id=ams_id,
  2771. tray_id=tray_id,
  2772. tag_uid=tag_uid,
  2773. tray_uuid=tray_uuid,
  2774. tray_type=tray.get("tray_type"),
  2775. tray_color=tray.get("tray_color"),
  2776. tray_sub_brands=tray.get("tray_sub_brands"),
  2777. tray_count=len(ams_unit.get("tray", [])),
  2778. )
  2779. continue
  2780. # Slot matched (existing tag, untagged inventory
  2781. # match, or freshly auto-created spool) — drop any
  2782. # stale dedup so a future tag swap re-prompts.
  2783. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2784. await auto_assign_spool(
  2785. printer_id,
  2786. ams_id,
  2787. tray_id,
  2788. spool,
  2789. printer_manager,
  2790. db,
  2791. tray_info_idx=tray_info_idx,
  2792. )
  2793. await db.commit()
  2794. await ws_manager.broadcast(
  2795. {
  2796. "type": "spool_auto_assigned",
  2797. "printer_id": printer_id,
  2798. "ams_id": ams_id,
  2799. "tray_id": tray_id,
  2800. "spool_id": spool.id,
  2801. }
  2802. )
  2803. logger.info(
  2804. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2805. spool.id,
  2806. printer_id,
  2807. ams_id,
  2808. tray_id,
  2809. )
  2810. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2811. db, tag_uid, tray_uuid
  2812. ):
  2813. # Non-BL spool with some tag — let user choose (not
  2814. # an archived one's, whose slot stays free)
  2815. await _broadcast_unknown_tag(
  2816. printer_id=printer_id,
  2817. ams_id=ams_id,
  2818. tray_id=tray_id,
  2819. tag_uid=tag_uid,
  2820. tray_uuid=tray_uuid,
  2821. tray_type=tray.get("tray_type"),
  2822. tray_color=tray.get("tray_color"),
  2823. tray_sub_brands=tray.get("tray_sub_brands"),
  2824. tray_count=len(ams_unit.get("tray", [])),
  2825. )
  2826. # No-tag slots (generic non-RFID filament) are left alone:
  2827. # nothing to identify, prompting "+ Add" would just create
  2828. # ghost spools with empty tags on every confirm.
  2829. except Exception as e:
  2830. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2831. try:
  2832. async with async_session() as db:
  2833. from backend.app.api.routes.settings import get_setting
  2834. from backend.app.models.printer import Printer
  2835. # Check if Spoolman is enabled
  2836. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2837. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2838. return
  2839. # Check sync mode
  2840. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2841. if sync_mode and sync_mode != "auto":
  2842. return # Only sync on auto mode
  2843. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2844. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2845. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2846. # always owned by per-print tracking, never by AMS auto-sync. The
  2847. # setting is still read by the settings UI for backwards compat but
  2848. # has no effect on the sync path here.
  2849. # Get Spoolman URL
  2850. spoolman_url = await get_setting(db, "spoolman_url")
  2851. if not spoolman_url:
  2852. return
  2853. # Get or create Spoolman client
  2854. client = await get_spoolman_client()
  2855. if not client:
  2856. try:
  2857. client = await init_spoolman_client(spoolman_url)
  2858. except ValueError as exc:
  2859. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2860. return
  2861. # Check if Spoolman is reachable
  2862. if not await client.health_check():
  2863. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2864. return
  2865. # Get printer name for location
  2866. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2867. printer = result.scalar_one_or_none()
  2868. printer_name = printer.name if printer else f"Printer {printer_id}"
  2869. # OPTIMIZATION: Fetch all spools once before processing trays
  2870. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2871. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2872. try:
  2873. cached_spools = await client.get_spools()
  2874. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2875. except Exception as e:
  2876. logger.error(
  2877. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2878. printer_id,
  2879. e,
  2880. )
  2881. return
  2882. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2883. from sqlalchemy.orm import selectinload
  2884. from backend.app.models.spool_assignment import SpoolAssignment
  2885. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2886. from backend.app.services.ams_slot_presence import spool_present
  2887. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2888. # Built-in remaining weight, used by sync_ams_tray only when the
  2889. # firmware reports an unusable remain%/tray_weight for a slot.
  2890. #
  2891. # Left empty since #2812. This block runs in Spoolman mode only,
  2892. # and until then the built-in table was emptied on the switch, so
  2893. # there was never anything here to read and the fallback was inert.
  2894. # Preserving those rows makes it live again, and it is keyed by slot
  2895. # rather than by spool: after a mode switch the tray may well hold
  2896. # different filament, and ``create_spool`` writes ``remaining_weight``
  2897. # unconditionally, so a stale figure would be seeded into a brand new
  2898. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2899. # intent survives for whoever revisits the cross-mode fallback.
  2900. inventory_weights: dict[tuple[int, int], float] = {}
  2901. if not await spoolman_owns_assignments(db):
  2902. try:
  2903. assign_result = await db.execute(
  2904. select(SpoolAssignment)
  2905. .options(selectinload(SpoolAssignment.spool))
  2906. .where(SpoolAssignment.printer_id == printer_id)
  2907. )
  2908. for assignment in assign_result.scalars().all():
  2909. spool = assignment.spool
  2910. if spool and spool.label_weight > 0:
  2911. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2912. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2913. except Exception as e:
  2914. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2915. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2916. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2917. slot_map_read = False
  2918. try:
  2919. slot_result = await db.execute(
  2920. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2921. )
  2922. for slot in slot_result.scalars().all():
  2923. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2924. slot_map_read = True
  2925. except Exception as e:
  2926. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2927. # Sync each AMS tray and collect slot changes for DB persistence
  2928. synced = 0
  2929. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2930. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2931. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2932. for ams_unit in ams_data:
  2933. if not isinstance(ams_unit, dict):
  2934. continue
  2935. ams_id = int(ams_unit.get("id", 0))
  2936. trays = ams_unit.get("tray", [])
  2937. for tray_data in trays:
  2938. if not isinstance(tray_data, dict):
  2939. continue
  2940. tray_id_raw = int(tray_data.get("id", 0))
  2941. tray = client.parse_ams_tray(ams_id, tray_data)
  2942. if not tray:
  2943. # Empty tray slot — record for local assignment cleanup
  2944. # and drop any cached unknown-tag broadcast so a
  2945. # reinserted spool re-prompts.
  2946. #
  2947. # Not during a running print: a slot that empties there
  2948. # is a filament runout, and the spool is still in the
  2949. # AMS. `spoolman_slot_assignments` is how a tag-less
  2950. # spool assigned through the Bambuddy UI is resolved at
  2951. # completion (#1459), so deleting the row mid-print
  2952. # loses the runout segment's usage — the same failure
  2953. # the internal inventory's auto-unlink had.
  2954. #
  2955. # Nor when firmware's presence bit says the slot is
  2956. # occupied. parse_ams_tray calls a tray with no type or
  2957. # no colour empty, and a spool the AMS cannot read has
  2958. # neither until something configures it — so a tag-less
  2959. # spool assigned through the UI had its row deleted by
  2960. # the first idle push after it was inserted. Same
  2961. # deletion as the internal inventory's in #3100, same
  2962. # answer, so the two modes stay in step.
  2963. #
  2964. # And only once the slot has stayed empty for the grace
  2965. # period -- the internal inventory's #3186 answer, for
  2966. # the same one-push blank.
  2967. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2968. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2969. if not printing_now and (
  2970. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2971. ):
  2972. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2973. empty_slots.append((ams_id, tray_id_raw))
  2974. else:
  2975. spoolman_held.add(hold_key)
  2976. logger.info(
  2977. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2978. "unlinking if it is still empty in %ds",
  2979. ams_id,
  2980. tray_id_raw,
  2981. linked_spool,
  2982. int(slot_unlink_grace.GRACE_SECONDS),
  2983. )
  2984. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2985. continue
  2986. spool_tag = (
  2987. tray.tray_uuid
  2988. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2989. else tray.tag_uid
  2990. )
  2991. # Provide the hint only when no RFID is available
  2992. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2993. try:
  2994. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2995. result = await client.sync_ams_tray(
  2996. tray,
  2997. printer_name,
  2998. db,
  2999. # Per-print tracking is the only weight writer (#1119).
  3000. # AMS auto-sync still maintains spool metadata / slot
  3001. # assignments but no longer touches remaining_weight.
  3002. disable_weight_sync=True,
  3003. cached_spools=cached_spools,
  3004. inventory_remaining=inv_remaining,
  3005. spoolman_spool_id_hint=hint,
  3006. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3007. )
  3008. if result is None and spool_tag and not auto_add_unknown_rfid:
  3009. # Spoolman skipped auto-create per user setting — surface
  3010. # the slot so the UI can offer "+ Add to inventory".
  3011. await _broadcast_unknown_tag(
  3012. printer_id=printer_id,
  3013. ams_id=ams_id,
  3014. tray_id=tray.tray_id,
  3015. tag_uid=tray.tag_uid or "",
  3016. tray_uuid=tray.tray_uuid or "",
  3017. tray_type=tray.tray_type,
  3018. tray_color=tray.tray_color,
  3019. tray_sub_brands=tray.tray_sub_brands,
  3020. tray_count=len(trays),
  3021. )
  3022. elif result:
  3023. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3024. if result:
  3025. synced += 1
  3026. if result.get("id"):
  3027. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3028. # If a new spool was created, add it to the cache
  3029. # so subsequent trays can find it if they reference the same tag
  3030. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3031. if not spool_exists:
  3032. cached_spools.append(result)
  3033. logger.debug(
  3034. "[Printer %s] Added newly created spool %s to cache",
  3035. printer_id,
  3036. result["id"],
  3037. )
  3038. # Reconcile slot_preset_mappings (the same row internal
  3039. # mode keeps in sync via inventory + spool_tag_matcher).
  3040. # Without this the slot card surfaces the previous spool's
  3041. # preset name — same bug shape, different inventory mode.
  3042. from backend.app.services.slot_preset_writer import (
  3043. upsert_slot_preset_for_spoolman_spool,
  3044. )
  3045. await upsert_slot_preset_for_spoolman_spool(
  3046. db=db,
  3047. spoolman_spool=result,
  3048. tray_info_idx=tray.tray_info_idx or "",
  3049. tray_sub_brands=tray.tray_sub_brands or "",
  3050. tray_type=tray.tray_type or "",
  3051. printer_id=printer_id,
  3052. ams_id=ams_id,
  3053. tray_id=tray.tray_id,
  3054. )
  3055. except Exception as e:
  3056. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3057. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3058. if synced > 0:
  3059. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3060. # Persist slot assignment changes to the local table: only slots
  3061. # whose spool this pass changed, and only while they still hold what
  3062. # it read before awaiting Spoolman, so a spool assigned by hand in
  3063. # between stays (SSA-3). The changed slots are announced: the slot
  3064. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3065. # tray, so with no event it kept the previous spool's preset name.
  3066. if slot_changes or empty_slots:
  3067. from backend.app.services.spoolman_slot_sync import write_slot_results
  3068. try:
  3069. await write_slot_results(
  3070. db,
  3071. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3072. if slot_map_read
  3073. else None,
  3074. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3075. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3076. )
  3077. except Exception as e:
  3078. await db.rollback()
  3079. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3080. except Exception as e:
  3081. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3082. # Largest finish photo attached to a notification; a bigger one is still linked.
  3083. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3084. async def _finish_photo_for_notification(
  3085. db, archive, archive_id: int, filename: str
  3086. ) -> tuple[str | None, bytes | None]:
  3087. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3088. With authentication off the link is the archive's own photo route, as it
  3089. always was: it opens without a login and doesn't expire. With
  3090. authentication on that route needs a media token, which nothing tapping a
  3091. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3092. link only ever answered 401. The photo is then saved as a notification
  3093. photo as well (utils/notification_photos.py) and the link points there: an
  3094. unguessable name that opens this one photo and nothing else, for 3 days.
  3095. The link is relative when no External URL is set. Bytes over
  3096. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3097. ``(None, None)`` when the photo can't be found.
  3098. """
  3099. from backend.app.api.routes.settings import get_setting
  3100. from backend.app.core.auth import is_auth_enabled
  3101. from backend.app.utils.archive_paths import find_archive_photo
  3102. from backend.app.utils.notification_photos import save_notification_photo
  3103. log = logging.getLogger(__name__)
  3104. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3105. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3106. photo_bytes: bytes | None = None
  3107. try:
  3108. photo_path = find_archive_photo(archive, filename)
  3109. if photo_path is not None:
  3110. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3111. except Exception as e:
  3112. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3113. try:
  3114. auth_on = await is_auth_enabled(db)
  3115. except Exception:
  3116. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3117. if auth_on:
  3118. url = None
  3119. if photo_bytes:
  3120. try:
  3121. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3122. url = f"{base}/api/v1/notifications/photos/{name}"
  3123. except Exception as e:
  3124. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3125. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3126. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3127. return url, None
  3128. if photo_bytes:
  3129. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3130. return url, photo_bytes
  3131. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3132. """Capture a camera snapshot for notification image attachment.
  3133. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3134. Uses: external camera > buffered frame > fresh capture.
  3135. Turns the chamber light on for the picture when the printer asks for it
  3136. (#1655). ``light=False`` is for callers that capture all through a print,
  3137. where the light would flash with every frame.
  3138. """
  3139. if not printer:
  3140. return None
  3141. async with camera_light(printer if light else None):
  3142. return await _capture_snapshot_frame(printer_id, printer, logger)
  3143. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3144. """The capture behind ``_capture_snapshot_for_notification``."""
  3145. try:
  3146. from backend.app.api.routes.settings import get_setting
  3147. async with async_session() as db:
  3148. capture_enabled = await get_setting(db, "capture_finish_photo")
  3149. if capture_enabled is not None and capture_enabled.lower() != "true":
  3150. return None
  3151. # Try external camera first
  3152. if printer.external_camera_enabled and printer.external_camera_url:
  3153. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3154. from backend.app.api.routes.camera import live_frame_for_capture
  3155. from backend.app.services.external_camera import capture_frame
  3156. # An external camera allows one reader, so capturing while a viewer
  3157. # is attached fails (#2707). A None here falls through to the paths
  3158. # below exactly as a failed capture did.
  3159. defer, buffered = live_frame_for_capture(printer_id)
  3160. if defer:
  3161. frame_data = buffered
  3162. else:
  3163. frame_data = await capture_frame(
  3164. printer.external_camera_url,
  3165. printer.external_camera_type or "mjpeg",
  3166. snapshot_url=printer.external_camera_snapshot_url,
  3167. )
  3168. if frame_data and len(frame_data) <= 2_500_000:
  3169. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3170. return _apply_camera_rotation(frame_data, printer, logger)
  3171. # Try buffered frame from active stream
  3172. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3173. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3174. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3175. buffered_frame = get_buffered_frame(printer_id)
  3176. if (active_for_printer or active_chamber) and buffered_frame:
  3177. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3178. if len(buffered_frame) <= 2_500_000:
  3179. return _apply_camera_rotation(buffered_frame, printer, logger)
  3180. # Fresh capture from printer camera
  3181. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3182. from backend.app.services.camera import capture_camera_frame_bytes
  3183. frame_data = await capture_camera_frame_bytes(
  3184. printer.ip_address, printer.access_code, printer.model, timeout=15
  3185. )
  3186. if frame_data and len(frame_data) <= 2_500_000:
  3187. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3188. return _apply_camera_rotation(frame_data, printer, logger)
  3189. except Exception as e:
  3190. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3191. return None
  3192. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3193. """#1867: bank a recent in-print camera frame for the finish photo.
  3194. Called on every layer change and (#2547) on every print-progress advance.
  3195. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3196. path has a pre-End-G-code image for prints that end with a plate swap.
  3197. Both drivers are print telemetry that stops the instant printing ends: no
  3198. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3199. plate swap) executes. So the last banked frame is always the finished print,
  3200. never the swapped plate — that property is what the #1867 path relies on and
  3201. it must survive any change to the throttle below.
  3202. Layer changes alone were not enough: they stop when the *final* layer
  3203. begins, which on a three-minute last layer left the bank stale by the whole
  3204. length of that layer (#2547). Progress keeps ticking through it.
  3205. Best-effort: any failure just leaves the previous banked frame.
  3206. """
  3207. logger = logging.getLogger(__name__)
  3208. client = printer_manager.get_client(printer_id)
  3209. state = client.state if client else None
  3210. if not state or state.state != "RUNNING":
  3211. return
  3212. # Only during actual extrusion — firmware ticks layer_num during the
  3213. # pre-print calibration sequence, whose sub-stages are non-zero.
  3214. if state.mc_print_sub_stage not in (None, 0):
  3215. return
  3216. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3217. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3218. # now that progress advances also drive banking, that exemption would fire a
  3219. # camera grab on every percent tick of the last layer. Bambu printers accept
  3220. # one RTSP client at a time, so each grab contends with the live view.
  3221. now = time.monotonic()
  3222. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3223. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3224. return
  3225. total = state.total_layers or 0
  3226. try:
  3227. async with async_session() as db:
  3228. from backend.app.models.printer import Printer
  3229. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3230. printer = result.scalar_one_or_none()
  3231. if not printer:
  3232. return
  3233. # Reuses the notification snapshot path, which honours the
  3234. # `capture_finish_photo` setting (returns None when disabled) so we
  3235. # don't bank frames the user never asked for. Without the chamber light
  3236. # (#1655): this runs every 25 seconds for the whole print.
  3237. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3238. if frame:
  3239. _inprint_frame_bank[printer_id] = frame
  3240. _inprint_frame_bank_ts[printer_id] = now
  3241. logger.debug(
  3242. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3243. printer_id,
  3244. layer_num,
  3245. total,
  3246. len(frame),
  3247. )
  3248. except Exception as e:
  3249. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3250. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3251. """Apply camera rotation to snapshot image if configured."""
  3252. from backend.app.services.camera import apply_camera_rotation
  3253. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3254. async def _send_print_start_notification(
  3255. printer_id: int,
  3256. data: dict,
  3257. archive_data: dict | None = None,
  3258. logger=None,
  3259. ):
  3260. """Helper to send print start notification with optional archive data."""
  3261. if logger is None:
  3262. logger = logging.getLogger(__name__)
  3263. try:
  3264. async with async_session() as db:
  3265. from backend.app.models.printer import Printer
  3266. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3267. printer = result.scalar_one_or_none()
  3268. printer_name = printer.name if printer else f"Printer {printer_id}"
  3269. # Capture camera snapshot for notification image attachment
  3270. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3271. if image_data:
  3272. if archive_data is None:
  3273. archive_data = {}
  3274. archive_data["image_data"] = image_data
  3275. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3276. # Send user-specific email notification for print start
  3277. if archive_data and archive_data.get("created_by_id"):
  3278. await notification_service.send_user_print_email(
  3279. event_type="user_print_start",
  3280. created_by_id=archive_data["created_by_id"],
  3281. printer_name=printer_name,
  3282. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3283. db=db,
  3284. )
  3285. except Exception as e:
  3286. logger.warning("Notification on_print_start failed: %s", e)
  3287. async def _dispatch_user_print_email(
  3288. status: str,
  3289. created_by_id: int | None,
  3290. printer_name: str,
  3291. filename: str,
  3292. db,
  3293. image_data: bytes | None = None,
  3294. finish_photo_url: str | None = None,
  3295. ) -> None:
  3296. """Send a user-specific print-completion email based on print status.
  3297. Maps the normalised print status to the correct event type and delegates
  3298. to :meth:`NotificationService.send_user_print_email`. A single helper
  3299. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3300. "stopped"`` dispatch block at every call site.
  3301. Does nothing if *created_by_id* is ``None``.
  3302. """
  3303. if created_by_id is None:
  3304. return
  3305. if status == "completed":
  3306. event_type = "user_print_complete"
  3307. elif status == "failed":
  3308. event_type = "user_print_failed"
  3309. elif status in ("stopped", "aborted", "cancelled"):
  3310. event_type = "user_print_stopped"
  3311. else:
  3312. return
  3313. await notification_service.send_user_print_email(
  3314. event_type=event_type,
  3315. created_by_id=created_by_id,
  3316. printer_name=printer_name,
  3317. filename=filename,
  3318. db=db,
  3319. image_data=image_data,
  3320. finish_photo_url=finish_photo_url,
  3321. )
  3322. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3323. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3324. try:
  3325. from backend.app.services.archive import extract_printable_objects_from_archive
  3326. client = printer_manager.get_client(printer_id)
  3327. if not client:
  3328. return
  3329. # Extract with positions for UI overlay, scoped to the plate that
  3330. # is printing — resolve_plate_id is the same resolver /cover uses,
  3331. # so the object list can't disagree with the thumbnail it is drawn
  3332. # over (#2522).
  3333. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3334. app_settings.base_dir / archive.file_path,
  3335. plate_number=resolve_plate_id(client.state),
  3336. )
  3337. if printable_objects:
  3338. client.state.printable_objects = printable_objects
  3339. client.state.printable_objects_bbox_all = bbox_all
  3340. client.state.skipped_objects = []
  3341. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3342. except Exception as e:
  3343. logger.debug("Failed to extract printable objects from archive: %s", e)
  3344. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3345. """Put the skip-objects list back after a restart mid-print.
  3346. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3347. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3348. which the #1304 guard suppresses on the first RUNNING push after startup.
  3349. Everything else this hook restores (the archive, the usage-tracking session,
  3350. the timelapse baseline) was already handled; the object list was not, so a
  3351. restart mid-print took skip-objects away for the rest of that print.
  3352. Nothing recovered it either: the printer card gates its Skip button on the
  3353. object count, and the one endpoint that can rebuild the list is reachable
  3354. only from the modal that button opens.
  3355. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3356. leftover ``status="printing"`` row from a completion we never saw cannot
  3357. hand this print someone else's objects. Without one, nothing is loaded
  3358. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3359. case on demand.
  3360. """
  3361. client = printer_manager.get_client(printer_id)
  3362. if client is None or client.state.printable_objects:
  3363. return
  3364. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3365. if subtask_id in ("", "0"):
  3366. return
  3367. from backend.app.models.archive import PrintArchive
  3368. archive = await db.scalar(
  3369. select(PrintArchive)
  3370. .where(
  3371. PrintArchive.printer_id == printer_id,
  3372. PrintArchive.status == "printing",
  3373. PrintArchive.subtask_id == subtask_id,
  3374. )
  3375. .order_by(PrintArchive.created_at.desc())
  3376. .limit(1)
  3377. )
  3378. if archive is not None:
  3379. _load_objects_from_archive(archive, printer_id, logger)
  3380. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3381. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3382. # past it; the second covers a handshake that failed again on the way back and
  3383. # armed a fresh one. Module-level so tests can shrink them.
  3384. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3385. # Retry ladder for the other temporary give-up: the file service answered and
  3386. # the transfer still did not finish, which at print start is usually the printer
  3387. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3388. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3389. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3390. # two cover a printer that stays busy well into the print.
  3391. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3392. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3393. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3394. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3395. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3396. # by view, so two views race), the cool-off retry task, and print completion.
  3397. # Without this they each read file_path == "" and each run a full copy, so the row
  3398. # ends up pointing at one timestamped directory while the others sit orphaned.
  3399. #
  3400. # Keyed by printer rather than archive because a printer runs one print at a time,
  3401. # which makes the two equally strong here — and it bounds the dict by printer
  3402. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3403. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3404. # resuming, so "no waiters" is not a question this API can answer.
  3405. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3406. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3407. """Fill in a no-3MF archive from a 3MF that turned up later.
  3408. Returns True when the row was upgraded. Safe to call speculatively: it
  3409. verifies the archive still exists, is still a fallback, and that the file
  3410. is a readable 3MF before touching anything.
  3411. Serialised per printer — see ``_fallback_recovery_locks``.
  3412. """
  3413. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3414. async with lock:
  3415. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3416. async def _recover_fallback_archive_locked(
  3417. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3418. ) -> bool:
  3419. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3420. ``price`` is False when the print's end is being handled: the archive
  3421. still reads "printing" then, and its end prices it.
  3422. """
  3423. import zipfile
  3424. from backend.app.models.archive import PrintArchive
  3425. from backend.app.services.archive import ArchiveService
  3426. logger = logging.getLogger(__name__)
  3427. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3428. return False
  3429. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3430. # A truncated or half-written download is worse than no download: it
  3431. # would replace an honest empty archive with wrong metadata.
  3432. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3433. return False
  3434. async with async_session() as db:
  3435. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3436. if archive is None or archive.deleted_at is not None:
  3437. return False
  3438. if archive.file_path:
  3439. # Already recovered, or never was a fallback. Either way there is a
  3440. # real 3MF attached and overwriting it is not this function's job.
  3441. return False
  3442. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3443. service = ArchiveService(db)
  3444. recovered = await service.archive_print(
  3445. printer_id=printer_id,
  3446. source_file=source_3mf,
  3447. print_data={**print_data, "status": archive.status or "printing"},
  3448. subtask_id=archive.subtask_id,
  3449. update_archive_id=archive.id,
  3450. )
  3451. if recovered is None:
  3452. return False
  3453. logger.info(
  3454. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3455. archive_id,
  3456. source_3mf,
  3457. recovered.file_size,
  3458. )
  3459. # Spoolman's tracking stored no 3MF usage at print start and would
  3460. # charge the AMS remain% change; the built-in tracker reads the archive
  3461. # at completion and needs nothing. Also at the print's end (``price``
  3462. # False): that recovery runs inside the close-out, before the charge.
  3463. try:
  3464. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3465. from backend.app.services.usage_tracker import is_completing
  3466. await attach_recovered_3mf(
  3467. printer_id,
  3468. recovered.id,
  3469. recovered.file_path,
  3470. db,
  3471. printer_manager,
  3472. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3473. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3474. )
  3475. except Exception:
  3476. logger.warning(
  3477. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3478. )
  3479. if price and recovered.status == "printing":
  3480. # Print start priced it from the default rate, having no 3MF to
  3481. # estimate from; now it has one. An ended print is left alone: its
  3482. # end prices it. A print Bambuddy didn't dispatch has no start
  3483. # plate; the one the archive just read from the 3MF stands in.
  3484. _schedule_archive_cost_estimate(
  3485. printer_id,
  3486. recovered.id,
  3487. printer_manager,
  3488. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3489. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3490. session_factory=async_session,
  3491. )
  3492. # `archive_updated`, not `archive_created` — the row was already on the
  3493. # Archives page as an empty card and is now filled in, not new.
  3494. await ws_manager.send_archive_updated(
  3495. {
  3496. "id": recovered.id,
  3497. "printer_id": recovered.printer_id,
  3498. "filename": recovered.filename,
  3499. "print_name": recovered.print_name,
  3500. "status": recovered.status,
  3501. }
  3502. )
  3503. return True
  3504. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3505. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3506. Called from the paths that pull a 3MF for a print that is already under way
  3507. — chiefly the cover endpoint, which downloads the very file the archive flow
  3508. could not get and, before #2957, used it for a thumbnail and nothing else.
  3509. The bytes are already local, so this costs a parse and a row update.
  3510. No-op when the running print has a real archive, which is the common case.
  3511. """
  3512. from backend.app.models.archive import PrintArchive
  3513. logger = logging.getLogger(__name__)
  3514. # `_active_prints` is keyed on the raw names seen at print start — the
  3515. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3516. # Callers here arrive with whichever variant their own path produced, so
  3517. # match on the same normalization the download cache uses rather than on an
  3518. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3519. # endpoint find an archive registered under "Desktop_Goose".
  3520. wanted = normalize_3mf_name(name)
  3521. archive_id = None
  3522. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3523. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3524. archive_id = value
  3525. break
  3526. if archive_id is None:
  3527. return False
  3528. async with async_session() as db:
  3529. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3530. # Cheap pre-check so the common case (a normal archive) does no work.
  3531. if archive is None or archive.file_path or archive.deleted_at is not None:
  3532. return False
  3533. try:
  3534. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3535. except Exception as e:
  3536. # Recovery is opportunistic. A failure here must never take down the
  3537. # caller, which is usually just trying to render a thumbnail.
  3538. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3539. return False
  3540. def _schedule_fallback_3mf_retry(
  3541. printer_id: int,
  3542. archive_id: int,
  3543. filenames: list[str],
  3544. delays: tuple[float, ...] | None = None,
  3545. reason: str = REASON_FTPS_COOLOFF,
  3546. ) -> None:
  3547. """Re-attempt the 3MF download after a temporary give-up.
  3548. ``reason`` says which give-up this is, and picks the default ladder: an
  3549. FTPS cool-off has to be waited out, while a transfer that timed out under
  3550. contention is worth asking about again straight away (#3063). It is only
  3551. read for the ladder and the log line -- the retry itself is identical, since
  3552. in both cases the file is on the printer and the last attempt at it failed
  3553. for a reason that does not last.
  3554. """
  3555. logger = logging.getLogger(__name__)
  3556. if delays is None:
  3557. delays = (
  3558. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3559. if reason == REASON_FTP_TRANSFER_FAILED
  3560. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3561. )
  3562. async def _retry() -> None:
  3563. from backend.app.models.archive import PrintArchive
  3564. from backend.app.models.printer import Printer
  3565. for delay in delays:
  3566. await asyncio.sleep(delay)
  3567. async with async_session() as db:
  3568. archive = (
  3569. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3570. ).scalar_one_or_none()
  3571. if archive is None or archive.deleted_at is not None or archive.file_path:
  3572. return
  3573. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3574. if printer is None:
  3575. return
  3576. # Read the fields while the session is open rather than touching
  3577. # a detached instance minutes later, mid-download.
  3578. printer_ip = printer.ip_address
  3579. printer_code = printer.access_code
  3580. printer_model = printer.model
  3581. # Someone else may have fetched it in the meantime — the cover
  3582. # endpoint routinely does, and its copy is the same bytes.
  3583. for name in filenames:
  3584. cached = get_cached_3mf(printer_id, name)
  3585. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3586. return
  3587. if ftps_handshake_blocked(printer_ip):
  3588. logger.info(
  3589. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3590. printer_id,
  3591. archive_id,
  3592. )
  3593. continue
  3594. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3595. for candidate in filenames:
  3596. # Bare name only. These come from the print-start flow, which
  3597. # already strips the path, but the local temp write must not
  3598. # depend on that holding for every future caller — a name that
  3599. # is absolute or contains ".." would otherwise escape the data
  3600. # volume via the `/` operator.
  3601. name = Path(candidate).name
  3602. if not name or name in (".", ".."):
  3603. continue
  3604. if not name.endswith(".3mf"):
  3605. name = f"{name}.3mf"
  3606. temp_path = app_settings.archive_dir / "temp" / name
  3607. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3608. try:
  3609. hit = await download_file_try_paths_async(
  3610. printer_ip,
  3611. printer_code,
  3612. ftp_probe_paths(name),
  3613. temp_path,
  3614. socket_timeout=ftp_timeout,
  3615. printer_model=printer_model,
  3616. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3617. )
  3618. except Exception as e:
  3619. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3620. continue
  3621. if not hit:
  3622. continue
  3623. cache_3mf_download(printer_id, name, temp_path)
  3624. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3625. return
  3626. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3627. async def _guarded() -> None:
  3628. try:
  3629. await _retry()
  3630. except asyncio.CancelledError:
  3631. raise
  3632. except Exception as e:
  3633. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3634. finally:
  3635. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3636. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3637. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3638. if existing and not existing.done():
  3639. existing.cancel()
  3640. task = asyncio.create_task(_guarded())
  3641. _fallback_3mf_retry_tasks[printer_id] = task
  3642. logger.info(
  3643. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3644. archive_id,
  3645. reason,
  3646. printer_id,
  3647. ", ".join(f"{d:g}s" for d in delays),
  3648. )
  3649. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3650. """Whether an archive created here should ask for the print's outcome (#1898).
  3651. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3652. branches below: a queued job already has its archive and takes the
  3653. expected-print branch, where the queue item's own ``confirm_outcome``
  3654. decides. The queue is still consulted, because a restart mid-print empties
  3655. ``_expected_prints`` — without the check the setting could override a queue
  3656. item that deliberately has the flag off. Any failure answers "don't ask":
  3657. an unwanted prompt is worse than a missing one, and this must never be the
  3658. reason a print goes unarchived.
  3659. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3660. leaves one behind when a completion cannot be matched to it
  3661. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3662. only takes it back once the printer has sat connected and terminal for
  3663. minutes. Until then every screen-started print on that printer would
  3664. silently lose its prompt, so the row is held against ``observed_name`` by
  3665. the same comparison a completion uses: a positive disagreement means the row
  3666. is about some other run and this print is external after all.
  3667. """
  3668. logger = logging.getLogger(__name__)
  3669. try:
  3670. # A savepoint rather than a rollback of the caller's transaction on
  3671. # failure: a failed statement leaves the transaction unusable, but a
  3672. # full rollback also expires every object the caller has loaded (the
  3673. # printer, the archive it just created), and on an async session the
  3674. # next attribute read then raises instead of reloading. Everything here
  3675. # is a read, so undoing the savepoint loses nothing.
  3676. async with db.begin_nested():
  3677. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3678. except Exception as e:
  3679. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3680. return False
  3681. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3682. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3683. from backend.app.api.routes.settings import get_setting, setting_is_true
  3684. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3685. return False
  3686. from backend.app.models.print_queue import PrintQueueItem
  3687. dispatched_here = await db.scalar(
  3688. select(PrintQueueItem)
  3689. .where(
  3690. PrintQueueItem.printer_id == printer_id,
  3691. PrintQueueItem.status == "printing",
  3692. )
  3693. .limit(1)
  3694. )
  3695. if dispatched_here is None:
  3696. return True
  3697. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3698. observed = (observed_name or "").strip()
  3699. if not expected or not observed or _subtask_names_match(expected, observed):
  3700. logger.info(
  3701. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3702. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3703. printer_id,
  3704. dispatched_here.id,
  3705. )
  3706. return False
  3707. logger.info(
  3708. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3709. "%r; treating this as an externally started print.",
  3710. dispatched_here.id,
  3711. printer_id,
  3712. expected,
  3713. observed,
  3714. )
  3715. return True
  3716. async def _dispatch_outcome_confirmation_safely(
  3717. db,
  3718. printer_id: int,
  3719. printer_name: str,
  3720. data: dict,
  3721. archive_id: int,
  3722. archive_data: dict | None = None,
  3723. ) -> None:
  3724. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3725. The completion task sends the per-user print email on the same session
  3726. right after the prompt. A failed statement in the prompt leaves that
  3727. session needing a rollback, and without one the email step fails with
  3728. PendingRollbackError; the prompt is the optional part, so it must not be
  3729. the reason the email never goes out.
  3730. """
  3731. try:
  3732. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3733. except Exception as e:
  3734. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3735. try:
  3736. await db.rollback()
  3737. except Exception:
  3738. pass
  3739. async def dispatch_outcome_confirmation(
  3740. db,
  3741. printer_id: int,
  3742. printer_name: str,
  3743. data: dict,
  3744. archive_id: int,
  3745. archive_data: dict | None = None,
  3746. ) -> bool:
  3747. """Emit the post-print outcome prompt for a completed archive (#1898).
  3748. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3749. queue item, or from ``confirm_outcome_external_prints`` for a print
  3750. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3751. question still open. Mints the per-archive capability token the one-tap
  3752. verdict links carry.
  3753. Lives here rather than inline in ``on_print_complete``'s notification task
  3754. because that task swallows every exception: extracted, the gate and the two
  3755. emissions can be driven by a test, which is the only thing standing between
  3756. a regression here and a farm that quietly stops asking.
  3757. Returns whether a prompt was sent.
  3758. """
  3759. logger = logging.getLogger(__name__)
  3760. from backend.app.models.archive import PrintArchive
  3761. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3762. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3763. return False
  3764. import secrets as _secrets
  3765. # A spent token stays on the row so the one-tap route can recognise it, so
  3766. # "has a token" no longer means "answerable". A prompt going out now needs a
  3767. # live one: mint a new token whenever the stored one is already spent, or
  3768. # every button in the new message would land on the already-answered page.
  3769. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3770. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3771. confirm_archive.confirm_token_used_at = None
  3772. await db.commit()
  3773. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3774. base = await get_external_base_url(db)
  3775. if not await get_setting(db, "external_url"):
  3776. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3777. # absolute URL, so an unconfigured install used to get a message body
  3778. # with two unusable relative paths and no buttons at all. The shared
  3779. # fallback at least produces tappable links; say which setting makes
  3780. # them resolve from a phone.
  3781. logger.warning(
  3782. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3783. "Set Settings → External URL so they resolve away from this host.",
  3784. base,
  3785. )
  3786. token = confirm_archive.confirm_token
  3787. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3788. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3789. confirm_url = f"{base}/archives?confirm={archive_id}"
  3790. await ws_manager.send_print_confirm_request(
  3791. printer_id,
  3792. {
  3793. "archive_id": archive_id,
  3794. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3795. },
  3796. )
  3797. await notification_service.on_print_confirm_request(
  3798. printer_id,
  3799. printer_name,
  3800. data,
  3801. db,
  3802. archive_data=archive_data,
  3803. good_url=good_url,
  3804. reject_url=reject_url,
  3805. confirm_url=confirm_url,
  3806. archive_id=archive_id,
  3807. )
  3808. return True
  3809. async def _printer_gone(db, printer_id: int) -> bool:
  3810. """Whether the printer was deleted. A column read: the session's loaded
  3811. Printer would otherwise answer for the database."""
  3812. from backend.app.models.printer import Printer
  3813. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3814. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3815. """Remove the archive just written if its printer was deleted meanwhile.
  3816. The delete route sweeps the printer's archives before it commits, so a row
  3817. committed after that sweep (the check before writing passed while the
  3818. delete was still uncommitted) is left for a printer that will never report
  3819. the print's end. A row the sweep reached is the route's: deleted with the
  3820. printer's archives, or detached (printer_id NULL) when the user kept them,
  3821. and then left as it is. Either way nothing is registered for it. Run after
  3822. the archive's commit, before anything is registered for it.
  3823. """
  3824. from backend.app.models.archive import PrintArchive
  3825. if not await _printer_gone(db, printer_id):
  3826. return False
  3827. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3828. if owner == printer_id:
  3829. logging.getLogger(__name__).info(
  3830. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3831. )
  3832. await ArchiveService(db).delete_archive(archive_id)
  3833. await forget_printer(printer_id)
  3834. return True
  3835. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3836. """After an IntegrityError on a print start's archive write: whether it was
  3837. the printer being deleted, forgotten then (the caller returns).
  3838. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3839. commit, so an archive written or adopted for it meanwhile (one that sets
  3840. printer_id) waits and the printer's foreign key then refuses it. That is
  3841. the printer being deleted, not an error; anything else is re-raised by the
  3842. caller.
  3843. """
  3844. await db.rollback()
  3845. if not await _printer_gone(db, printer_id):
  3846. return False
  3847. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3848. await forget_printer(printer_id)
  3849. return True
  3850. async def _forget_if_printer_gone(printer_id: int) -> None:
  3851. """At the end of a print start: the slow steps after the last check (smart
  3852. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3853. printer's delete and its forget_printer, and then wrote state back.
  3854. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3855. SQLite; PostgreSQL refuses it.)
  3856. Its own session: those steps can leave the handler's needing a rollback (a
  3857. write to the archive the delete removed). Never raises: it runs inside the
  3858. fallback branch's try, whose except reports the archive as failed.
  3859. """
  3860. try:
  3861. async with async_session() as db:
  3862. gone = await _printer_gone(db, printer_id)
  3863. if gone:
  3864. await forget_printer(printer_id)
  3865. except Exception:
  3866. logging.getLogger(__name__).warning(
  3867. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3868. )
  3869. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  3870. """Tell the UI a plate check could not run. It does not block the print,
  3871. but an unchecked plate is not an empty one."""
  3872. try:
  3873. await ws_manager.broadcast(
  3874. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  3875. )
  3876. except Exception as e:
  3877. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  3878. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  3879. """The ``_expected_prints`` keys a print start may be registered under."""
  3880. keys: list[tuple[int, str]] = []
  3881. if subtask_name:
  3882. keys.append((printer_id, subtask_name))
  3883. keys.append((printer_id, f"{subtask_name}.3mf"))
  3884. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3885. if filename:
  3886. fname = filename.split("/")[-1] if "/" in filename else filename
  3887. keys.append((printer_id, fname))
  3888. # Strip extensions to match
  3889. base = fname.replace(".gcode", "").replace(".3mf", "")
  3890. keys.append((printer_id, base))
  3891. keys.append((printer_id, f"{base}.3mf"))
  3892. return keys
  3893. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  3894. """Whether this print start is one Bambuddy sent to the printer."""
  3895. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  3896. return True
  3897. from backend.app.models.archive import PrintArchive
  3898. from backend.app.models.print_queue import PrintQueueItem
  3899. # The queue row the scheduler sets to printing before it sends -- but only
  3900. # when it was sent as this print: a row left printing by a run whose end
  3901. # was missed names another file.
  3902. dispatched_names = (
  3903. await db.execute(
  3904. select(PrintArchive.filename)
  3905. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  3906. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  3907. )
  3908. ).scalars()
  3909. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  3910. return any(
  3911. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  3912. for dispatched in dispatched_names
  3913. if dispatched
  3914. for seen in observed
  3915. )
  3916. async def on_print_start(printer_id: int, data: dict):
  3917. """Handle print start - archive the 3MF file immediately."""
  3918. logger = logging.getLogger(__name__)
  3919. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3920. try:
  3921. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3922. except Exception:
  3923. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3924. # Clear any stale user-stopped flag from previous print cycles
  3925. _user_stopped_printers.discard(printer_id)
  3926. _kill_switch_stopped.discard(printer_id)
  3927. # A new print starts its milestones from zero (#3211). The status path only
  3928. # resets on progress below 5 while not printing, which a printer that goes
  3929. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3930. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3931. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3932. _last_progress_milestone[printer_id] = 0
  3933. _kill_switch_notification_tasks.pop(printer_id, None)
  3934. # #1721: drop any leftover pre-captured finish frame from a prior print
  3935. # so a never-consumed cache entry can't bleed into the new print's photo.
  3936. _stage22_finish_frames.pop(printer_id, None)
  3937. # #1867: same for the in-print frame bank — a queued print must not reuse
  3938. # the previous job's banked frame.
  3939. _inprint_frame_bank.pop(printer_id, None)
  3940. _inprint_frame_bank_ts.pop(printer_id, None)
  3941. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3942. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3943. # print's flag instead of inheriting it.
  3944. print_dispatch_context.adopt(printer_id)
  3945. # Cancel any active bed cooldown waiter for this printer
  3946. if _bed_cool_waiters.pop(printer_id, None):
  3947. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3948. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3949. from backend.app.api.routes.printers import clear_cover_cache
  3950. clear_cover_cache(printer_id)
  3951. await ws_manager.send_print_start(printer_id, data)
  3952. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3953. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3954. # MQTT relay - publish print start
  3955. try:
  3956. printer_info = printer_manager.get_printer(printer_id)
  3957. if printer_info:
  3958. await mqtt_relay.on_print_start(
  3959. printer_id,
  3960. printer_info.name,
  3961. printer_info.serial_number,
  3962. data.get("filename", ""),
  3963. data.get("subtask_name", ""),
  3964. )
  3965. except Exception:
  3966. pass # Don't fail print start callback if MQTT fails
  3967. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3968. # and mapping, and the seeded tray-change log.
  3969. #
  3970. # Unconditional, for both inventory backends. This only *captures* — the
  3971. # writing is still split, with the internal tracker skipped at completion
  3972. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3973. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3974. # tray-change log, and that log is the only record of which spool fed
  3975. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3976. # it on one side only would leave Spoolman users with the mid-print
  3977. # restart bug this fixes for everyone else.
  3978. try:
  3979. async with async_session() as db:
  3980. from backend.app.api.routes.settings import get_setting
  3981. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3982. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3983. await usage_on_print_start(
  3984. printer_id,
  3985. data,
  3986. printer_manager,
  3987. db=db,
  3988. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3989. )
  3990. except Exception as e:
  3991. logger.warning("Usage tracker on_print_start failed: %s", e)
  3992. # Track if notification was sent (to avoid sending twice)
  3993. notification_sent = False
  3994. # Smart plug automation: turn on plug when print starts
  3995. try:
  3996. async with async_session() as db:
  3997. await smart_plug_manager.on_print_start(printer_id, db)
  3998. except Exception as e:
  3999. logger.warning("Smart plug on_print_start failed: %s", e)
  4000. async with async_session() as db:
  4001. from backend.app.models.printer import Printer
  4002. from backend.app.services.bambu_ftp import list_files_async
  4003. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4004. printer = result.scalar_one_or_none()
  4005. # Plate detection check - pause if objects detected on build plate
  4006. logger.info(
  4007. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4008. )
  4009. if printer and printer.plate_detection_enabled:
  4010. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4011. # Release the pooled DB connection before the plate-detection camera
  4012. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4013. # printer SELECT has run so far — nothing to persist — so this commit
  4014. # is a data-noop that ends the read transaction and returns the
  4015. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4016. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4017. # archive lookups below re-acquire a fresh connection on next execute.
  4018. await db.commit()
  4019. try:
  4020. from backend.app.services.plate_detection import check_plate_empty
  4021. # Build ROI tuple from printer settings if available
  4022. roi = None
  4023. if all(
  4024. [
  4025. printer.plate_detection_roi_x is not None,
  4026. printer.plate_detection_roi_y is not None,
  4027. printer.plate_detection_roi_w is not None,
  4028. printer.plate_detection_roi_h is not None,
  4029. ]
  4030. ):
  4031. roi = (
  4032. printer.plate_detection_roi_x,
  4033. printer.plate_detection_roi_y,
  4034. printer.plate_detection_roi_w,
  4035. printer.plate_detection_roi_h,
  4036. )
  4037. # The light is held, not switched, so a live view opened
  4038. # meanwhile keeps it when the check lets go (SP-C11). Every
  4039. # printer, whatever the camera light mode: detection needs it.
  4040. plate_photo_data = None
  4041. objects_detected = False
  4042. check_failure: str | None = None
  4043. async with camera_light(printer, any_mode=True, settle=2.5):
  4044. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4045. plate_result = await check_plate_empty(
  4046. printer_id=printer_id,
  4047. ip_address=printer.ip_address,
  4048. access_code=printer.access_code,
  4049. model=printer.model,
  4050. include_debug_image=False,
  4051. external_camera_url=printer.external_camera_url,
  4052. external_camera_type=printer.external_camera_type,
  4053. use_external=printer.external_camera_enabled,
  4054. roi=roi,
  4055. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4056. )
  4057. # No reference to compare against is a check that did not
  4058. # run either: say so rather than call the plate empty.
  4059. check_failure = getattr(plate_result, "failure_reason", None) or (
  4060. "not_calibrated" if plate_result.needs_calibration else None
  4061. )
  4062. objects_detected = not check_failure and not plate_result.is_empty
  4063. if objects_detected:
  4064. # Objects detected - pause the print!
  4065. logger.warning(
  4066. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4067. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4068. )
  4069. pause_client = printer_manager.get_client(printer_id)
  4070. if pause_client:
  4071. pause_client.pause_print()
  4072. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4073. # Snapshot while the light's still on — restoring it first
  4074. # would leave the notification with a dark photo.
  4075. try:
  4076. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4077. except Exception as snap_err:
  4078. logger.warning(
  4079. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4080. )
  4081. if objects_detected:
  4082. # Send notification about plate not empty
  4083. await ws_manager.broadcast(
  4084. {
  4085. "type": "plate_not_empty",
  4086. "printer_id": printer_id,
  4087. "printer_name": printer.name,
  4088. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4089. }
  4090. )
  4091. # Also send push notification
  4092. try:
  4093. await notification_service.on_plate_not_empty(
  4094. printer_id=printer_id,
  4095. printer_name=printer.name,
  4096. db=db,
  4097. difference_percent=plate_result.difference_percent,
  4098. image_data=plate_photo_data,
  4099. )
  4100. except Exception as notif_err:
  4101. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4102. elif check_failure:
  4103. logger.warning(
  4104. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4105. printer_id,
  4106. check_failure,
  4107. plate_result.message,
  4108. )
  4109. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4110. else:
  4111. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4112. except Exception as plate_err:
  4113. # Don't block print on plate detection errors
  4114. logger.warning(
  4115. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4116. printer_id,
  4117. plate_err,
  4118. )
  4119. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4120. if not printer:
  4121. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4122. if not notification_sent:
  4123. await _send_print_start_notification(printer_id, data, logger=logger)
  4124. return
  4125. # Skip the printer's own jobs — a calibration run is not a user's print.
  4126. # See is_internal_printer_job for what counts and why both fields are
  4127. # tested; the pressure-advance line reports as a subtask name with no
  4128. # /usr/ path, which the old prefix-only test here missed entirely.
  4129. #
  4130. # No notification either. The event describes the printer calibrating
  4131. # itself, so "Print started" is as wrong as the archive was, and the
  4132. # matching completion is suppressed in on_print_complete for the same
  4133. # reason. Checked before the auto-archive switches, whose "off" path
  4134. # still notifies.
  4135. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4136. # print Bambuddy dispatched is never one, whatever it is called.
  4137. # Dispatched = an expected print, or, after a restart that lost those,
  4138. # a queue job printing on the printer.
  4139. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4140. (data.get("filename") or "").startswith("/usr/")
  4141. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4142. ):
  4143. logger.info(
  4144. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4145. data.get("filename", ""),
  4146. data.get("subtask_name", ""),
  4147. )
  4148. return
  4149. # The global switch is the master: off, no printer archives prints
  4150. # started outside Bambuddy; on, each printer's own switch decides.
  4151. from backend.app.api.routes.settings import get_setting
  4152. _global_auto_archive = await get_setting(db, "auto_archive")
  4153. archives_prints = printer.auto_archive and (
  4154. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4155. )
  4156. if not archives_prints:
  4157. # auto-archive disabled — check if there's an expected print (dispatched
  4158. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4159. # If so, fall through to the expected-print handling below so the archive
  4160. # is tracked in _active_prints and usage tracking works at completion.
  4161. _fn = data.get("filename", "")
  4162. _sn = data.get("subtask_name", "")
  4163. _check_keys: list[tuple[int, str]] = []
  4164. if _sn:
  4165. _check_keys += [
  4166. (printer_id, _sn),
  4167. (printer_id, f"{_sn}.3mf"),
  4168. (printer_id, f"{_sn}.gcode.3mf"),
  4169. ]
  4170. if _fn:
  4171. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4172. _check_keys.append((printer_id, _base_fn))
  4173. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4174. _check_keys += [
  4175. (printer_id, _no_archive_base),
  4176. (printer_id, f"{_no_archive_base}.3mf"),
  4177. ]
  4178. _has_expected = any(k in _expected_prints for k in _check_keys)
  4179. if not _has_expected:
  4180. # No expected print — truly external print (started from slicer/touchscreen)
  4181. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4182. if not notification_sent:
  4183. _no_archive_creator: int | None = None
  4184. for _key in _check_keys:
  4185. _expected_prints.pop(_key, None)
  4186. _expected_print_registered_at.pop(_key, None)
  4187. popped_creator = _expected_print_creators.pop(_key, None)
  4188. if _no_archive_creator is None:
  4189. _no_archive_creator = popped_creator
  4190. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4191. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4192. return
  4193. else:
  4194. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4195. # Get the filename and subtask_name
  4196. filename = data.get("filename", "")
  4197. subtask_name = data.get("subtask_name", "")
  4198. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4199. # present, it lets us match an archive across a backend restart (#972):
  4200. # same id → same print → resume the existing row instead of cancelling
  4201. # it and recreating from scratch (which loses started_at). Treat "0"
  4202. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4203. raw_mqtt = data.get("raw_data") or {}
  4204. subtask_id = raw_mqtt.get("subtask_id")
  4205. if subtask_id is not None:
  4206. subtask_id = str(subtask_id).strip()
  4207. if subtask_id in ("", "0"):
  4208. subtask_id = None
  4209. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4210. if not filename and not subtask_name:
  4211. # Send notification without archive data (no filename)
  4212. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4213. if not notification_sent:
  4214. await _send_print_start_notification(printer_id, data, logger=logger)
  4215. return
  4216. # Check if this is an expected print from reprint/scheduled
  4217. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4218. expected_archive_id = None
  4219. # Who queued it, taken with the entries it was registered beside: left
  4220. # behind once those are gone (the archive deleted mid-dispatch, or the
  4221. # start notification already sent), the expiry never saw it, and an
  4222. # unrelated later print of that name was attributed to that user (EP-2).
  4223. fallback_creator = None
  4224. for key in expected_keys:
  4225. expected_archive_id = _expected_prints.pop(key, None)
  4226. _expected_print_registered_at.pop(key, None)
  4227. if expected_archive_id:
  4228. # Clean up other possible keys for this print
  4229. for other_key in expected_keys:
  4230. _expected_prints.pop(other_key, None)
  4231. _expected_print_registered_at.pop(other_key, None)
  4232. creator = _expected_print_creators.pop(other_key, None)
  4233. if fallback_creator is None:
  4234. fallback_creator = creator
  4235. break
  4236. if expected_archive_id:
  4237. # This is a reprint/scheduled print - use existing archive, don't create new one
  4238. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4239. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4240. # Bambuddy's once the expected entry is consumed here.
  4241. _owned_print_archive_ids.add(expected_archive_id)
  4242. from backend.app.models.archive import PrintArchive
  4243. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4244. archive = result.scalar_one_or_none()
  4245. # Deleted after this handler loaded it (the plate check waits
  4246. # seconds) but before the route forgot the expected print: the
  4247. # archive the route kept or deleted is left as the route left it.
  4248. if archive and await _printer_gone(db, printer_id):
  4249. logger.info(
  4250. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4251. )
  4252. await forget_printer(printer_id)
  4253. return
  4254. if archive:
  4255. # As it was before this adoption: put back if the printer turns
  4256. # out to have been deleted while it was adopted (below).
  4257. before_adoption = {
  4258. attr.columns[0].name: getattr(archive, attr.key)
  4259. for attr in sa_inspect(PrintArchive).column_attrs
  4260. if attr.key != "id"
  4261. }
  4262. # Update archive status to printing
  4263. archive.status = "printing"
  4264. archive.started_at = datetime.now(timezone.utc)
  4265. # The previous run's outcome is not this one's: a reprint that
  4266. # completes must not keep showing why the last one failed.
  4267. archive.failure_reason = None
  4268. archive.completed_at = None
  4269. # The previous run's answer is still on this row and the
  4270. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4271. # so without a reset the second run inherits the first run's
  4272. # verdict: no prompt at all, and a green "good" badge on a run
  4273. # nobody ever judged.
  4274. if archive.confirm_requested:
  4275. archive.user_verdict = None
  4276. archive.user_verdict_source = None
  4277. archive.user_verdict_at = None
  4278. archive.confirm_token = None
  4279. archive.confirm_token_used_at = None
  4280. # Reprint of an archive reuses the source row. Without resetting
  4281. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4282. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4283. # extracts the *original* print's last frame, which then ships in
  4284. # the completion notification (#1707). Clear the path so the
  4285. # scanner runs fresh; also unlink the old video file so reprints
  4286. # don't accumulate orphans in the archive directory. Photos list
  4287. # is left alone — accumulating one finish photo per run is fine.
  4288. # The print-start baseline (#2704) is stale for the same reason:
  4289. # it describes the printer before the previous run. The capture
  4290. # below overwrites it, but clear it here too so an early failure
  4291. # can't leave the scan diffing against the wrong snapshot.
  4292. #
  4293. # Unlinked only when it is the same plate printing again. Every
  4294. # plate of a Send All shares this archive, and the video on it
  4295. # can be the only copy of another plate's run -- the printer's
  4296. # was deleted once it attached (#3275). That one is left in the
  4297. # archive directory, which goes with the archive. A video whose
  4298. # plate is not on record (attached by hand, or before the
  4299. # column existed) is kept too where the 3MF has other plates,
  4300. # or cannot be read: nothing tells it apart from another plate's,
  4301. # and keeping costs one file where deleting can cost the only
  4302. # copy. On an archive with exactly one plate it is that plate's.
  4303. archive.timelapse_baseline = None
  4304. stale_timelapse_relpath = archive.timelapse_path
  4305. stale_timelapse_plate_id = archive.timelapse_plate_id
  4306. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4307. if stale_timelapse_relpath:
  4308. archive.timelapse_path = None
  4309. archive.timelapse_plate_id = None
  4310. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4311. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4312. from backend.app.services.archive import plate_indexes_in_3mf
  4313. plates = await asyncio.to_thread(
  4314. plate_indexes_in_3mf,
  4315. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4316. )
  4317. stale_is_this_plates = len(plates) == 1
  4318. if stale_timelapse_relpath and not stale_is_this_plates:
  4319. logger.info(
  4320. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4321. stale_timelapse_relpath,
  4322. stale_timelapse_plate_id,
  4323. expected_archive_id,
  4324. starting_plate_id,
  4325. )
  4326. # The video is deleted once the adoption stands (below).
  4327. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4328. # Persist a restart-stable id so a later restart resumes this
  4329. # archive by subtask_id instead of name-matching + duplicating
  4330. # it (#1485). The printer often hasn't echoed subtask_id back
  4331. # this soon after dispatch, so fall back to the id Bambuddy
  4332. # minted when it sent the print command. Scoped to this
  4333. # expected-print branch on purpose: an expected match means
  4334. # Bambuddy dispatched this exact print in this process, so the
  4335. # client's last-dispatch id genuinely belongs to it — using it
  4336. # for an externally-started print could mis-tag the archive.
  4337. effective_subtask_id = subtask_id
  4338. if not effective_subtask_id:
  4339. _client = printer_manager.get_client(printer_id)
  4340. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4341. if _dispatched:
  4342. effective_subtask_id = str(_dispatched).strip() or None
  4343. # Update on first-set OR on reprint (the queue dispatcher mints
  4344. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4345. # the rewrite for reprints leaves the archive holding the FIRST
  4346. # run's id; if MQTT then reconnects mid-print, the reconciler
  4347. # (#1542) compares the stale stored id against the printer's
  4348. # live id, sees a mismatch, and synthesises a bogus PRINT
  4349. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4350. # in #1807. Inequality check preserves the noop-on-stable-push
  4351. # behaviour the earlier `not archive.subtask_id` guard provided.
  4352. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4353. archive.subtask_id = effective_subtask_id
  4354. # #1403 follow-up: VP-queue archives are created with
  4355. # printer_id=None at queue-add time (we don't know which
  4356. # printer will run the job yet). When the print actually
  4357. # starts on a specific printer the expected-archive lookup
  4358. # used to skip this assignment, leaving printer_id=None
  4359. # forever — which then disables the "Scan for timelapse"
  4360. # button in ArchivesPage (gated on !archive.printer_id).
  4361. if archive.printer_id != printer_id:
  4362. archive.printer_id = printer_id
  4363. adopting_id = archive.id # a rollback expires the object
  4364. try:
  4365. await db.commit()
  4366. except (IntegrityError, StaleDataError):
  4367. # The archive stays unchanged, or is gone: "delete archives"
  4368. # removed the row under the adoption, which then matched no
  4369. # row (StaleDataError) rather than being refused.
  4370. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4371. return
  4372. raise
  4373. # The printer can be deleted between the check above and this
  4374. # commit (the route's transaction lasts seconds), and the commit
  4375. # then adopted the archive anyway: status, verdict and timelapse
  4376. # changed, and the deleted printer's id written on a row the
  4377. # route had detached or never touched. Undo the adoption.
  4378. if await _printer_gone(db, printer_id):
  4379. logger.info(
  4380. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4381. printer_id,
  4382. archive.id,
  4383. )
  4384. # Everything as before this adoption. The printer it had
  4385. # then stays, unless it was the deleted one: the route
  4386. # detached that row (kept) or deleted it (no row matches).
  4387. previous_printer = before_adoption["printer_id"]
  4388. await db.execute(
  4389. update(PrintArchive)
  4390. .where(PrintArchive.id == archive.id)
  4391. .values(
  4392. {
  4393. **before_adoption,
  4394. "printer_id": None if previous_printer == printer_id else previous_printer,
  4395. }
  4396. )
  4397. )
  4398. await db.commit()
  4399. await forget_printer(printer_id)
  4400. return
  4401. if delete_stale_video and stale_timelapse_relpath:
  4402. try:
  4403. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4404. if stale_path.is_file():
  4405. stale_path.unlink()
  4406. logger.info(
  4407. "Deleted stale timelapse %s on reprint of archive %s",
  4408. stale_timelapse_relpath,
  4409. expected_archive_id,
  4410. )
  4411. except OSError as e:
  4412. logger.warning(
  4413. "Failed to delete stale timelapse %s on reprint: %s",
  4414. stale_timelapse_relpath,
  4415. e,
  4416. )
  4417. # Track as active print
  4418. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4419. # Start timelapse session if external camera is enabled (#1353).
  4420. # Queue / VP-dispatched prints land here in the expected-archive
  4421. # branch and used to skip start_session entirely — frames were
  4422. # never captured and the post-print stitch silently returned None.
  4423. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4424. # Inject ams_mapping into usage tracker session — the session was created
  4425. # before expected-print promotion, so it may have ams_mapping=None when
  4426. # the MQTT request topic subscription failed (common on P1S/A1).
  4427. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4428. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4429. if _stored_map or _stored_plate_id is not None:
  4430. try:
  4431. from backend.app.services.usage_tracker import _active_sessions
  4432. _ut_session = _active_sessions.get(printer_id)
  4433. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4434. _ut_session.ams_mapping = _stored_map
  4435. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4436. # plate_id injection covers direct-Print of plate N of a multi-plate
  4437. # 3MF — queue prints already capture it via the on_print_start queue
  4438. # lookup, but direct-Print never goes through the queue (#1697).
  4439. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4440. _ut_session.plate_id = _stored_plate_id
  4441. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4442. except Exception:
  4443. pass
  4444. # Set up energy tracking (#941: persist start on archive row)
  4445. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4446. await ws_manager.send_archive_updated(
  4447. {
  4448. "id": archive.id,
  4449. "status": "printing",
  4450. }
  4451. )
  4452. # Send notification with archive data (reprint/scheduled)
  4453. if not notification_sent:
  4454. # Use archive's created_by_id; fall back to the creator registered via
  4455. # register_expected_print (handles library-file-based queue items where
  4456. # the freshly-created archive has no created_by_id yet), taken above.
  4457. archive_data = {
  4458. "print_time_seconds": archive.print_time_seconds,
  4459. "created_by_id": archive.created_by_id or fallback_creator,
  4460. }
  4461. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4462. # Extract printable objects from the archived 3MF file
  4463. _load_objects_from_archive(archive, printer_id, logger)
  4464. # Store Spoolman tracking data for per-filament usage reporting
  4465. try:
  4466. await _store_spoolman_print_data(
  4467. printer_id,
  4468. archive.id,
  4469. archive.file_path,
  4470. db,
  4471. printer_manager,
  4472. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4473. plate_id=_get_start_plate_id(archive.id),
  4474. )
  4475. except Exception as e:
  4476. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4477. # Price the print from its spools now rather than only at completion (#3261)
  4478. _schedule_archive_cost_estimate(
  4479. printer_id,
  4480. archive.id,
  4481. printer_manager,
  4482. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4483. plate_id=_get_start_plate_id(archive.id),
  4484. session_factory=async_session,
  4485. )
  4486. # Capture timelapse file baseline for snapshot-diff on completion
  4487. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4488. # hit this branch — without the baseline the completion-time scan
  4489. # falls into its "take baseline now" fallback, which snapshots
  4490. # AFTER the new MP4 already exists and never matches a diff
  4491. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4492. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4493. await _forget_if_printer_gone(printer_id)
  4494. return # Skip creating a new archive
  4495. # The archive was deleted after the job was queued.
  4496. if not archives_prints:
  4497. # Only the expected print brought a printer that does not
  4498. # archive this far; with it gone, nothing is archived.
  4499. return
  4500. # Otherwise archive the print anew rather than drop it, so it still
  4501. # gets its notification, usage tracking and history.
  4502. logger.warning(
  4503. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4504. expected_archive_id,
  4505. printer_id,
  4506. )
  4507. # Check if there's already a "printing" archive for this printer/file
  4508. # This prevents duplicates when backend restarts during an active print
  4509. from backend.app.models.archive import PrintArchive
  4510. existing_archive: PrintArchive | None = None
  4511. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4512. # across a backend restart for the same print, so this is the most
  4513. # reliable way to reattach. Only a row still printing: a cancelled one
  4514. # has been through completion (usage, history, notifications) already,
  4515. # and reopening it would count the print twice.
  4516. if subtask_id:
  4517. by_id = await db.execute(
  4518. select(PrintArchive)
  4519. .where(PrintArchive.printer_id == printer_id)
  4520. .where(PrintArchive.subtask_id == subtask_id)
  4521. .where(PrintArchive.status == "printing")
  4522. .order_by(PrintArchive.created_at.desc())
  4523. .limit(1)
  4524. )
  4525. existing_archive = by_id.scalar_one_or_none()
  4526. # Fallback match: name-based lookup. Kept as-is for prints whose
  4527. # subtask_id is missing ("0" / local / non-cloud prints).
  4528. if existing_archive is None:
  4529. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4530. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4531. # A print started from the printer's screen names its file in full,
  4532. # so the forms above double its extension. The file itself is the
  4533. # one exact match, and nothing looser is added (#3009).
  4534. if _subtask_is_the_file(subtask_name, filename):
  4535. archive_filenames.append(subtask_name)
  4536. existing = await db.execute(
  4537. select(PrintArchive)
  4538. .where(PrintArchive.printer_id == printer_id)
  4539. .where(PrintArchive.status == "printing")
  4540. .where(
  4541. or_(
  4542. PrintArchive.print_name == check_name,
  4543. PrintArchive.filename.in_(archive_filenames),
  4544. )
  4545. )
  4546. .order_by(PrintArchive.created_at.desc())
  4547. .limit(1)
  4548. )
  4549. existing_archive = existing.scalar_one_or_none()
  4550. if existing_archive:
  4551. # subtask_id match → always resume, regardless of age. Same print,
  4552. # just a backend restart.
  4553. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4554. if subtask_match:
  4555. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4556. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4557. _mark_owned_if_dispatched(existing_archive)
  4558. if existing_archive.energy_start_kwh is None:
  4559. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4560. if not notification_sent:
  4561. archive_data = {
  4562. "print_time_seconds": existing_archive.print_time_seconds,
  4563. "created_by_id": existing_archive.created_by_id,
  4564. }
  4565. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4566. _load_objects_from_archive(existing_archive, printer_id, logger)
  4567. return
  4568. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4569. # stale from the printer's *current* progress, not wall-clock age.
  4570. # A genuinely long print used to trip a blind 4h cutoff and have its
  4571. # live archive cancelled + duplicated on every backend restart
  4572. # (#1485). If the printer reports real progress, this name-matched
  4573. # 'printing' archive IS that ongoing print — resume it whatever its
  4574. # age. Only treat it as a stale leftover when the printer clearly
  4575. # shows a different, freshly-started print: near-0% progress on an
  4576. # archive far too old to still be at 0%. Unknown progress (printer
  4577. # not connected) never cancels — resuming is the safe default.
  4578. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4579. live_status = printer_manager.get_status(printer_id)
  4580. live_progress = getattr(live_status, "progress", None) if live_status else None
  4581. looks_stale = (
  4582. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4583. )
  4584. # Two subtask ids are two prints, however young the archive: one
  4585. # whose completion was missed must not swallow the next print of
  4586. # the same file. Except Bambuddy's own reprint, which reuses the
  4587. # row and mints a fresh id (#1807): the id it last sent says so,
  4588. # and after a restart, which forgets it, this printer's queue job
  4589. # running the archive.
  4590. if (
  4591. not looks_stale
  4592. and subtask_id
  4593. and existing_archive.subtask_id
  4594. and existing_archive.subtask_id != subtask_id
  4595. ):
  4596. _client = printer_manager.get_client(printer_id)
  4597. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4598. if _dispatched:
  4599. looks_stale = _dispatched != subtask_id
  4600. else:
  4601. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4602. queue_run = await db.scalar(
  4603. select(_PQI.id)
  4604. .where(_PQI.archive_id == existing_archive.id)
  4605. .where(_PQI.printer_id == printer_id)
  4606. .where(_PQI.status == "printing")
  4607. .limit(1)
  4608. )
  4609. looks_stale = queue_run is None
  4610. if looks_stale:
  4611. logger.warning(
  4612. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4613. " — marking cancelled and creating new archive",
  4614. existing_archive.id,
  4615. archive_age,
  4616. live_progress,
  4617. existing_archive.subtask_id,
  4618. subtask_id,
  4619. )
  4620. existing_archive.status = "cancelled"
  4621. # Canonical key, not a sentence (issue #2974). "No status update
  4622. # received" is what both stale paths actually observed; which of
  4623. # the two it was is already carried by ``status`` -- cancelled
  4624. # here, the reconciled outcome at the reconnect site -- so one
  4625. # key loses no information and gives the Statistics breakdown a
  4626. # single bucket instead of two untranslatable prose strings.
  4627. existing_archive.failure_reason = "noStatusUpdate"
  4628. await db.commit()
  4629. # Its print keys go with it; the new archive registers its own.
  4630. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4631. del _active_prints[_key]
  4632. # Fall through to create new archive (don't return)
  4633. else:
  4634. logger.info(
  4635. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4636. )
  4637. # Track this as the active print
  4638. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4639. _mark_owned_if_dispatched(existing_archive)
  4640. # Attach subtask_id retroactively so future restarts can resume.
  4641. # Compare for inequality (not "is empty") to also pick up reprint
  4642. # dispatches that mint a fresh id — see #1807 for the bogus
  4643. # "Print Stopped" the strict-empty guard caused on reconnect.
  4644. if subtask_id and existing_archive.subtask_id != subtask_id:
  4645. existing_archive.subtask_id = subtask_id
  4646. await db.commit()
  4647. # Also set up energy tracking if not already tracked (#941: persisted column)
  4648. if existing_archive.energy_start_kwh is None:
  4649. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4650. # Send notification with archive data (existing archive)
  4651. if not notification_sent:
  4652. archive_data = {
  4653. "print_time_seconds": existing_archive.print_time_seconds,
  4654. "created_by_id": existing_archive.created_by_id,
  4655. }
  4656. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4657. # Extract printable objects from the archived 3MF file
  4658. _load_objects_from_archive(existing_archive, printer_id, logger)
  4659. return
  4660. # Build list of possible 3MF filenames to try
  4661. possible_names = []
  4662. # Bambu printers typically store files as "Name.gcode.3mf"
  4663. # The subtask_name is usually the best source for the filename
  4664. if subtask_name:
  4665. if _subtask_is_the_file(subtask_name, filename):
  4666. # A print started from the printer's own screen reports the
  4667. # file's full name, extension included. That is the file, so
  4668. # no extension is appended to it (#3009).
  4669. possible_names.append(subtask_name)
  4670. else:
  4671. # Try common Bambu naming patterns
  4672. possible_names.append(f"{subtask_name}.gcode.3mf")
  4673. possible_names.append(f"{subtask_name}.3mf")
  4674. # Try original filename with .3mf extension
  4675. if filename:
  4676. # Extract just the filename part, not the full path
  4677. fname = filename.split("/")[-1] if "/" in filename else filename
  4678. if fname.endswith(".3mf"):
  4679. possible_names.append(fname)
  4680. elif fname.endswith(".gcode"):
  4681. base = fname.rsplit(".", 1)[0]
  4682. possible_names.append(f"{base}.gcode.3mf")
  4683. possible_names.append(f"{base}.3mf")
  4684. else:
  4685. possible_names.append(f"{fname}.gcode.3mf")
  4686. possible_names.append(f"{fname}.3mf")
  4687. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4688. space_variants = []
  4689. for name in possible_names:
  4690. if " " in name:
  4691. space_variants.append(name.replace(" ", "_"))
  4692. possible_names.extend(space_variants)
  4693. # Remove duplicates while preserving order
  4694. seen = set()
  4695. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4696. logger.info("Trying filenames: %s", possible_names)
  4697. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4698. # here means none of the expected-/existing-archive write branches ran
  4699. # (they all return earlier) — only SELECTs have executed on this path, so
  4700. # this commit persists nothing; it ends the read transaction so the
  4701. # connection returns to the pool during the download. That download tries
  4702. # up to five remote paths per candidate filename with retry/backoff and
  4703. # can run for minutes under FTP contention; holding the session across it
  4704. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4705. # work runs during the download — the new-archive writes below re-acquire
  4706. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4707. await db.commit()
  4708. # Try to find and download the 3MF file
  4709. temp_path = None
  4710. downloaded_filename = None
  4711. # Cache check: cover endpoint may have already pulled this 3MF during
  4712. # the print (frontend opens the card and shows the thumbnail) — reuse
  4713. # that file instead of re-downloading 36MB over the same FTP link that
  4714. # just served it (#972). The cache keys on a normalized filename so
  4715. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4716. for try_filename in possible_names:
  4717. if not try_filename.endswith(".3mf"):
  4718. continue
  4719. cached = get_cached_3mf(printer_id, try_filename)
  4720. if cached:
  4721. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4722. temp_path = cached
  4723. downloaded_filename = try_filename
  4724. break
  4725. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4726. # H2-series and P2S the answer is routinely no — the file stays on
  4727. # internal eMMC and port 990 only ever serves external storage — and
  4728. # then the whole sweep below (six filenames x five directories x four
  4729. # retries, then the directory walk) is ~110 connections that cannot
  4730. # succeed. Skip it and say why (#2780).
  4731. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4732. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4733. # running rather than because the file is somewhere unreachable. The
  4734. # distinction is the whole of #2957: one is permanent, the other clears
  4735. # in minutes with the file still sitting on the printer.
  4736. blocked_by_ftps_cooloff = False
  4737. # Set when a probe reached the printer and still came back without the
  4738. # file -- a timeout mid-transfer, a refused connection, anything that is
  4739. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4740. # caught by name below, so a file that genuinely is not on the card
  4741. # leaves this False and schedules nothing. Anything else means the
  4742. # transfer, not the file, is what failed, and that does not last (#3063).
  4743. ftp_transfer_failed = False
  4744. # The print's name, for a fallback archive whose `subtask_name` the
  4745. # plate guard below had to disown. Display only, and deliberately kept
  4746. # apart from `subtask_name`: that variable is what every file lookup
  4747. # here is built from, and once a name has been shown to fetch another
  4748. # plate's 3MF it must not key `_active_prints` either, or the cover
  4749. # endpoint hands the same contradicted file to
  4750. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4751. display_name_after_plate_reject: str | None = None
  4752. # Get FTP retry settings
  4753. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4754. # ...but "the printer put it on eMMC" is where it went, not whether we
  4755. # can read it. An H2D with a card in mirrors the job to /cache and
  4756. # serves it happily, and skipping on the URL alone cost that reporter
  4757. # every archive for two days (#2856). So ask the printer instead of
  4758. # guessing: the dispatch named the exact file, which is one connection
  4759. # walking five paths rather than the sweep's ~110. Only when the probe
  4760. # comes back empty does the verdict's reason stand.
  4761. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4762. if ftps_handshake_blocked(printer.ip_address):
  4763. # Deliberately NOT recorded as a cool-off give-up. This branch
  4764. # only runs on an unreachable verdict, and that verdict is the
  4765. # honest, permanent reason the archive is empty — the probe was
  4766. # a long shot on top of it. Blaming the cool-off here would
  4767. # schedule a retry for a file sitting on internal eMMC, which is
  4768. # the sweep #2780 removed (#2957).
  4769. logger.debug(
  4770. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4771. storage.probe_filename,
  4772. printer_id,
  4773. )
  4774. else:
  4775. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4776. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4777. try:
  4778. probe_hit = await download_file_try_paths_async(
  4779. printer.ip_address,
  4780. printer.access_code,
  4781. ftp_probe_paths(storage.probe_filename),
  4782. probe_path,
  4783. socket_timeout=ftp_timeout,
  4784. printer_model=printer.model,
  4785. )
  4786. except Exception as e:
  4787. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4788. probe_hit = False
  4789. if probe_hit:
  4790. downloaded_filename = storage.probe_filename
  4791. temp_path = probe_path
  4792. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4793. # Naming the path, not just the file: a printer that keeps
  4794. # uploads around for weeks can serve a same-named copy of an
  4795. # earlier slice, and without the directory in the log that
  4796. # mismatch is invisible rather than merely rare (#1820).
  4797. logger.info(
  4798. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4799. downloaded_filename,
  4800. probe_hit,
  4801. printer_id,
  4802. storage.reason,
  4803. )
  4804. if not storage.reachable and not downloaded_filename:
  4805. # Same opening words whether or not a probe ran, because that is
  4806. # the phrase support asks people to grep for — only the tail says
  4807. # which of the two happened.
  4808. logger.info(
  4809. "Skipping the 3MF lookup for printer %s: %s — %s",
  4810. printer_id,
  4811. storage.reason,
  4812. "no copy of it on external storage either"
  4813. if storage.probe_filename
  4814. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4815. )
  4816. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4817. if not try_filename.endswith(".3mf"):
  4818. continue
  4819. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4820. # printers, so try it first — deferring it to last cost #972's reporter
  4821. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4822. # landing on the path that actually had the file.
  4823. remote_paths = [
  4824. f"/{try_filename}",
  4825. f"/cache/{try_filename}",
  4826. f"/model/{try_filename}",
  4827. f"/data/{try_filename}",
  4828. f"/data/Metadata/{try_filename}",
  4829. ]
  4830. temp_path = app_settings.archive_dir / "temp" / try_filename
  4831. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4832. for remote_path in remote_paths:
  4833. if ftps_handshake_blocked(printer.ip_address):
  4834. # The printer's FTPS service is not completing a TLS
  4835. # handshake, so it has no path we could reach — walking the
  4836. # remaining candidates only re-runs the same failure
  4837. # (#2780). Fall through to the no-3MF archive now.
  4838. #
  4839. # Remember *why*, though. This is the one give-up that is
  4840. # temporary: the cool-off clears in minutes and the file was
  4841. # on the printer the whole time. The fallback archive is
  4842. # stamped with it so a retry can be scheduled, and so the
  4843. # Archives banner stops blaming storage (#2957).
  4844. blocked_by_ftps_cooloff = True
  4845. logger.warning(
  4846. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4847. printer_id,
  4848. )
  4849. break
  4850. logger.debug("Trying FTP download: %s", remote_path)
  4851. try:
  4852. if ftp_retry_enabled:
  4853. downloaded = await with_ftp_retry(
  4854. download_file_async,
  4855. printer.ip_address,
  4856. printer.access_code,
  4857. remote_path,
  4858. temp_path,
  4859. timeout=ftp_timeout,
  4860. socket_timeout=ftp_timeout,
  4861. printer_model=printer.model,
  4862. max_retries=ftp_retry_count,
  4863. retry_delay=ftp_retry_delay,
  4864. operation_name=f"Download 3MF from {remote_path}",
  4865. cooloff_ip=printer.ip_address,
  4866. non_retry_exceptions=(FileNotOnPrinterError,),
  4867. )
  4868. else:
  4869. downloaded = await download_file_async(
  4870. printer.ip_address,
  4871. printer.access_code,
  4872. remote_path,
  4873. temp_path,
  4874. timeout=ftp_timeout,
  4875. socket_timeout=ftp_timeout,
  4876. printer_model=printer.model,
  4877. )
  4878. if downloaded:
  4879. downloaded_filename = try_filename
  4880. logger.info("Downloaded: %s", remote_path)
  4881. # Populate shared cache so the cover endpoint (if it
  4882. # runs next) doesn't refetch the same 36MB over FTP.
  4883. cache_3mf_download(printer_id, try_filename, temp_path)
  4884. break
  4885. # with_ftp_retry returns None once it has spent its budget,
  4886. # and download_file_async returns False on a timeout, so an
  4887. # exhausted transfer arrives here rather than as an
  4888. # exception (#3063).
  4889. ftp_transfer_failed = True
  4890. except FileNotOnPrinterError:
  4891. # 550 — file isn't at this path. Advance to next candidate
  4892. # without burning the retry budget.
  4893. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4894. except Exception as e:
  4895. ftp_transfer_failed = True
  4896. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4897. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4898. break
  4899. # If still not found, try listing directories to find matching file
  4900. # Different printer models use different directory structures. Skipped
  4901. # when the printer's FTPS handshake is failing — the directory walk is
  4902. # five more connections that cannot get further than the download did.
  4903. if (
  4904. not downloaded_filename
  4905. and storage.reachable
  4906. and (filename or subtask_name)
  4907. and not ftps_handshake_blocked(printer.ip_address)
  4908. ):
  4909. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4910. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4911. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4912. # Every folder is listed before one file is picked, so a file named
  4913. # for the print in a later folder wins over one that merely
  4914. # contains the name in an earlier folder.
  4915. listed_paths: list[str] = []
  4916. for search_dir in search_dirs:
  4917. try:
  4918. dir_files = await list_files_async(
  4919. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4920. )
  4921. except Exception as e:
  4922. logger.debug("Failed to list %s: %s", search_dir, e)
  4923. continue
  4924. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4925. if threemf_files:
  4926. logger.info(
  4927. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4928. )
  4929. listed_paths += [
  4930. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  4931. ]
  4932. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  4933. fname = posixpath.basename(remote_full_path)
  4934. logger.info("Found matching file: %s", remote_full_path)
  4935. temp_path = app_settings.archive_dir / "temp" / fname
  4936. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4937. try:
  4938. if ftp_retry_enabled:
  4939. downloaded = await with_ftp_retry(
  4940. download_file_async,
  4941. printer.ip_address,
  4942. printer.access_code,
  4943. remote_full_path,
  4944. temp_path,
  4945. timeout=ftp_timeout,
  4946. socket_timeout=ftp_timeout,
  4947. printer_model=printer.model,
  4948. max_retries=ftp_retry_count,
  4949. retry_delay=ftp_retry_delay,
  4950. operation_name=f"Download 3MF from {remote_full_path}",
  4951. cooloff_ip=printer.ip_address,
  4952. )
  4953. else:
  4954. downloaded = await download_file_async(
  4955. printer.ip_address,
  4956. printer.access_code,
  4957. remote_full_path,
  4958. temp_path,
  4959. timeout=ftp_timeout,
  4960. socket_timeout=ftp_timeout,
  4961. printer_model=printer.model,
  4962. )
  4963. except Exception as e:
  4964. logger.debug("Failed to download %s: %s", remote_full_path, e)
  4965. continue
  4966. if downloaded:
  4967. downloaded_filename = fname
  4968. logger.info("Found and downloaded: %s", remote_full_path)
  4969. cache_3mf_download(printer_id, fname, temp_path)
  4970. break
  4971. # The listing named the file, so it is on the card;
  4972. # only the transfer failed (#3063).
  4973. ftp_transfer_failed = True
  4974. # Validate the downloaded 3MF actually matches the plate that's running
  4975. # (#1204): subtask_name lags across consecutive plates of the same model,
  4976. # so the first FTP candidate (built from subtask_name) can land on the
  4977. # previous plate's still-resident upload. Cross-check the slice_info
  4978. # plate index against the plate parsed from gcode_file (always fresh —
  4979. # it's the field whose change triggered this callback).
  4980. if downloaded_filename and temp_path:
  4981. expected_plate = parse_plate_id(filename)
  4982. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4983. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4984. logger.warning(
  4985. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4986. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4987. downloaded_filename,
  4988. actual_plate,
  4989. expected_plate,
  4990. subtask_name,
  4991. )
  4992. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4993. retry_succeeded = False
  4994. if corrected_subtask and corrected_subtask != subtask_name:
  4995. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4996. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4997. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4998. for remote_path in (
  4999. f"/{try_filename}",
  5000. f"/cache/{try_filename}",
  5001. f"/model/{try_filename}",
  5002. f"/data/{try_filename}",
  5003. f"/data/Metadata/{try_filename}",
  5004. ):
  5005. try:
  5006. if ftp_retry_enabled:
  5007. downloaded = await with_ftp_retry(
  5008. download_file_async,
  5009. printer.ip_address,
  5010. printer.access_code,
  5011. remote_path,
  5012. retry_temp_path,
  5013. timeout=ftp_timeout,
  5014. socket_timeout=ftp_timeout,
  5015. printer_model=printer.model,
  5016. max_retries=ftp_retry_count,
  5017. retry_delay=ftp_retry_delay,
  5018. operation_name=f"Re-download 3MF from {remote_path}",
  5019. cooloff_ip=printer.ip_address,
  5020. non_retry_exceptions=(FileNotOnPrinterError,),
  5021. )
  5022. else:
  5023. downloaded = await download_file_async(
  5024. printer.ip_address,
  5025. printer.access_code,
  5026. remote_path,
  5027. retry_temp_path,
  5028. timeout=ftp_timeout,
  5029. socket_timeout=ftp_timeout,
  5030. printer_model=printer.model,
  5031. )
  5032. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5033. logger.info(
  5034. "[CALLBACK] Re-download succeeded with corrected name %s "
  5035. "(plate %s) — replacing wrong file",
  5036. try_filename,
  5037. expected_plate,
  5038. )
  5039. try:
  5040. temp_path.unlink(missing_ok=True)
  5041. except OSError:
  5042. pass
  5043. temp_path = retry_temp_path
  5044. downloaded_filename = try_filename
  5045. subtask_name = corrected_subtask
  5046. cache_3mf_download(printer_id, try_filename, temp_path)
  5047. retry_succeeded = True
  5048. break
  5049. elif downloaded:
  5050. # Wrong plate again — discard and keep trying
  5051. try:
  5052. retry_temp_path.unlink(missing_ok=True)
  5053. except OSError:
  5054. pass
  5055. except FileNotOnPrinterError:
  5056. continue
  5057. except Exception as e:
  5058. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5059. if retry_succeeded:
  5060. break
  5061. # If the retry didn't find a matching file, drop the wrong 3MF
  5062. # so the no-3MF fallback below creates an archive whose name
  5063. # at least reflects the right plate.
  5064. if not retry_succeeded:
  5065. logger.warning(
  5066. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5067. expected_plate,
  5068. )
  5069. try:
  5070. temp_path.unlink(missing_ok=True)
  5071. except OSError:
  5072. pass
  5073. temp_path = None
  5074. downloaded_filename = None
  5075. # Whatever the sweep's transport did earlier, it is not why
  5076. # this archive ends up empty: a 3MF downloaded fine, it was
  5077. # just the wrong plate. Retrying would re-fetch that same
  5078. # contradicted file under the same stale names and hand it
  5079. # to _recover_fallback_archive, which checks that a
  5080. # candidate is a readable 3MF but not which plate it is --
  5081. # so the row would be filled in with another plate's
  5082. # filament and cost, the exact swap #2957 removed (#3063).
  5083. ftp_transfer_failed = False
  5084. # Disown the name for *lookups*: it has just been shown to
  5085. # fetch another plate's 3MF, and it keys `_active_prints`
  5086. # below, where the cover endpoint's own download of that
  5087. # same name would find this archive and fill it in with the
  5088. # file we are discarding here.
  5089. #
  5090. # Keep it for the *title*, which is a separate question.
  5091. # ``swap_plate_suffix`` returns None both for a name that
  5092. # carries no "- Plate N" / "_plate_N" suffix and for no
  5093. # name at all, and those are not the same situation: a name
  5094. # without a suffix holds no stale plate number to be wrong
  5095. # about. Blanking both uses at once dropped the project
  5096. # name too, and the row fell through to the gcode_file path
  5097. # titled "plate_1" though the real name was in hand.
  5098. # #1204's own premise is consecutive plates *of the same
  5099. # model*, so the project part is right either way (#3126).
  5100. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5101. subtask_name = corrected_subtask or ""
  5102. # Deleted while the 3MF was being fetched (that can take minutes): no
  5103. # archive, timelapse or tracking for a printer that will never report
  5104. # the print's end. forget_printer again: the download registered its
  5105. # 3MF cache entry after the delete cleared the id. (A delete committing
  5106. # while the archive is written is caught after its commit.)
  5107. if await _printer_gone(db, printer_id):
  5108. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5109. await forget_printer(printer_id)
  5110. return
  5111. if not downloaded_filename or not temp_path:
  5112. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5113. # Create a fallback archive without 3MF data so the print is still tracked
  5114. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5115. try:
  5116. from backend.app.models.archive import PrintArchive
  5117. # Why the card is empty. The two temporary causes outrank the
  5118. # storage verdict because they say the sweep never got a fair
  5119. # answer: a cool-off skipped it at the transport, and a failed
  5120. # transfer reached the printer but never finished. Either way
  5121. # the file is still on the card, so reporting where the printer
  5122. # files its jobs would describe a setting that is not the
  5123. # problem (#2957, #3063).
  5124. if blocked_by_ftps_cooloff:
  5125. no_3mf_reason = REASON_FTPS_COOLOFF
  5126. elif storage.reachable and ftp_transfer_failed:
  5127. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5128. else:
  5129. no_3mf_reason = storage.reason
  5130. # Derive print name from subtask_name or filename. The
  5131. # plate guard's disowned name comes second: it is a real name
  5132. # for a real print, and only the gcode_file path is left
  5133. # otherwise -- which titles the row "plate_1" (#3126).
  5134. print_name = subtask_name or display_name_after_plate_reject or filename
  5135. if print_name:
  5136. # Clean up the name (remove extensions, path parts)
  5137. print_name = print_name.split("/")[-1]
  5138. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5139. else:
  5140. print_name = "Unknown Print"
  5141. # Recover estimated print time from MQTT (best-effort for notifications)
  5142. fallback_print_time = None
  5143. mqtt_remaining = data.get("remaining_time")
  5144. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5145. fallback_print_time = int(mqtt_remaining)
  5146. if fallback_print_time is None:
  5147. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5148. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5149. fallback_print_time = int(mc_remaining * 60)
  5150. # Best-effort filament metadata from MQTT — see
  5151. # _extract_filament_data_from_mqtt. Without this the fallback
  5152. # archive's filament fields stayed NULL even though the AMS
  5153. # state at print start was sitting right there in `data`.
  5154. # The slicer's ams_mapping (when present) narrows the result
  5155. # to slots actually used by the print (#1533).
  5156. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5157. # Create minimal archive entry
  5158. fallback_archive = PrintArchive(
  5159. printer_id=printer_id,
  5160. filename=filename or f"{print_name}.3mf",
  5161. file_path="", # Empty - no 3MF file available
  5162. file_size=0,
  5163. print_name=print_name,
  5164. print_time_seconds=fallback_print_time,
  5165. status="printing",
  5166. started_at=datetime.now(timezone.utc),
  5167. subtask_id=subtask_id,
  5168. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5169. filament_type=mqtt_filament_meta.get("filament_type"),
  5170. filament_color=mqtt_filament_meta.get("filament_color"),
  5171. extra_data={
  5172. "no_3mf_available": True,
  5173. # Why the card is empty, when we know -- see above. The
  5174. # banner reads this to stop telling H2/P2 owners to
  5175. # switch on a setting that is already on and would not
  5176. # have helped (#2780).
  5177. "no_3mf_reason": no_3mf_reason,
  5178. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5179. "_print_data": data,
  5180. },
  5181. )
  5182. db.add(fallback_archive)
  5183. try:
  5184. await db.commit()
  5185. except IntegrityError:
  5186. # Not "Failed to create fallback archive" below, and no
  5187. # start notification for a printer that is gone.
  5188. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5189. return
  5190. raise
  5191. await db.refresh(fallback_archive)
  5192. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5193. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5194. return
  5195. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5196. # Track as active print
  5197. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5198. # Record starting energy if smart plug available (#941: persisted column)
  5199. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5200. # Send WebSocket notification
  5201. await ws_manager.send_archive_created(
  5202. {
  5203. "id": fallback_archive.id,
  5204. "printer_id": fallback_archive.printer_id,
  5205. "filename": fallback_archive.filename,
  5206. "print_name": fallback_archive.print_name,
  5207. "status": fallback_archive.status,
  5208. }
  5209. )
  5210. # MQTT relay - publish archive created
  5211. try:
  5212. await mqtt_relay.on_archive_created(
  5213. archive_id=fallback_archive.id,
  5214. print_name=fallback_archive.print_name,
  5215. printer_name=printer.name,
  5216. status=fallback_archive.status,
  5217. )
  5218. except Exception:
  5219. pass # Don't fail if MQTT fails
  5220. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5221. try:
  5222. await _store_spoolman_print_data(
  5223. printer_id,
  5224. fallback_archive.id,
  5225. fallback_archive.file_path,
  5226. db,
  5227. printer_manager,
  5228. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5229. plate_id=_get_start_plate_id(fallback_archive.id),
  5230. )
  5231. except Exception as e:
  5232. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5233. # Both temporary give-ups are worth coming back for, and for
  5234. # the same reason: the file is on the printer and the last look
  5235. # failed at the transport rather than finding nothing. One waits
  5236. # out the handshake block (#2957), the other waits for the
  5237. # printer to stop being busy (#3063). Deliberately not scheduled
  5238. # for a storage verdict: a file on internal eMMC will not appear
  5239. # at any FTPS path however long we wait, and retrying it is
  5240. # exactly the sweep #2780 removed.
  5241. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5242. # `possible_names`, not the raw MQTT strings: it is the exact
  5243. # list this flow just tried, already stripped of any path
  5244. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5245. # some firmware) and deduped.
  5246. _schedule_fallback_3mf_retry(
  5247. printer_id=printer_id,
  5248. archive_id=fallback_archive.id,
  5249. filenames=list(possible_names),
  5250. reason=no_3mf_reason,
  5251. )
  5252. # Send notification without archive data (file not found)
  5253. if not notification_sent:
  5254. await _send_print_start_notification(printer_id, data, logger=logger)
  5255. # The same baseline the other two on_print_start branches take
  5256. # (#2704), and last for the same reason they are: it lists the
  5257. # printer's timelapse directory, so a slow card must not delay
  5258. # the _active_prints registration, the energy reading, the
  5259. # archive-created event or the start notification above it.
  5260. #
  5261. # This branch never took one, so every no-3MF archive reached
  5262. # completion with no baseline in memory and none on the row, and
  5263. # the completion scan fell into its "snapshot now" fallback --
  5264. # which runs after the printer has written the video, so the new
  5265. # file landed inside the baseline and no diff ever matched
  5266. # (#2957 follow-up).
  5267. #
  5268. # Skipped when the FTPS cool-off is what produced this fallback:
  5269. # the listing needs the same connection that just failed, so it
  5270. # could only record that the card was unreadable. The scan
  5271. # handles that case by refusing to choose between candidates.
  5272. if not blocked_by_ftps_cooloff:
  5273. await _capture_timelapse_baseline_at_start(
  5274. printer, printer_id, logger, archive_id=fallback_archive.id
  5275. )
  5276. await _forget_if_printer_gone(printer_id)
  5277. return
  5278. except Exception as e:
  5279. logger.error("Failed to create fallback archive: %s", e)
  5280. # Send notification without archive data (file not found)
  5281. if not notification_sent:
  5282. await _send_print_start_notification(printer_id, data, logger=logger)
  5283. return
  5284. try:
  5285. # Archive the file with status "printing"
  5286. service = ArchiveService(db)
  5287. try:
  5288. archive = await service.archive_print(
  5289. printer_id=printer_id,
  5290. source_file=temp_path,
  5291. print_data={**data, "status": "printing"},
  5292. subtask_id=subtask_id,
  5293. )
  5294. except IntegrityError:
  5295. # archive_print removed the folder it had copied the 3MF into.
  5296. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5297. return
  5298. raise
  5299. if archive:
  5300. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5301. # Set on the row rather than passed to archive_print, which also
  5302. # serves the queue dispatcher — there the queue item decides.
  5303. # Guarded because this branch has no ``except``: an unhandled
  5304. # write error would take the _active_prints registration, the
  5305. # start notification, the energy reading and the timelapse
  5306. # baseline below it with it, and a missing prompt is by far the
  5307. # cheaper failure.
  5308. archive_id = archive.id
  5309. try:
  5310. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5311. archive.confirm_requested = True
  5312. await db.commit()
  5313. except Exception as e:
  5314. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5315. # The rollback expires every loaded object, and on an async
  5316. # session reading one afterwards raises instead of
  5317. # reloading, so the two this branch goes on to use are
  5318. # fetched again. The archive itself was committed by
  5319. # archive_print; only the flag is lost.
  5320. try:
  5321. await db.rollback()
  5322. archive = await db.get(PrintArchive, archive_id)
  5323. printer = await db.get(Printer, printer_id)
  5324. except Exception as reload_error:
  5325. logger.warning(
  5326. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5327. )
  5328. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5329. return
  5330. # Track this active print (use both original filename and downloaded filename)
  5331. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5332. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5333. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5334. # Record starting energy from smart plug if available (#941: persisted column)
  5335. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5336. await ws_manager.send_archive_created(
  5337. {
  5338. "id": archive.id,
  5339. "printer_id": archive.printer_id,
  5340. "filename": archive.filename,
  5341. "print_name": archive.print_name,
  5342. "status": archive.status,
  5343. }
  5344. )
  5345. # MQTT relay - publish archive created
  5346. try:
  5347. await mqtt_relay.on_archive_created(
  5348. archive_id=archive.id,
  5349. print_name=archive.print_name,
  5350. printer_name=printer.name,
  5351. status=archive.status,
  5352. )
  5353. except Exception:
  5354. pass # Don't fail if MQTT fails
  5355. # Send notification with archive data (new archive created)
  5356. if not notification_sent:
  5357. archive_data = {
  5358. "print_time_seconds": archive.print_time_seconds,
  5359. "created_by_id": archive.created_by_id,
  5360. }
  5361. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5362. # Extract printable objects for skip object functionality
  5363. try:
  5364. from backend.app.services.archive import extract_printable_objects_from_3mf
  5365. client = printer_manager.get_client(printer_id)
  5366. if client:
  5367. with open(temp_path, "rb") as f:
  5368. threemf_data = f.read()
  5369. # Extract with positions for UI overlay, scoped to the
  5370. # plate that is printing — an all-plates 3MF carries
  5371. # every plate's objects (#2522).
  5372. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5373. threemf_data,
  5374. plate_number=resolve_plate_id(client.state),
  5375. include_positions=True,
  5376. )
  5377. if printable_objects:
  5378. # Store objects in printer state
  5379. client.state.printable_objects = printable_objects
  5380. client.state.printable_objects_bbox_all = bbox_all
  5381. client.state.skipped_objects = [] # Reset skipped objects for new print
  5382. logger.info(
  5383. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5384. )
  5385. except Exception as e:
  5386. logger.debug("Failed to extract printable objects: %s", e)
  5387. # Store Spoolman tracking data for per-filament usage reporting
  5388. try:
  5389. await _store_spoolman_print_data(
  5390. printer_id,
  5391. archive.id,
  5392. archive.file_path,
  5393. db,
  5394. printer_manager,
  5395. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5396. plate_id=_get_start_plate_id(archive.id),
  5397. )
  5398. except Exception as e:
  5399. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5400. # Price the print from its spools now rather than only at completion (#3261)
  5401. _schedule_archive_cost_estimate(
  5402. printer_id,
  5403. archive.id,
  5404. printer_manager,
  5405. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5406. plate_id=_get_start_plate_id(archive.id),
  5407. session_factory=async_session,
  5408. )
  5409. # Capture timelapse file baseline for snapshot-diff on completion
  5410. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5411. await _forget_if_printer_gone(printer_id)
  5412. finally:
  5413. # Keep temp_path around until print completes so the cover endpoint
  5414. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5415. # the file. If the cache entry was evicted early (file vanished),
  5416. # clean up any stragglers here to avoid leaking disk on retries.
  5417. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5418. if temp_path and temp_path.exists() and cached_now != temp_path:
  5419. temp_path.unlink()
  5420. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5421. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5422. # tests can shrink them without waiting out real delays.
  5423. #
  5424. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5425. # looking. Across 247 support bundles the attempt that found the video was #1
  5426. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5427. # decaying one, which is the signature of a budget that expires while files are
  5428. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5429. # prints make big videos and the printer writes them after the print ends, so
  5430. # the poll now runs for minutes and costs one FTP LIST per round.
  5431. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5432. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5433. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5434. def _timelapse_scan_max_attempts() -> int:
  5435. """Round cap for the poll, derived from the wall-clock budget.
  5436. The deadline alone is not a sufficient bound: it assumes each round really
  5437. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5438. and an FTP list that fails immediately would otherwise spin against the
  5439. printer at full speed for the whole window. Whichever bound is reached
  5440. first ends the poll.
  5441. """
  5442. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5443. # A zero interval makes the wall-clock budget meaningless; fall back to
  5444. # the round count the production interval would have given.
  5445. return 32
  5446. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5447. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5448. """Video filenames already attached to some other archive of this printer.
  5449. Used to disambiguate when more than one file is new since the baseline —
  5450. which happens when a previous print's video landed after this print's
  5451. baseline was taken. Ordering the candidates would be the obvious fix and is
  5452. the wrong one: it can only be done on mtime or on the filename timestamp,
  5453. both of which come from the printer's own clock, and a LAN-only printer
  5454. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5455. ``attach_timelapse`` saves the video into the archive directory under the
  5456. printer's original filename, and the later MP4 conversion keeps the stem,
  5457. so the stem of ``timelapse_path`` recovers what was claimed.
  5458. """
  5459. from backend.app.models.archive import PrintArchive
  5460. rows = await db.execute(
  5461. select(PrintArchive.timelapse_path).where(
  5462. PrintArchive.printer_id == printer_id,
  5463. PrintArchive.id != exclude_archive_id,
  5464. PrintArchive.timelapse_path.is_not(None),
  5465. )
  5466. )
  5467. return {Path(p).stem for p in rows.scalars().all() if p}
  5468. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5469. """Whether an *empty* timelapse listing for *printer* can be believed.
  5470. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5471. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5472. from one holding no videos. Everywhere that only wants to know "is there a
  5473. video yet" the difference does not matter — both mean "not yet, retry".
  5474. It matters where an empty listing is recorded as a *baseline*. Recording
  5475. "the card held nothing" for a card that was never read means every video on
  5476. it counts as new once the cool-off expires, and the completion scan then
  5477. attaches a stale video to this print and deletes it from the printer
  5478. (#2957 follow-up). Those two callers ask this first.
  5479. """
  5480. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5481. ip_address = getattr(printer, "ip_address", None)
  5482. if not ip_address:
  5483. return True
  5484. return not ftps_handshake_blocked(ip_address)
  5485. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5486. """List video files from printer's timelapse directory.
  5487. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5488. Returns (video_files, found_path) where video_files is a list of file dicts
  5489. and found_path is the directory where they were found, or ([], None).
  5490. An empty return does not distinguish "no videos" from "could not read the
  5491. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5492. baseline callers consult before believing one.
  5493. """
  5494. from backend.app.services.bambu_ftp import list_files_async
  5495. logger = logging.getLogger(__name__)
  5496. # No card in the slot means no /timelapse to walk — four connections that
  5497. # can only fail, on a path whose failures are swallowed and so would go on
  5498. # costing time silently forever (#2780).
  5499. #
  5500. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5501. # inside the loop's own try/except, so a caller that passed something
  5502. # unexpected used to get an empty listing rather than an exception. Keep
  5503. # that, instead of making this gate the first thing that can raise here.
  5504. printer_id = getattr(printer, "id", None)
  5505. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5506. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5507. return [], None
  5508. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5509. try:
  5510. found_files = await list_files_async(
  5511. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5512. )
  5513. if found_files:
  5514. video_files = [
  5515. f
  5516. for f in found_files
  5517. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5518. ]
  5519. if video_files:
  5520. return video_files, timelapse_path
  5521. except Exception as e:
  5522. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5523. continue
  5524. return [], None
  5525. async def _capture_timelapse_baseline_at_start(
  5526. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5527. ) -> None:
  5528. """Snapshot the printer's timelapse directory at print start so the
  5529. completion-time scan can pick the new file by set-difference.
  5530. Must be called from every on_print_start path that proceeds to a real
  5531. print — both the new-archive branch and the expected-archive branch (which
  5532. queue / VP-dispatched prints take). Without a baseline,
  5533. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5534. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5535. so the new file ends up in the "baseline" set and no diff ever matches.
  5536. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5537. unreliable — the snapshot-diff approach sidesteps that entirely.
  5538. When ``archive_id`` is known the baseline is also written to the archive
  5539. row, so it survives a restart and the manual "Scan for Timelapse" button
  5540. can run the same diff instead of falling back to clock-based matching
  5541. (#2704). Only baselines taken at print start are persisted — one taken at
  5542. completion already contains the new video and would poison a later scan.
  5543. """
  5544. names: set[str] | None = None
  5545. try:
  5546. if not _timelapse_listing_is_trustworthy(printer):
  5547. # Recorded anyway, deliberately. An empty baseline taken off a card
  5548. # we could not read is not authoritative, but it is still the right
  5549. # *default*: Bambuddy deletes each video from the printer once it is
  5550. # attached, so the usual card holds exactly one video at completion
  5551. # and an empty baseline resolves it correctly. Persisting NULL
  5552. # instead would send completion to take its own snapshot, by which
  5553. # point this print's video is on the card and would be swallowed by
  5554. # it. The ambiguity is handled where it actually bites — see
  5555. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5556. logger.warning(
  5557. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5558. "handshake cool-off, so the card could not be read — treating it as empty",
  5559. printer_id,
  5560. )
  5561. baseline_files, _ = await _list_timelapse_videos(printer)
  5562. names = {f.get("name", "") for f in baseline_files}
  5563. _timelapse_baselines[printer_id] = names
  5564. logger.info(
  5565. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5566. len(names),
  5567. printer_id,
  5568. )
  5569. except Exception as e:
  5570. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5571. if archive_id is None:
  5572. return
  5573. try:
  5574. async with async_session() as db:
  5575. from backend.app.models.archive import PrintArchive
  5576. archive = await db.get(PrintArchive, archive_id)
  5577. if archive is not None:
  5578. # Written even when the listing failed, and then as NULL. A
  5579. # reprint reuses the archive row, so leaving the previous run's
  5580. # baseline in place would have the scan diff this print against
  5581. # the state of the printer before the *last* one — and a stale
  5582. # baseline reads as authoritative, where NULL correctly falls
  5583. # back to a fresh snapshot.
  5584. archive.timelapse_baseline = sorted(names) if names is not None else None
  5585. await db.commit()
  5586. except Exception as e:
  5587. # In-memory baseline still covers the normal completion path.
  5588. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5589. async def _scan_for_timelapse_with_retries(
  5590. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5591. ):
  5592. """Poll the printer for this print's timelapse and attach it.
  5593. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5594. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5595. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5596. (#2704). Comparing the current listing against the set of filenames that
  5597. existed when the print started needs no clock at all, because the printer
  5598. writes the video only once the print has ended.
  5599. Baseline precedence: the caller's in-memory set, then the one persisted on
  5600. the archive at print start, then a snapshot taken now. The last of those is
  5601. a poor substitute — by completion the new video may already be on the card,
  5602. in which case it lands in the "baseline" and no diff can ever match — but it
  5603. is all that is available for a print that began before Bambuddy started.
  5604. On success the video is deleted from the printer, which keeps ``/timelapse``
  5605. down to the unclaimed files and makes the next diff unambiguous.
  5606. """
  5607. logger = logging.getLogger(__name__)
  5608. # Cleared when the baseline had to be taken off a card we could not read, so
  5609. # the attach step refuses to choose between several candidates (#2957).
  5610. baseline_trusted = True
  5611. # --- Phase 1: establish the baseline -------------------------------------
  5612. try:
  5613. async with async_session() as db:
  5614. from backend.app.models.printer import Printer
  5615. service = ArchiveService(db)
  5616. archive = await service.get_archive(archive_id)
  5617. if not archive:
  5618. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5619. return
  5620. if archive.timelapse_path:
  5621. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5622. return
  5623. if not archive.printer_id:
  5624. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5625. return
  5626. # The run this scan is for. The archive row passes to a newer run
  5627. # when it prints again (the next plate, a reprint), and that run's
  5628. # video is its own.
  5629. run_started_at = archive.started_at
  5630. if baseline_names is not None:
  5631. logger.info(
  5632. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5633. len(baseline_names),
  5634. archive_id,
  5635. )
  5636. elif archive.timelapse_baseline is not None:
  5637. # Persisted at print start — survives a restart mid-print.
  5638. baseline_names = set(archive.timelapse_baseline)
  5639. logger.info(
  5640. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5641. len(baseline_names),
  5642. archive_id,
  5643. )
  5644. else:
  5645. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5646. printer = result.scalar_one_or_none()
  5647. if not printer:
  5648. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5649. return
  5650. if not _timelapse_listing_is_trustworthy(printer):
  5651. # The card is unreadable at the one moment a baseline has to
  5652. # be taken, so the empty listing below means "we never
  5653. # looked", not "these are all new". Carry on with it anyway
  5654. # — the usual card holds exactly one video, which resolves
  5655. # correctly — but stop the poll from *choosing* between
  5656. # several, which is how a stale video got attached to this
  5657. # print and then deleted off the printer (#2957 follow-up).
  5658. baseline_trusted = False
  5659. logger.warning(
  5660. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5661. "handshake cool-off. A single new video still resolves; several will not be "
  5662. "guessed between — use Scan for Timelapse to pick one by hand",
  5663. archive_id,
  5664. archive.printer_id,
  5665. )
  5666. baseline_files, _ = await _list_timelapse_videos(printer)
  5667. baseline_names = {f.get("name", "") for f in baseline_files}
  5668. logger.info(
  5669. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5670. len(baseline_names),
  5671. archive_id,
  5672. )
  5673. except Exception as e:
  5674. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5675. return
  5676. # --- Phase 2: poll for a file that was not there when the print began -----
  5677. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5678. max_attempts = _timelapse_scan_max_attempts()
  5679. seen_names: set[str] = set()
  5680. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5681. attempt = 0
  5682. while True:
  5683. await asyncio.sleep(delay)
  5684. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5685. attempt += 1
  5686. try:
  5687. from backend.app.models.printer import Printer
  5688. # Read phase: fetch archive + printer in a short session and release
  5689. # the pooled connection BEFORE the FTP list/download below. Holding it
  5690. # across the FTP round-trips left one connection idle-in-transaction per
  5691. # in-flight scan (issue #2572).
  5692. async with async_session() as db:
  5693. service = ArchiveService(db)
  5694. archive = await service.get_archive(archive_id)
  5695. if not archive:
  5696. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5697. return
  5698. if archive.timelapse_path:
  5699. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5700. return
  5701. if archive.started_at != run_started_at:
  5702. logger.info(
  5703. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  5704. )
  5705. return
  5706. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5707. printer = result.scalar_one_or_none()
  5708. if not printer:
  5709. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5710. return
  5711. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5712. # I/O phase (no DB connection held): FTP list + download.
  5713. video_files, found_path = await _list_timelapse_videos(printer)
  5714. # The poll can run for dozens of rounds, so only narrate a round
  5715. # that saw something change. Repeating the whole listing every 30 s
  5716. # would bury the one interesting line in the support bundle.
  5717. names_now = {f.get("name", "") for f in video_files}
  5718. changed = attempt == 1 or names_now != seen_names
  5719. seen_names = names_now
  5720. speak = logger.info if changed else logger.debug
  5721. if video_files:
  5722. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5723. if changed:
  5724. for f in video_files[:5]:
  5725. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5726. attached = await _attach_first_unclaimed_timelapse(
  5727. archive_id,
  5728. printer,
  5729. video_files,
  5730. baseline_names,
  5731. claimed,
  5732. attempt,
  5733. logger,
  5734. quiet=not changed,
  5735. require_unambiguous=not baseline_trusted,
  5736. plate_id=plate_id,
  5737. run_started_at=run_started_at,
  5738. )
  5739. if attached:
  5740. return
  5741. else:
  5742. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5743. except Exception as e:
  5744. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5745. if attempt >= max_attempts or time.monotonic() >= deadline:
  5746. break
  5747. # No name-match fallback: it compared the print name against the filename,
  5748. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5749. # bundles it fired 159 times and matched zero times, so all it added was a
  5750. # misleading log line before giving up.
  5751. logger.warning(
  5752. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5753. archive_id,
  5754. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5755. )
  5756. async def _attach_layer_timelapse(
  5757. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  5758. ) -> None:
  5759. """Attach the external camera's stitched timelapse to the archive.
  5760. The camera's video is the one the user set up in Bambuddy, so it wins
  5761. over the printer's own when both are on: it replaces the printer's video
  5762. (usually there first; stitching takes minutes) and that file is deleted,
  5763. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  5764. the run the frames were taken for: when the archive is printing again by
  5765. the time the stitch is done, the video is not the new run's and is
  5766. dropped. The stitched file is a temporary either way.
  5767. """
  5768. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  5769. logger = logging.getLogger(__name__)
  5770. try:
  5771. async with async_session() as db:
  5772. service = ArchiveService(db)
  5773. archive = await service.get_archive(archive_id)
  5774. if archive is None:
  5775. return
  5776. if archive.started_at != run_started_at:
  5777. logger.info(
  5778. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  5779. )
  5780. return
  5781. replaced = archive.timelapse_path
  5782. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  5783. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  5784. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  5785. return
  5786. attached = archive.timelapse_path
  5787. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  5788. if replaced and replaced != attached:
  5789. try:
  5790. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  5791. except PathTraversalError:
  5792. return
  5793. await asyncio.to_thread(old.unlink, missing_ok=True)
  5794. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  5795. finally:
  5796. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  5797. # ``run_started_at`` not given: attach whichever run the archive is on.
  5798. _ANY_RUN = object()
  5799. async def _attach_first_unclaimed_timelapse(
  5800. archive_id: int,
  5801. printer,
  5802. video_files: list[dict],
  5803. baseline_names: set[str],
  5804. claimed: set[str],
  5805. attempt: int,
  5806. logger: logging.Logger,
  5807. *,
  5808. quiet: bool = False,
  5809. require_unambiguous: bool = False,
  5810. plate_id: int | None = None,
  5811. run_started_at: datetime | None | object = _ANY_RUN,
  5812. ) -> bool:
  5813. """Download and attach the one video that belongs to this print.
  5814. A candidate is any file absent from the print-start baseline. More than one
  5815. can qualify when a previous print's video landed late, after this print's
  5816. baseline was taken — those are filtered out by name, because they are
  5817. already attached to another archive. Sorting the candidates instead would
  5818. mean sorting on mtime or on the filename timestamp, both of which come from
  5819. the printer's unsynced clock.
  5820. Returns True once a video is attached. The printer's copy is deleted only
  5821. after the attach succeeds on bytes whose length matched the listing.
  5822. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5823. already seen this exact listing — the poll runs for many rounds and only the
  5824. rounds where something changed are worth an INFO line.
  5825. """
  5826. from backend.app.services.bambu_ftp import (
  5827. DownloadDeadlineExceeded,
  5828. delete_archived_timelapse,
  5829. download_file_bytes_async,
  5830. remote_file_settled,
  5831. )
  5832. speak = logger.debug if quiet else logger.info
  5833. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5834. if not new_files:
  5835. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5836. return False
  5837. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5838. if not candidates:
  5839. speak(
  5840. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5841. attempt,
  5842. len(new_files),
  5843. )
  5844. return False
  5845. if len(candidates) > 1:
  5846. if require_unambiguous:
  5847. # The baseline is not evidence -- it was taken off a card that could
  5848. # not be read -- so "new since the baseline" does not narrow these
  5849. # down at all. Taking the first would attach an arbitrary video to
  5850. # this print and then delete it from the printer.
  5851. logger.warning(
  5852. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5853. "leaving all of them on the printer for manual selection",
  5854. attempt,
  5855. len(candidates),
  5856. ", ".join(str(f.get("name")) for f in candidates),
  5857. )
  5858. return False
  5859. logger.warning(
  5860. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5861. "the rest stay on the printer for manual selection",
  5862. attempt,
  5863. len(candidates),
  5864. ", ".join(str(f.get("name")) for f in candidates),
  5865. )
  5866. target = candidates[0]
  5867. file_name = str(target.get("name") or "") # every listed entry has one
  5868. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5869. logger.info(
  5870. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5871. attempt,
  5872. file_name,
  5873. archive_id,
  5874. )
  5875. # The listing always carries a size (`list_files` skips entries it can't
  5876. # parse), but read it explicitly: the delete below is destructive and must
  5877. # depend on a size we actually had, not on one we hoped was there.
  5878. expected_size = target.get("size")
  5879. try:
  5880. timelapse_data = await download_file_bytes_async(
  5881. printer.ip_address,
  5882. printer.access_code,
  5883. remote_path,
  5884. printer_model=printer.model,
  5885. expected_size=expected_size,
  5886. )
  5887. except DownloadDeadlineExceeded:
  5888. # Too slow for its size this round; the printer keeps its copy.
  5889. timelapse_data = None
  5890. if not timelapse_data:
  5891. # Short or failed transfer. The printer keeps its copy, so the next
  5892. # round can try again — which is exactly why the delete below is
  5893. # gated on a verified download.
  5894. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5895. return False
  5896. # The length check above proves we got what the listing said, not that the
  5897. # printer had finished writing. A video still being written can be listed
  5898. # short, served short, and pass — so confirm it has stopped growing before
  5899. # committing to it and deleting the original (#2704).
  5900. if not await remote_file_settled(
  5901. printer.ip_address,
  5902. printer.access_code,
  5903. remote_path,
  5904. len(timelapse_data),
  5905. printer_model=printer.model,
  5906. ):
  5907. return False
  5908. # Write phase: attach in a fresh short-lived session. The download took a
  5909. # while: by now the archive may have its video, or be printing again for a
  5910. # newer run, whose video this is not. Then nothing is attached or deleted,
  5911. # and the poll ends (True).
  5912. async with async_session() as db:
  5913. service = ArchiveService(db)
  5914. if run_started_at is not _ANY_RUN:
  5915. current = await service.get_archive(archive_id)
  5916. if current is None or current.timelapse_path or current.started_at != run_started_at:
  5917. logger.info(
  5918. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  5919. "%s stays on the printer",
  5920. archive_id,
  5921. file_name,
  5922. )
  5923. return True
  5924. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5925. if not success:
  5926. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5927. return False
  5928. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5929. await delete_archived_timelapse(
  5930. printer.ip_address,
  5931. printer.access_code,
  5932. remote_path,
  5933. verified=expected_size is not None,
  5934. printer_model=printer.model,
  5935. printer_name=printer.name,
  5936. )
  5937. return True
  5938. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5939. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5940. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5941. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5942. # How long the *background* upgrade keeps waiting after the notification has
  5943. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5944. # printer can't hold up the print-complete notification; this one exists so the
  5945. # archive still ends up with the better frame afterwards.
  5946. #
  5947. # Measured across 261 attaches in the support bundles, the video lands a median
  5948. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5949. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5950. # was 546s. Every other model was inside 26s. The long budget is therefore
  5951. # almost entirely for P1-series users; on everything else the short wait already
  5952. # wins and this task never runs.
  5953. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5954. async def _capture_finish_photo_from_timelapse(
  5955. archive_id: int,
  5956. archive_dir: Path,
  5957. timeout: float | None = None,
  5958. rotation: int = 0,
  5959. ) -> tuple[str | None, bool]:
  5960. """Wait for the per-print timelapse to land on the archive and extract its
  5961. last frame as the finish photo (#1397).
  5962. Bambu firmware stops timelapse recording after the toolhead parks but
  5963. before the bed-drop end-gcode runs, so the last frame frames the finished
  5964. print correctly. A live camera grab at gcode_state=FINISH captures the
  5965. bed already lowered.
  5966. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5967. ``archive.timelapse_path`` when the file lands. This function polls for
  5968. that field.
  5969. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5970. the wait ran out with no video on the archive yet — i.e. the video may
  5971. still be coming and a later attempt could succeed. It is False when the
  5972. video landed (whether or not extraction worked), because in that case
  5973. waiting longer changes nothing. The caller uses that to decide between
  5974. falling back permanently and scheduling a background upgrade.
  5975. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5976. still (#2708) so this source agrees with every other finish-photo source.
  5977. The archived video itself is the printer's own file and is left alone —
  5978. rotating it would mean re-encoding it.
  5979. """
  5980. import uuid
  5981. from backend.app.models.archive import PrintArchive
  5982. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5983. logger = logging.getLogger(__name__)
  5984. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5985. deadline = asyncio.get_event_loop().time() + budget
  5986. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5987. while True:
  5988. async with async_session() as db:
  5989. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5990. archive = result.scalar_one_or_none()
  5991. timelapse_relpath = archive.timelapse_path if archive else None
  5992. if timelapse_relpath:
  5993. video_path = app_settings.base_dir / timelapse_relpath
  5994. if video_path.exists() and video_path.stat().st_size > 0:
  5995. photos_dir = archive_dir / "photos"
  5996. photos_dir.mkdir(parents=True, exist_ok=True)
  5997. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5998. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5999. output_path = photos_dir / filename
  6000. if await extract_video_last_frame(video_path, output_path):
  6001. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6002. logger.info(
  6003. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6004. video_path.name,
  6005. archive_id,
  6006. )
  6007. return filename, False
  6008. logger.warning(
  6009. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6010. video_path.name,
  6011. archive_id,
  6012. )
  6013. return None, False
  6014. if asyncio.get_event_loop().time() >= deadline:
  6015. logger.info(
  6016. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6017. archive_id,
  6018. budget,
  6019. )
  6020. return None, True
  6021. await asyncio.sleep(poll_interval)
  6022. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6023. """Add the timelapse's last frame to an archive after the fact (#2704).
  6024. The print-complete notification waits only ~60s for the video, because
  6025. holding a notification for minutes is worse than sending it with a live
  6026. camera grab. On a P1-series printer the video often lands well after that,
  6027. so the archive used to be stuck with the live grab — which is taken at
  6028. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6029. the worse photo of the two.
  6030. This keeps waiting in the background and, when the video arrives, extracts
  6031. the frame and puts it *first* in the archive's photo list, so opening the
  6032. gallery shows it. The live grab is deliberately kept: the notification that
  6033. already went out links to that exact file, and deleting it would leave a
  6034. broken image in Discord or Telegram.
  6035. """
  6036. logger = logging.getLogger(__name__)
  6037. filename, _ = await _capture_finish_photo_from_timelapse(
  6038. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6039. )
  6040. if not filename:
  6041. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6042. return
  6043. try:
  6044. async with async_session() as db:
  6045. from backend.app.models.archive import PrintArchive
  6046. archive = await db.get(PrintArchive, archive_id)
  6047. if archive is None:
  6048. return
  6049. photos = list(archive.photos or [])
  6050. if filename in photos:
  6051. return
  6052. # Front of the list: PhotoGalleryModal opens at index 0.
  6053. archive.photos = [filename, *photos]
  6054. await db.commit()
  6055. except Exception as e:
  6056. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6057. return
  6058. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6059. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6060. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6061. """Put the filament-attribution context back after a restart mid-print.
  6062. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6063. both die with the process. The print keeps running, so at completion the
  6064. tracker would fall back to whatever the printer reports *now* — and AMS
  6065. filament backup makes "now" the substitute tray, charging the whole print
  6066. to the spool that only finished it.
  6067. The persisted row is only trusted when its print name still matches what
  6068. the printer says it is running: a row left behind by a completion we never
  6069. saw must not attach itself to the next print.
  6070. """
  6071. try:
  6072. from backend.app.api.routes.settings import get_setting
  6073. from backend.app.services.usage_tracker import (
  6074. clear_persisted_session,
  6075. get_persisted_print_name,
  6076. restore_session,
  6077. )
  6078. persisted_name = await get_persisted_print_name(db, printer_id)
  6079. current_name = (state.subtask_name or "").strip()
  6080. if persisted_name and current_name and persisted_name.strip() != current_name:
  6081. logger.info(
  6082. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6083. printer_id,
  6084. persisted_name,
  6085. current_name,
  6086. )
  6087. await clear_persisted_session(db, printer_id)
  6088. # Fall through to seeding: the print on the printer is real, it just
  6089. # isn't the one the row described.
  6090. persisted_log = None
  6091. else:
  6092. # Spoolman users get the tray-change log back but no in-memory
  6093. # session — see ``on_print_start`` on why that dict is load-bearing
  6094. # for the remain%-sync guard.
  6095. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6096. persisted_log = await restore_session(
  6097. db,
  6098. printer_id,
  6099. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6100. )
  6101. if persisted_log:
  6102. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6103. # Anything this process already observed goes after the persisted
  6104. # history — the log is ordered by layer, and a fresh process can
  6105. # only have seen changes from later in the print.
  6106. for entry in state.tray_change_log or []:
  6107. if tuple(entry) not in restored:
  6108. restored.append(tuple(entry))
  6109. state.tray_change_log = restored
  6110. tray_now = state.tray_now
  6111. if 0 <= tray_now <= 254:
  6112. if not state.tray_change_log:
  6113. # No persisted history — a print that started before this build,
  6114. # or before the row existed. Seed with the tray feeding right
  6115. # now so the remainder of the print is at least attributable to
  6116. # the right spool.
  6117. state.tray_change_log = [(tray_now, state.layer_num)]
  6118. logger.info(
  6119. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6120. printer_id,
  6121. tray_now,
  6122. state.layer_num,
  6123. )
  6124. # The tray handler updates ``last_loaded_tray`` on every push
  6125. # regardless of whether it logged a change, so re-align it to avoid
  6126. # a duplicate entry on the next push. Only ever with a real tray:
  6127. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6128. # 255" fallback, and writing 255 into it would defeat that.
  6129. state.last_loaded_tray = tray_now
  6130. except Exception:
  6131. # Never let attribution recovery cost the caller its timelapse
  6132. # baseline — that capture has to happen before the printer uploads
  6133. # the in-flight MP4 and there is no second chance at it.
  6134. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6135. async def on_print_running_observed(printer_id: int, data: dict):
  6136. """Restart-recovery for a print that started before Bambuddy came up.
  6137. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6138. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6139. creation). This hook restores the persisted archive into ``_active_prints``
  6140. and captures the timelapse baseline that normally hangs off print start.
  6141. Fires once per session, in lieu of on_print_start when restart-recovery
  6142. kicks in. The printer doesn't upload the timelapse until after PRINT
  6143. COMPLETE, so a baseline captured any time during the print is still
  6144. pre-upload.
  6145. """
  6146. logger = logging.getLogger(__name__)
  6147. async with async_session() as db:
  6148. from backend.app.models.printer import Printer
  6149. state = printer_manager.get_status(printer_id)
  6150. if state is not None:
  6151. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6152. if authorization is True:
  6153. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6154. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6155. await _restore_printable_objects(printer_id, state, db, logger)
  6156. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6157. printer = result.scalar_one_or_none()
  6158. if not printer:
  6159. logger.warning(
  6160. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6161. printer_id,
  6162. )
  6163. return
  6164. # Avoid double-capture: ownership reconciliation above must still run when
  6165. # a baseline already exists, but the camera work itself is one-shot.
  6166. if printer_id in _timelapse_baselines:
  6167. logger.debug(
  6168. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6169. printer_id,
  6170. )
  6171. return
  6172. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6173. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6174. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6175. against the printer's current MQTT state.
  6176. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6177. COMPLETE events, typically a print finishing during an MQTT disconnect
  6178. window followed by a smart-plug power cycle):
  6179. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6180. provably not running anymore — only branch that should fire under
  6181. normal disconnect-then-reconnect timing.
  6182. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6183. firmware mints a fresh ``subtask_id`` for each print, including the
  6184. ghost replay it runs after a power cycle from a leftover SD file —
  6185. so a mismatch unambiguously means the in-DB archive is no longer
  6186. the print on the printer.
  6187. 3. Printer is running but ``subtask_name`` is empty. The printer
  6188. doesn't know what it's running; the archive's reference to it is
  6189. already broken.
  6190. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6191. with matching subtask_id+subtask_name is left alone. The cost of a false
  6192. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6193. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6194. clears on synthesis, so the real completion creates a fresh row instead
  6195. of overwriting the synthesised one (#1679). The cost of a false negative
  6196. is the ghost-print loop in #1542.
  6197. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6198. MQTT has connected but the first ``push_status`` response hasn't been
  6199. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6200. The reconcile caller in ``on_printer_status_change`` is already gated
  6201. on a real ``state.state``, so in normal operation this branch is
  6202. unreachable; it's kept as belt-and-braces for future callers and for
  6203. the narrow window where a partial state update could arrive
  6204. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6205. ``not stale`` on degenerate input is strictly conservative: a real
  6206. stale archive will still be caught by the next push_status arriving
  6207. with terminal state.
  6208. """
  6209. current_state = (state.state or "").upper()
  6210. if current_state in ("", "UNKNOWN"):
  6211. # No real push_status yet — PrinterState defaults are not evidence.
  6212. return False, ""
  6213. if current_state in ("IDLE", "FINISH", "FAILED"):
  6214. return True, f"printer state {current_state}"
  6215. # Below here the printer is in a running / pre-running state (RUNNING /
  6216. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6217. current_subtask_id = (state.subtask_id or "").strip()
  6218. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6219. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6220. current_subtask_name = (state.subtask_name or "").strip()
  6221. if not current_subtask_name:
  6222. return True, "printer subtask_name empty"
  6223. return False, ""
  6224. async def prime_kprofile_table(printer_id: int) -> int:
  6225. """Read the printer's calibration table once per connection.
  6226. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6227. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6228. report ``cali_idx`` and nothing else -- that number can only come from
  6229. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6230. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6231. backup, or the printer answering a query BambuStudio made on the report
  6232. topic we share. A Bambuddy that nobody visited showed a card with no K
  6233. values at all.
  6234. Only the diameters actually fitted are asked for, which is one request on a
  6235. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6236. what the backup does, and it is both wasteful and the thing that used to
  6237. blank the table.
  6238. Returns the number of nozzles whose table was read.
  6239. """
  6240. client = printer_manager.get_client(printer_id)
  6241. state = printer_manager.get_status(printer_id)
  6242. if client is None or state is None or not state.connected:
  6243. return 0
  6244. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6245. # ask once, and both entries are empty until the first push_status lands.
  6246. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6247. if not diameters:
  6248. logging.getLogger(__name__).debug(
  6249. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6250. printer_id,
  6251. )
  6252. return 0
  6253. primed = 0
  6254. for diameter in diameters:
  6255. try:
  6256. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6257. except Exception as exc: # noqa: BLE001
  6258. # A printer that won't answer costs the card its K values, nothing
  6259. # more — never the connection this runs on the back of.
  6260. logging.getLogger(__name__).warning(
  6261. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6262. )
  6263. continue
  6264. primed += 1
  6265. logging.getLogger(__name__).info(
  6266. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6267. )
  6268. return primed
  6269. def _sd_files_in_use(state) -> set[str]:
  6270. """Names of the SD-card files the printer may be printing right now (#3009).
  6271. The post-print cleanup works out what to delete from the finished archive,
  6272. not from the printer. When reconciliation closes an old archive because the
  6273. printer has moved on to a new job, and that job is the same file reprinted
  6274. from the printer's screen, the cleanup would delete the file mid-print.
  6275. Empty unless the printer is busy: on an ordinary completion the state is
  6276. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6277. name, a path or a URL depending on firmware, and some report only the
  6278. plate's G-code, so the job name is matched as well, in the same spellings
  6279. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6280. ignores case.
  6281. """
  6282. def _text(value) -> str:
  6283. return value.strip() if isinstance(value, str) else ""
  6284. if state is None:
  6285. return set()
  6286. current_state = _text(getattr(state, "state", None)).upper()
  6287. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6288. return set()
  6289. in_use: set[str] = set()
  6290. gcode_file = _text(getattr(state, "gcode_file", None))
  6291. if gcode_file:
  6292. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6293. # both legal in a file name, and raises on some inputs.
  6294. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6295. if name:
  6296. in_use.add(name.lower())
  6297. subtask_name = _text(getattr(state, "subtask_name", None))
  6298. if subtask_name:
  6299. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6300. for ext in (".3mf", ".gcode"):
  6301. in_use.add(f"{name}{ext}".lower())
  6302. return in_use
  6303. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6304. """Synthesise ``on_print_complete`` for archives whose print can't be
  6305. running on the printer anymore.
  6306. Called once per MQTT (re)connection (from on_printer_status_change when
  6307. the connected edge flips False → True) and at Bambuddy startup (from
  6308. the FastAPI lifespan). Without this, a print that completes during a
  6309. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6310. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6311. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6312. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6313. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6314. closes the loop by faking the missed PRINT COMPLETE — the existing
  6315. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6316. and notifications.
  6317. Synthesised ``status="aborted"`` is the conservative label: we have no
  6318. proof the print finished successfully (and no progress evidence to
  6319. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6320. fires later, overwrites the status with the correct value.
  6321. Returns the number of archives reconciled.
  6322. """
  6323. state = printer_manager.get_status(printer_id)
  6324. if not state:
  6325. return 0
  6326. # Don't reconcile while disconnected — we'd be making a decision against
  6327. # stale cached state. The connected → reconcile edge handles this.
  6328. if not state.connected:
  6329. return 0
  6330. from backend.app.models.archive import PrintArchive
  6331. reconciled = 0
  6332. async with async_session() as db:
  6333. result = await db.execute(
  6334. select(PrintArchive).where(
  6335. PrintArchive.printer_id == printer_id,
  6336. PrintArchive.status == "printing",
  6337. )
  6338. )
  6339. active = list(result.scalars().all())
  6340. if not active:
  6341. return 0
  6342. logger = logging.getLogger(__name__)
  6343. for archive in active:
  6344. is_stale, reason = _is_active_archive_stale(archive, state)
  6345. if not is_stale:
  6346. continue
  6347. logger.info(
  6348. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6349. printer_id,
  6350. archive.id,
  6351. archive.filename,
  6352. reason,
  6353. )
  6354. # Synthesised payload: minimal fields the on_print_complete chain
  6355. # needs. `_reconciled` marker lets downstream code distinguish this
  6356. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6357. # metrics / debug logging). raw_data is the live printer state so
  6358. # the usage tracker can compare end-of-print remain% against the
  6359. # captured start values.
  6360. try:
  6361. await on_print_complete(
  6362. printer_id,
  6363. {
  6364. "status": "aborted",
  6365. "filename": archive.filename,
  6366. "subtask_name": archive.print_name or "",
  6367. "subtask_id": archive.subtask_id or "",
  6368. "raw_data": state.raw_data or {},
  6369. "_reconciled": True,
  6370. },
  6371. )
  6372. reconciled += 1
  6373. except Exception as e:
  6374. # Catch-all: a reconciliation failure must not block the
  6375. # printer's normal status flow. The archive stays in
  6376. # ``status="printing"`` and the next reconnect retries.
  6377. logger.warning(
  6378. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6379. archive.id,
  6380. e,
  6381. )
  6382. return reconciled
  6383. # #2547: clearance left between the nozzle and the top of the print when the
  6384. # plate is commanded back into camera framing. The nozzle is parked away from
  6385. # the part by then, so this is belt-and-braces against a max_z_height that
  6386. # under-reports (e.g. a slicer that excludes a final Z hop).
  6387. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6388. # How far below the restored position to drop the plate again afterwards, so
  6389. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6390. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6391. # on machines with less headroom.
  6392. _PLATE_PARK_DROP_MM = 100.0
  6393. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6394. # this axis, so it is a proven-safe speed for the full travel.
  6395. _PLATE_RESTORE_FEEDRATE = 600
  6396. # Time allowed for the plate to reach the restored position before the camera
  6397. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6398. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6399. # How long `_background_finish_photo` waits for this producer. Must cover the
  6400. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6401. # notification path's own photo wait so a slow producer degrades to a
  6402. # photo-less notification rather than a missed one. The chamber light's
  6403. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6404. # camera_light.MAX_DELAY_SECONDS stays below it.
  6405. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6406. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6407. """The ``_active_prints`` keys a finished print may be registered under.
  6408. Matching how they were registered in on_print_start. Shared by
  6409. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6410. to find the same binding.
  6411. """
  6412. possible_keys = []
  6413. # Try subtask_name variations first (most reliable for matching)
  6414. if subtask_name:
  6415. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6416. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6417. possible_keys.append((printer_id, subtask_name))
  6418. # Try filename variations
  6419. if filename:
  6420. # Extract just the filename if it's a path
  6421. fname = filename.split("/")[-1] if "/" in filename else filename
  6422. if fname.endswith(".3mf"):
  6423. possible_keys.append((printer_id, fname))
  6424. elif fname.endswith(".gcode"):
  6425. base_name = fname.rsplit(".", 1)[0]
  6426. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6427. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6428. possible_keys.append((printer_id, fname))
  6429. else:
  6430. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6431. possible_keys.append((printer_id, f"{fname}.3mf"))
  6432. possible_keys.append((printer_id, fname))
  6433. # Also try full path versions
  6434. if filename.endswith(".3mf"):
  6435. possible_keys.append((printer_id, filename))
  6436. elif filename.endswith(".gcode"):
  6437. base_name = filename.rsplit(".", 1)[0]
  6438. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6439. possible_keys.append((printer_id, filename))
  6440. else:
  6441. possible_keys.append((printer_id, f"{filename}.3mf"))
  6442. possible_keys.append((printer_id, filename))
  6443. return possible_keys
  6444. def _archive_name_forms(archive) -> set[str]:
  6445. """The names an archive could be echoed back as, in normalised form (#3240).
  6446. Its print name, and its filename with and without the 3MF extension.
  6447. """
  6448. forms = set()
  6449. if archive.print_name:
  6450. forms.add(_normalise_subtask_name(archive.print_name))
  6451. if archive.filename:
  6452. forms.add(_normalise_subtask_name(archive.filename))
  6453. for suffix in (".gcode.3mf", ".3mf"):
  6454. if archive.filename.lower().endswith(suffix):
  6455. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6456. forms.discard("")
  6457. return forms
  6458. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6459. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6460. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6461. from the plate recorded when the job was dispatched. Neither is touched:
  6462. ``on_print_complete`` pops both, which is why the finish-photo producer
  6463. calls this before its first await, while they are still there.
  6464. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6465. archive, or that it only knows by a name -- and on any error: the producer
  6466. calls this before the ``try`` that always releases the photo consumer, so
  6467. it must not raise.
  6468. """
  6469. try:
  6470. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6471. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6472. if archive_id is None:
  6473. return None, None
  6474. return archive_id, _print_plate_ids.get(archive_id)
  6475. except Exception:
  6476. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6477. return None, None
  6478. async def _max_z_for_current_print(
  6479. printer_id: int,
  6480. data: dict,
  6481. logger,
  6482. archive_id: int | None,
  6483. plate_id: int | None = None,
  6484. ) -> float | None:
  6485. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6486. This number becomes the target of a real Z move, so every step here refuses
  6487. rather than guesses. A height belonging to some *other* print is the one
  6488. failure that could drive the nozzle into the model: 20 mm carried onto a
  6489. 200 mm print would command the plate up through the part.
  6490. Three independent things therefore have to agree before a height is
  6491. returned:
  6492. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6493. when it started (see ``_bound_print``), never one found by name. A name
  6494. is not an identity: every plate of a multi-plate file shares one, and a
  6495. reprint reuses its archive row, so the newest archive with the right
  6496. name can be another plate of the same file. Support bundles show the
  6497. old name lookup doing exactly that (archive 288 for a print bound to
  6498. 169, 313 layers against 125), stopped only by the layer check below.
  6499. No binding, no move.
  6500. 2. **Identity.** The bound archive's name still has to be the finished
  6501. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6502. because the printer echoes spaces as underscores (#3240). Exact: not a
  6503. substring, and not the completion check's tolerance for a truncated
  6504. echo.
  6505. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6506. match the layer count the printer itself reported over MQTT for the print
  6507. that just ended. These come from genuinely different sources, so a
  6508. mismatch means the row is not this print, whatever its name says.
  6509. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6510. plate of a multi-plate file reuses the archive row without updating its
  6511. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6512. ``on_print_complete`` may already have flipped the status by the time we
  6513. run.
  6514. """
  6515. subtask_name = (data.get("subtask_name") or "").strip()
  6516. if not subtask_name:
  6517. # Nothing to identify the print by — refuse rather than fall back to
  6518. # "whatever ran last on this printer".
  6519. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6520. return None
  6521. if archive_id is None:
  6522. logger.info(
  6523. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6524. printer_id,
  6525. subtask_name,
  6526. )
  6527. return None
  6528. try:
  6529. from backend.app.models.archive import PrintArchive
  6530. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6531. async with async_session() as db:
  6532. result = await db.execute(
  6533. select(PrintArchive).where(
  6534. PrintArchive.id == archive_id,
  6535. PrintArchive.printer_id == printer_id,
  6536. PrintArchive.status.in_(("printing", "completed")),
  6537. PrintArchive.deleted_at.is_(None),
  6538. )
  6539. )
  6540. archive = result.scalar_one_or_none()
  6541. if archive is None or not archive.file_path:
  6542. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6543. return None
  6544. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6545. logger.warning(
  6546. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6547. printer_id,
  6548. archive_id,
  6549. subtask_name,
  6550. )
  6551. return None
  6552. client = printer_manager.get_client(printer_id)
  6553. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6554. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6555. logger.warning(
  6556. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6557. "— refusing to move the plate on a height that may not be this print's",
  6558. printer_id,
  6559. archive.id,
  6560. archive.total_layers,
  6561. reported_layers,
  6562. )
  6563. return None
  6564. # Stored relative to the data directory, like every other archive path
  6565. # (#3240: this read a `data_dir` setting that does not exist).
  6566. path = app_settings.base_dir / archive.file_path
  6567. plate = plate_id or archive.plate_id or 1
  6568. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6569. except Exception as e:
  6570. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6571. return None
  6572. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6573. """Raise the plate back into camera framing before the finish photo (#2547).
  6574. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6575. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6576. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6577. This commands an absolute ``G1 Z`` back to just above the last printed
  6578. layer.
  6579. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6580. clearance`` is a height the toolhead was physically at seconds earlier, so
  6581. it is inside the travel limits by construction and leaves the nozzle above
  6582. the part. It is also unambiguous across model families: Z is the
  6583. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6584. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6585. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6586. (#2579).
  6587. Returns True if the move was sent and waited out, False if it was skipped.
  6588. """
  6589. client = printer_manager.get_client(printer_id)
  6590. if client is None:
  6591. return False
  6592. # Re-read state immediately before commanding motion. If the queue has
  6593. # already started the next print, the printer is no longer ours to move.
  6594. state = getattr(client, "state", None)
  6595. if state is None or state.state != "FINISH":
  6596. logger.info(
  6597. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6598. printer_id,
  6599. getattr(state, "state", "unknown"),
  6600. )
  6601. return False
  6602. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6603. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6604. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6605. return False
  6606. logger.info(
  6607. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6608. printer_id,
  6609. target_z,
  6610. max_z_height,
  6611. _PLATE_RESTORE_CLEARANCE_MM,
  6612. _PLATE_RESTORE_SETTLE_SECONDS,
  6613. )
  6614. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6615. return True
  6616. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6617. """Drop the plate again after the finish photo (#2547).
  6618. Without this the user walks up to a finished print sitting just under the
  6619. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6620. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6621. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6622. print homes anyway.
  6623. """
  6624. client = printer_manager.get_client(printer_id)
  6625. state = getattr(client, "state", None) if client else None
  6626. if client is None or state is None or state.state != "FINISH":
  6627. return
  6628. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6629. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6630. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6631. """True if a queue item is about to take this printer (#2547).
  6632. The scheduler dispatches the next job the moment a print completes, and a
  6633. plate move interleaved with a print start is not a race worth having. The
  6634. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6635. this window; this closes the head of it.
  6636. """
  6637. try:
  6638. from backend.app.models.print_queue import PrintQueueItem
  6639. async with async_session() as db:
  6640. result = await db.execute(
  6641. select(PrintQueueItem.id)
  6642. .where(
  6643. PrintQueueItem.printer_id == printer_id,
  6644. PrintQueueItem.status.in_(("pending", "printing")),
  6645. )
  6646. .limit(1)
  6647. )
  6648. return result.scalar_one_or_none() is not None
  6649. except Exception as e:
  6650. # Fail closed: if we can't tell, don't move the plate.
  6651. logging.getLogger(__name__).debug(
  6652. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6653. )
  6654. return True
  6655. async def on_finish_photo_moment(printer_id: int, data: dict):
  6656. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6657. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6658. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6659. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6660. HMS halt, firmware variants). Grabs one frame via the same
  6661. external-camera / RTSP path the post-completion fallback uses, stores
  6662. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6663. ``_background_finish_photo`` consume the cached bytes when it runs.
  6664. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6665. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6666. set to Smooth (#1721). No force-on now means the user's explicit
  6667. timelapse=off in the slicer send dialog is respected.
  6668. """
  6669. logger = logging.getLogger(__name__)
  6670. trigger = data.get("trigger", "unknown")
  6671. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6672. logger.info(
  6673. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6674. printer_id,
  6675. trigger,
  6676. timelapse_was_active,
  6677. )
  6678. # If a timelapse is actively recording, skip the pre-capture — the
  6679. # post-completion path will extract the last frame from the recorded
  6680. # video, which still provides the best framing (toolhead parked,
  6681. # before bed drop) without the per-layer parking side effects.
  6682. if timelapse_was_active:
  6683. logger.info(
  6684. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6685. printer_id,
  6686. )
  6687. return
  6688. # #1790: register the producer-done event BEFORE the first await so the
  6689. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6690. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6691. # The `finally` below guarantees `set()` runs on every exit, including
  6692. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6693. producer_done = asyncio.Event()
  6694. _stage22_finish_in_flight[printer_id] = producer_done
  6695. # #3240: also before the first await. On the FINISH-state path
  6696. # `on_print_complete` is dispatched right behind us and pops both the
  6697. # print's archive binding and its plate; read here, they are still there.
  6698. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6699. # #2547: set once the plate has actually been raised, and read by the
  6700. # `finally` below. Declared out here so a failure anywhere after the move —
  6701. # a camera timeout, a DB error — still lowers the plate again.
  6702. restore_max_z: float | None = None
  6703. try:
  6704. async with async_session() as db:
  6705. from backend.app.api.routes.settings import get_setting
  6706. from backend.app.models.printer import Printer
  6707. capture_setting = await get_setting(db, "capture_finish_photo")
  6708. if capture_setting is not None and capture_setting.lower() != "true":
  6709. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6710. return
  6711. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6712. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6713. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6714. printer = result.scalar_one_or_none()
  6715. if printer is None:
  6716. logger.warning(
  6717. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6718. printer_id,
  6719. )
  6720. return
  6721. frame_bytes: bytes | None = None
  6722. # #2708: the banked frame arrives already rotated — it comes from
  6723. # `_capture_snapshot_for_notification`, which rotates before returning.
  6724. # Every other source below is a raw grab. Tracking which lets us store
  6725. # exactly one rotation in `_stage22_finish_frames` either way.
  6726. frame_already_rotated = False
  6727. # On the FINISH-state path the End G-code has already run, and two very
  6728. # different situations arrive here needing opposite answers.
  6729. #
  6730. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6731. # snippet may have ejected the plate — the scene in front of the camera
  6732. # is no longer the finished print, and no amount of moving the plate
  6733. # brings it back. Use the banked in-print frame instead.
  6734. #
  6735. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6736. # than the camera frames well, and the toolhead is parked out of the
  6737. # way. That is the *best* moment available on firmware that never emits
  6738. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6739. # back. Preferring the bank here unconditionally, as this code used to,
  6740. # is what shipped a mid-print photo with the toolhead over the part.
  6741. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6742. banked = _inprint_frame_bank.get(printer_id)
  6743. if banked:
  6744. frame_bytes = banked
  6745. frame_already_rotated = True
  6746. logger.info(
  6747. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6748. "frame (%d bytes) instead of a post-swap live grab",
  6749. len(banked),
  6750. )
  6751. else:
  6752. logger.warning(
  6753. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6754. "in-print bank is empty — falling back to a live grab, which may show a "
  6755. "swapped or empty plate",
  6756. printer_id,
  6757. )
  6758. # `restore_max_z` is set only once the plate is actually up, because the
  6759. # `finally` reads it to decide whether it owes a move back down.
  6760. #
  6761. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6762. # came up empty above: that machine may have just ejected its plate, and
  6763. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6764. # taking for a photo of a bed we already know may be bare.
  6765. if (
  6766. frame_bytes is None
  6767. and trigger == "finish_state"
  6768. and restore_plate_enabled
  6769. and not print_dispatch_context.end_gcode_injected(printer_id)
  6770. ):
  6771. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6772. if wants_restore is None:
  6773. logger.info(
  6774. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6775. printer_id,
  6776. )
  6777. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6778. logger.info(
  6779. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6780. printer_id,
  6781. )
  6782. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6783. restore_max_z = wants_restore
  6784. # Chamber light for the live capture below (#1655). The banked frame
  6785. # above was taken without it, like every in-print bank.
  6786. async with camera_light(printer if frame_bytes is None else None):
  6787. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6788. from backend.app.api.routes.camera import live_frame_for_capture
  6789. from backend.app.services.external_camera import capture_frame
  6790. # #2707: this used to collide with the live view and fail, which is
  6791. # how finish-photo notifications went out with no image attached.
  6792. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6793. defer, buffered = live_frame_for_capture(printer_id)
  6794. if defer:
  6795. frame_bytes = buffered
  6796. else:
  6797. frame_bytes = await capture_frame(
  6798. printer.external_camera_url,
  6799. printer.external_camera_type or "mjpeg",
  6800. snapshot_url=printer.external_camera_snapshot_url,
  6801. )
  6802. if frame_bytes:
  6803. logger.info(
  6804. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6805. len(frame_bytes),
  6806. )
  6807. elif frame_bytes is None:
  6808. from backend.app.api.routes.camera import get_buffered_frame
  6809. buffered = get_buffered_frame(printer_id)
  6810. if buffered:
  6811. frame_bytes = buffered
  6812. logger.info(
  6813. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6814. len(frame_bytes),
  6815. )
  6816. else:
  6817. from backend.app.services.camera import capture_camera_frame_bytes
  6818. frame_bytes = await capture_camera_frame_bytes(
  6819. ip_address=printer.ip_address,
  6820. access_code=printer.access_code,
  6821. model=printer.model,
  6822. timeout=15,
  6823. )
  6824. if frame_bytes:
  6825. logger.info(
  6826. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6827. len(frame_bytes),
  6828. )
  6829. if frame_bytes:
  6830. if not frame_already_rotated:
  6831. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6832. _stage22_finish_frames[printer_id] = frame_bytes
  6833. else:
  6834. logger.warning(
  6835. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6836. printer_id,
  6837. )
  6838. except Exception as e:
  6839. logger.warning(
  6840. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6841. printer_id,
  6842. e,
  6843. )
  6844. finally:
  6845. # #2547: we raised the plate, so we own lowering it — including when the
  6846. # capture above failed or threw partway through.
  6847. if restore_max_z is not None:
  6848. try:
  6849. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6850. except Exception as e:
  6851. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6852. # #1790: always unblock the consumer's bounded wait — whether we stored
  6853. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6854. # dict entry by the consumer doesn't affect signalling.
  6855. producer_done.set()
  6856. def _subtask_name_from_filename(filename: str) -> str:
  6857. """Recover the subtask name a print command would have carried for *filename*.
  6858. The dispatcher derives the printer-facing subtask name from the archive's
  6859. file name, so stripping the extensions back off gives the value MQTT echoes
  6860. on completion. Only the two extensions Bambuddy actually stores are removed,
  6861. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6862. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6863. """
  6864. name = PurePosixPath(filename).name
  6865. for suffix in (".3mf", ".gcode"):
  6866. if name.lower().endswith(suffix):
  6867. name = name[: -len(suffix)]
  6868. return name
  6869. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6870. """Whether the subtask name is the printed 3MF's own file name.
  6871. A print started from the printer's screen reports the same full name, with
  6872. its extension, as both subtask and file (#3009). A dispatched print reports
  6873. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6874. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6875. """
  6876. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6877. return False
  6878. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6879. # How the printer marks a subtask name it had to cut short. Observed on real
  6880. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6881. # (a name with multibyte characters came back at 98), so match the marker
  6882. # rather than a length.
  6883. _SUBTASK_TRUNCATION_MARKER = "..."
  6884. def _normalise_subtask_name(name: str) -> str:
  6885. """Canonical form for comparing a dispatched name against MQTT's echo.
  6886. The printer does not echo the name back verbatim: it substitutes
  6887. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6888. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6889. The 3MF lookup in this module has always known that -- it builds
  6890. space-to-underscore variants of every candidate filename, and its
  6891. directory search normalises both sides before comparing. This exists so
  6892. the completion check reads the same rule from the same place instead of
  6893. growing its own, which is exactly how it came to disagree (#2829).
  6894. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6895. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6896. are dropped after the substitution so both sides agree (#3241).
  6897. """
  6898. return name.strip().replace(" ", "_").strip("_").casefold()
  6899. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  6900. """The 3MF files of the printer's folder listings that are this print's.
  6901. A file of the print's own name wins, in whichever folder. Only without one
  6902. is a file that merely contains the name taken, and then only when it is
  6903. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  6904. candidates none can be told apart. Paths keep the listings' order.
  6905. """
  6906. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  6907. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  6908. if exact:
  6909. return exact
  6910. term = _normalise_subtask_name(search_term)
  6911. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  6912. if len(partial) > 1:
  6913. logging.getLogger(__name__).info(
  6914. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  6915. )
  6916. return []
  6917. return partial
  6918. def _subtask_names_match(expected: str, observed: str) -> bool:
  6919. """Whether two subtask names describe the same print.
  6920. Beyond the space/underscore substitution, the printer truncates long names
  6921. and marks the cut with ``...``. A truncated echo has to count as a match or
  6922. every print with a long name strands its queue item the same way.
  6923. """
  6924. expected_n = _normalise_subtask_name(expected)
  6925. observed_n = _normalise_subtask_name(observed)
  6926. if expected_n == observed_n:
  6927. return True
  6928. # Either side can be the truncated one: the printer truncates what it
  6929. # echoes, and an archive whose own filename was recorded from a previous
  6930. # truncated echo carries the marker too.
  6931. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6932. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6933. continue
  6934. # The full side has lost its edge underscores; a cut that lands right
  6935. # after one keeps it, so drop it here too (#3241). Nothing left before
  6936. # the marker is no evidence of anything, and must not match every name.
  6937. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6938. if kept and full.startswith(kept):
  6939. return True
  6940. return False
  6941. async def _queue_item_dispatched_name(db, item) -> str:
  6942. """The subtask name *item* was dispatched under, or "" when unknowable.
  6943. A row with no archive, or an archive with no file name, is unverifiable
  6944. rather than wrong; every caller answers that with its permissive branch.
  6945. """
  6946. if item.archive_id is None:
  6947. return ""
  6948. from backend.app.models.archive import PrintArchive
  6949. archive = await db.get(PrintArchive, item.archive_id)
  6950. if archive is None or not archive.filename:
  6951. return ""
  6952. return _subtask_name_from_filename(archive.filename)
  6953. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6954. """Whether this completion event is plausibly about *item*'s print.
  6955. The caller finds its queue row by printer and ``status='printing'`` alone,
  6956. which is all a completion event gives it -- there is no run identifier in
  6957. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6958. completion delivered for this printer closes whichever row happens to be
  6959. printing, however unrelated. Comparing the subtask name against the archive
  6960. the row was dispatched with costs one primary-key load and rules that out.
  6961. Deliberately permissive: it answers False only on a positive disagreement
  6962. between two names we actually have. A row with no archive, an archive with
  6963. no file name, or an event with no subtask name is unverifiable rather than
  6964. wrong, and refusing those would strand the item in ``printing`` and wedge
  6965. the printer's queue -- a worse failure than the one being prevented.
  6966. """
  6967. observed = (data.get("subtask_name") or "").strip()
  6968. if not observed or item.archive_id is None:
  6969. return True
  6970. from backend.app.models.archive import PrintArchive
  6971. archive = await db.get(PrintArchive, item.archive_id)
  6972. if archive is None or not archive.filename:
  6973. return True
  6974. expected = _subtask_name_from_filename(archive.filename)
  6975. if not expected or _subtask_names_match(expected, observed):
  6976. return True
  6977. logging.getLogger(__name__).warning(
  6978. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6979. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6980. "printing rather than closing a run this event is not about.",
  6981. item.id,
  6982. expected,
  6983. archive.id,
  6984. archive.filename,
  6985. observed,
  6986. )
  6987. return False
  6988. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6989. """Spend the 3MF download cache on a still-empty fallback archive.
  6990. ``on_print_complete`` drops the cache as its first act, which deletes the
  6991. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6992. print ran and the archive never got one, this is the last moment those bytes
  6993. exist (#2957).
  6994. """
  6995. logger = logging.getLogger(__name__)
  6996. names = [
  6997. n
  6998. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6999. if n
  7000. ]
  7001. for name in names:
  7002. try:
  7003. cached = get_cached_3mf(printer_id, name)
  7004. # The print has ended: its completion prices the archive, so no
  7005. # print-start estimate is scheduled to race it.
  7006. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7007. return
  7008. except Exception as e:
  7009. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7010. # Longest the print's end waits for its file to be deleted from the SD card
  7011. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7012. async def _cleanup_sd_card_after_print(
  7013. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7014. ) -> None:
  7015. """Delete a finished print's file from the printer's SD card."""
  7016. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7017. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7018. # auto-start files found in root on power cycle, causing ghost prints.
  7019. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7020. try:
  7021. if subtask_name:
  7022. archive_filename: str | None = None
  7023. async with async_session() as db:
  7024. from backend.app.models.archive import PrintArchive
  7025. from backend.app.models.printer import Printer
  7026. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7027. printer = result.scalar_one_or_none()
  7028. if archive_id:
  7029. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7030. archive_filename = archive_row.scalar_one_or_none()
  7031. if printer:
  7032. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7033. from backend.app.utils.filename import derive_remote_filename
  7034. # Primary candidate: the exact path the dispatcher uploaded to
  7035. # (derived from archive.filename via the same rule as upload).
  7036. # Without it, a library row that ended up with a doubled
  7037. # .gcode.3mf (#1542) leaves the real file behind because the
  7038. # subtask_name + ext fallbacks below don't match what's on the
  7039. # SD card. Fallbacks remain for archive-less prints (subtask
  7040. # never resolved to an archive) and for older naming variants.
  7041. candidate_paths: list[str] = []
  7042. if archive_filename:
  7043. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7044. for ext in (".3mf", ".gcode"):
  7045. fallback = f"/{subtask_name}{ext}"
  7046. if fallback not in candidate_paths:
  7047. candidate_paths.append(fallback)
  7048. # Three outcomes track across all candidates so the final log
  7049. # line reflects what actually happened. The A1 in #1721 always
  7050. # ends here with ``any_not_found=True`` and the others False
  7051. # — its firmware auto-cleans the SD card before our cleanup
  7052. # runs, every candidate FTP-DELE returns 550, and the old
  7053. # code burned 3 retries × 2 s × 3 candidates per print
  7054. # logging a misleading "may linger" WARNING on a successful
  7055. # print.
  7056. any_deleted = False
  7057. any_real_failure = False
  7058. any_not_found = False
  7059. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7060. for remote_path in candidate_paths:
  7061. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7062. logger.info(
  7063. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7064. remote_path,
  7065. printer.name,
  7066. )
  7067. continue
  7068. # Retry only the FAILED case — 550 NOT_FOUND will never
  7069. # recover by waiting, so a "file isn't here" answer
  7070. # advances immediately to the next candidate without
  7071. # consuming the retry budget.
  7072. for attempt in range(1, 4):
  7073. try:
  7074. delete_result = await delete_file_async(
  7075. printer.ip_address,
  7076. printer.access_code,
  7077. remote_path,
  7078. printer_model=printer.model,
  7079. )
  7080. except Exception as e:
  7081. delete_result = DeleteResult.FAILED
  7082. logger.warning(
  7083. "SD card cleanup attempt %d/3 raised for %s: %s",
  7084. attempt,
  7085. remote_path,
  7086. e,
  7087. )
  7088. if delete_result == DeleteResult.DELETED:
  7089. any_deleted = True
  7090. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7091. break
  7092. if delete_result == DeleteResult.NOT_FOUND:
  7093. any_not_found = True
  7094. break # 550 will not recover; try next candidate
  7095. # FAILED: real error — retry with backoff, then give up
  7096. if attempt < 3:
  7097. await asyncio.sleep(2)
  7098. else:
  7099. any_real_failure = True
  7100. logger.warning(
  7101. "SD card cleanup failed after 3 attempts for %s "
  7102. "(network/auth/transient error — file may linger on SD card)",
  7103. remote_path,
  7104. )
  7105. if not any_deleted and not any_real_failure and any_not_found:
  7106. # Every candidate said "not here." Either the printer
  7107. # firmware swept the SD card itself (common on A1) or the
  7108. # dispatcher's upload path doesn't match our candidate
  7109. # rule. Either way: nothing to clean up, no warning.
  7110. logger.debug(
  7111. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7112. "(printer likely self-cleaned)",
  7113. printer.name,
  7114. )
  7115. except Exception as e:
  7116. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7117. async def on_print_complete(printer_id: int, data: dict):
  7118. """Handle print completion - update the archive status.
  7119. The printer counts as printing until the print's usage is booked (or this
  7120. ends), so the AMS remain% weight sync can't charge it a second time while
  7121. the usage tracker works (WU-3). Marked before the first await.
  7122. """
  7123. from backend.app.services.usage_tracker import done_completing, mark_completing
  7124. mark_completing(printer_id)
  7125. try:
  7126. await _close_out_print(printer_id, data)
  7127. finally:
  7128. done_completing(printer_id)
  7129. async def _close_out_print(printer_id: int, data: dict):
  7130. import time
  7131. logger = logging.getLogger(__name__)
  7132. start_time = time.time()
  7133. def log_timing(section: str):
  7134. elapsed = time.time() - start_time
  7135. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7136. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7137. # A kill-switch stop sends its provider notification immediately. Keep the
  7138. # task so the later notification path can await it and avoid a duplicate;
  7139. # if that immediate attempt failed, the regular completion path retries.
  7140. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7141. # Last chance before the bytes go: if this print's archive is still an empty
  7142. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7143. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7144. # below deletes the file (#2957).
  7145. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7146. # A pending cool-off retry has nothing left to recover for — the cache is
  7147. # about to be dropped and the print is over.
  7148. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7149. if retry_task and not retry_task.done():
  7150. retry_task.cancel()
  7151. # Drop the 3MF download cache for this printer (#972). The print is over,
  7152. # nothing else legitimately needs the bytes; keeping them would only risk
  7153. # handing a stale file to the next print if it reuses the same name.
  7154. clear_3mf_cache(printer_id)
  7155. try:
  7156. ws_data = {
  7157. "status": data.get("status"),
  7158. "filename": data.get("filename"),
  7159. "subtask_name": data.get("subtask_name"),
  7160. "timelapse_was_active": data.get("timelapse_was_active"),
  7161. }
  7162. await ws_manager.send_print_complete(printer_id, ws_data)
  7163. log_timing("WebSocket send_print_complete")
  7164. except Exception as e:
  7165. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7166. # Capture user info before clearing (needed for print log entry)
  7167. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7168. # Clear current print user tracking (Issue #206)
  7169. printer_manager.clear_current_print_user(printer_id)
  7170. # If the user explicitly stopped this print from the queue UI the printer will
  7171. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7172. # correct "print stopped" notification/email is sent instead of a failure alert.
  7173. _raw_status = data.get("status", "completed")
  7174. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7175. logger.info(
  7176. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7177. _raw_status,
  7178. printer_id,
  7179. )
  7180. data = {**data, "status": "cancelled"}
  7181. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7182. logger.info(
  7183. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7184. _raw_status,
  7185. printer_id,
  7186. )
  7187. data = {**data, "status": "cancelled", "_kill_switch": True}
  7188. _user_stopped_printers.discard(printer_id)
  7189. _kill_switch_stopped.discard(printer_id)
  7190. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7191. # may have left material on the bed: a user can cancel ten hours into a
  7192. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7193. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7194. # `_user_stopped_printers` is only populated when the user stops via the
  7195. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7196. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7197. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7198. # Auto Off power cycles and Bambuddy restarts.
  7199. try:
  7200. notify_live_activities.print_finished(printer_id, data)
  7201. except Exception:
  7202. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7203. _final_status = data.get("status", "completed")
  7204. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7205. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7206. # MQTT relay - publish print complete
  7207. try:
  7208. printer_info = printer_manager.get_printer(printer_id)
  7209. if printer_info:
  7210. await mqtt_relay.on_print_complete(
  7211. printer_id,
  7212. printer_info.name,
  7213. printer_info.serial_number,
  7214. data.get("filename", ""),
  7215. data.get("subtask_name", ""),
  7216. data.get("status", "completed"),
  7217. )
  7218. except Exception:
  7219. pass # Don't fail print complete callback if MQTT fails
  7220. filename = data.get("filename", "")
  7221. subtask_name = data.get("subtask_name", "")
  7222. if not filename and not subtask_name:
  7223. # Which print ended can't be told: the printer reported no name since
  7224. # Bambuddy started (a print that failed while preparing, a calibration).
  7225. # Charge nothing, but close the print session, which otherwise kept the
  7226. # AMS weight sync off until the next print (AS-5). A print archived as
  7227. # running is closed and charged by the reconnect reconcile.
  7228. logger.warning("Print complete without filename or subtask_name")
  7229. try:
  7230. from backend.app.services.usage_tracker import discard_session
  7231. async with async_session() as db:
  7232. await discard_session(db, printer_id)
  7233. except Exception as e:
  7234. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7235. return
  7236. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7237. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7238. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7239. # Find the archive for this print
  7240. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7241. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7242. archive_id = None
  7243. for key in possible_keys:
  7244. archive_id = _active_prints.pop(key, None)
  7245. if archive_id:
  7246. _owned_print_archive_ids.discard(archive_id)
  7247. logger.info("Found archive %s with key %s", archive_id, key)
  7248. # Also clean up any other keys pointing to this archive
  7249. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7250. for k in keys_to_remove:
  7251. _active_prints.pop(k, None)
  7252. break
  7253. # The archive bound when the print started, before the name search below.
  7254. # Only this one may give the finish-photo plate restore a height (#3240):
  7255. # the search matches names by substring.
  7256. bound_archive_id = archive_id
  7257. if not archive_id:
  7258. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7259. async with async_session() as db:
  7260. from backend.app.models.archive import PrintArchive
  7261. # Try matching by subtask_name (stored as print_name) first. The
  7262. # same name rule as the queue's completion check: a name inside
  7263. # another ("Clip" in "Cable Clip") is a different print, and the
  7264. # printer's underscores for spaces and truncation still match.
  7265. if subtask_name:
  7266. printing = await db.scalars(
  7267. select(PrintArchive)
  7268. .where(PrintArchive.printer_id == printer_id)
  7269. .where(PrintArchive.status == "printing")
  7270. .order_by(PrintArchive.created_at.desc())
  7271. )
  7272. # A print started from the printer's screen reports its file
  7273. # name, extensions included, as the subtask (#3009).
  7274. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7275. archive = next(
  7276. (
  7277. candidate
  7278. for candidate in printing
  7279. if any(
  7280. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7281. or (
  7282. candidate.filename
  7283. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7284. )
  7285. for name in reported
  7286. )
  7287. ),
  7288. None,
  7289. )
  7290. if archive:
  7291. archive_id = archive.id
  7292. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7293. # Also try by filename
  7294. if not archive_id and filename:
  7295. result = await db.execute(
  7296. select(PrintArchive)
  7297. .where(PrintArchive.printer_id == printer_id)
  7298. .where(PrintArchive.filename == filename)
  7299. .where(PrintArchive.status == "printing")
  7300. .order_by(PrintArchive.created_at.desc())
  7301. .limit(1)
  7302. )
  7303. archive = result.scalar_one_or_none()
  7304. if archive:
  7305. archive_id = archive.id
  7306. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7307. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7308. # closed below. The stranded-job closer gives up after five and closed it
  7309. # first, so the job's auto-off and its billing never ran. Inline rather
  7310. # than in the background, so the next job of the same file isn't released
  7311. # (and uploaded under the name being deleted) while the cleanup still
  7312. # works on it. A delete already sent may still finish in its FTP thread
  7313. # after the cutoff, as one past delete_file_async's own timeout always did.
  7314. try:
  7315. await asyncio.wait_for(
  7316. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7317. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7318. )
  7319. except TimeoutError:
  7320. logger.warning(
  7321. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7322. printer_id,
  7323. _SD_CLEANUP_BUDGET_SECONDS,
  7324. )
  7325. log_timing("SD card cleanup")
  7326. # Update queue item status early — must run before the archive_id early-return
  7327. # so queue items don't get stuck in "printing" when archive lookup fails.
  7328. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7329. queue_item_id = None
  7330. billing_run_id: str | None = None
  7331. billing_user_id: int | None = None
  7332. billing_cost_center_id: int | None = None
  7333. billing_plate_id: int | None = None
  7334. queue_status = None
  7335. queue_auto_off = False
  7336. try:
  7337. from backend.app.core.database import run_with_retry
  7338. from backend.app.models.print_queue import PrintQueueItem
  7339. async def _update_queue_status(db):
  7340. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7341. nonlocal queue_item_id, queue_status, queue_auto_off
  7342. result = await db.execute(
  7343. select(PrintQueueItem)
  7344. .where(PrintQueueItem.printer_id == printer_id)
  7345. .where(PrintQueueItem.status == "printing")
  7346. )
  7347. printing_items = list(result.scalars().all())
  7348. if len(printing_items) > 1:
  7349. logger.warning(
  7350. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7351. printer_id,
  7352. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7353. )
  7354. item = printing_items[0] if printing_items else None
  7355. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7356. return
  7357. if item:
  7358. queue_status = data.get("status", "completed")
  7359. # MQTT sends "aborted" for cancelled prints; normalise to
  7360. # "cancelled" so it matches the queue schema Literal.
  7361. if queue_status == "aborted":
  7362. queue_status = "cancelled"
  7363. item.status = queue_status
  7364. item.completed_at = datetime.now(timezone.utc)
  7365. if queue_status == "failed" and not item.error_message:
  7366. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7367. # Bump usage counters on the source library file so admins can
  7368. # sort by "last printed" and (eventually) auto-purge stale
  7369. # files — #1008.
  7370. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7371. await db.commit()
  7372. queue_item_id = item.id
  7373. billing_run_id = item.billing_run_id
  7374. billing_user_id = item.created_by_id
  7375. billing_cost_center_id = item.cost_center_id
  7376. billing_plate_id = item.plate_id
  7377. queue_auto_off = item.auto_off_after
  7378. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7379. await run_with_retry(_update_queue_status, label="queue status update")
  7380. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7381. # their own sessions and have their own error handling — no retry needed.
  7382. if queue_item_id is not None:
  7383. # Batch orders (#342): this run may have been the last one an order
  7384. # owed. Re-evaluate here rather than lazily on read, so a finished
  7385. # order reports itself complete without someone opening the page.
  7386. try:
  7387. from backend.app.services.print_batch import refresh_batch_status_for_item
  7388. async with async_session() as db:
  7389. await refresh_batch_status_for_item(db, queue_item_id)
  7390. await db.commit()
  7391. except Exception as e:
  7392. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7393. # MQTT relay - publish queue job completed
  7394. try:
  7395. printer_info = printer_manager.get_printer(printer_id)
  7396. await mqtt_relay.on_queue_job_completed(
  7397. job_id=queue_item_id,
  7398. filename=filename or subtask_name,
  7399. printer_id=printer_id,
  7400. printer_name=printer_info.name if printer_info else "Unknown",
  7401. status=queue_status,
  7402. )
  7403. except Exception:
  7404. pass # Don't fail if MQTT fails
  7405. # Check if queue is now empty and send notification
  7406. try:
  7407. from sqlalchemy import func as sa_func
  7408. async with async_session() as db:
  7409. count_result = await db.execute(
  7410. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7411. )
  7412. pending_count = count_result.scalar() or 0
  7413. if pending_count == 0:
  7414. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7415. completed_result = await db.execute(
  7416. select(sa_func.count(PrintQueueItem.id)).where(
  7417. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7418. PrintQueueItem.completed_at >= today_start,
  7419. )
  7420. )
  7421. completed_count = completed_result.scalar() or 1
  7422. await notification_service.on_queue_completed(
  7423. completed_count=completed_count,
  7424. db=db,
  7425. )
  7426. except Exception:
  7427. pass # Don't fail if notification fails
  7428. # Handle auto_off_after - power off printer if the queue item opted
  7429. # in. Delegates to the smart-plug manager so the off honours each
  7430. # plug's configured strategy (time delay or temperature threshold),
  7431. # is cancelled if the printer starts printing again, and never cuts
  7432. # power on a loaded print (#1890). Previously an inline block here
  7433. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7434. # timeout regardless of print state — cutting a touchscreen reprint.
  7435. if queue_auto_off:
  7436. try:
  7437. async with async_session() as db:
  7438. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7439. except Exception as e:
  7440. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7441. except Exception as e:
  7442. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7443. log_timing("Queue item update")
  7444. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7445. # Must run before archive_id early-return so it fires for all prints (including
  7446. # prints started from BambuStudio/touchscreen that have no archive).
  7447. if data.get("status") == "completed":
  7448. try:
  7449. from backend.app.api.routes.settings import get_setting
  7450. async with async_session() as db:
  7451. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7452. threshold = float(threshold_str) if threshold_str else 35.0
  7453. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7454. async with async_session() as db:
  7455. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7456. if providers:
  7457. _bed_cool_waiters[printer_id] = {
  7458. "threshold": threshold,
  7459. "filename": filename or subtask_name or "",
  7460. "registered_at": time.time(),
  7461. }
  7462. logger.info(
  7463. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7464. printer_id,
  7465. threshold,
  7466. )
  7467. else:
  7468. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7469. except Exception as e:
  7470. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7471. # Capture the slicer estimate before usage tracking runs. The tracker may
  7472. # update archive.cost with this run's measured cost; billing partial runs
  7473. # against that already-partial value would discount the charge twice.
  7474. billing_planned_grams: float | None = None
  7475. billing_base_cost: float | None = None
  7476. if archive_id:
  7477. try:
  7478. async with async_session() as db:
  7479. from backend.app.models.archive import PrintArchive
  7480. billing_archive = await db.get(PrintArchive, archive_id)
  7481. if billing_archive:
  7482. billing_path = (
  7483. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7484. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7485. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7486. billing_archive,
  7487. billing_path,
  7488. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7489. )
  7490. except Exception as e:
  7491. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7492. # --- Track filament consumption (must run before archive_id early-return so usage
  7493. # is recorded even when auto-archive is disabled) ---
  7494. usage_results: list[dict] = []
  7495. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7496. stored_ams_mapping = data.get("ams_mapping")
  7497. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  7498. # Drained either way, like the plate below: left over, it would be read by
  7499. # the archive's next run, dispatched without a mapping.
  7500. registered_ams_mapping = _print_ams_mappings.pop(archive_id, None) if archive_id else None
  7501. if not stored_ams_mapping:
  7502. stored_ams_mapping = registered_ams_mapping
  7503. # Always drain the plate_id register on completion — the session already
  7504. # consumed it at print-start injection; leaving it would leak into the next
  7505. # print on the same archive_id (rare but possible with reprints) (#1697).
  7506. # Capture the popped value so the completion notification can scope the
  7507. # archive-level (summed-across-plates per #1593) filament + time totals
  7508. # down to the single plate that was actually printed (#1785).
  7509. notify_plate_id: int | None = None
  7510. if archive_id:
  7511. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7512. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7513. try:
  7514. async with async_session() as db:
  7515. from backend.app.api.routes.settings import get_setting
  7516. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7517. if not _spoolman_on or _spoolman_on.lower() != "true":
  7518. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7519. async with async_session() as db:
  7520. usage_results = await usage_on_print_complete(
  7521. printer_id,
  7522. data,
  7523. printer_manager,
  7524. db,
  7525. archive_id=archive_id,
  7526. ams_mapping=stored_ams_mapping,
  7527. )
  7528. if usage_results:
  7529. await ws_manager.broadcast(
  7530. {
  7531. "type": "spool_usage_logged",
  7532. "printer_id": printer_id,
  7533. "usage": usage_results,
  7534. }
  7535. )
  7536. log_timing("Usage tracker")
  7537. except Exception as e:
  7538. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7539. # Drop the print-start context unconditionally — the Spoolman branch above
  7540. # skips the internal tracker entirely, so nothing else would clear what
  7541. # print start captured, and a row surviving its print would be restored
  7542. # onto the next one after a restart.
  7543. try:
  7544. from backend.app.services.usage_tracker import discard_session
  7545. async with async_session() as db:
  7546. await discard_session(db, printer_id)
  7547. except Exception as e:
  7548. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7549. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7550. # A partial run's cost from the Spoolman spools it was charged to; the
  7551. # built-in inventory's comes in usage_results.
  7552. spoolman_run_cost: float | None = None
  7553. if archive_id:
  7554. if data.get("status") == "completed":
  7555. try:
  7556. await _report_spoolman_usage(printer_id, archive_id)
  7557. log_timing("Spoolman usage report")
  7558. except Exception as e:
  7559. logger.warning("Spoolman usage reporting failed: %s", e)
  7560. else:
  7561. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7562. try:
  7563. async with async_session() as db:
  7564. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7565. printer_id,
  7566. archive_id,
  7567. db,
  7568. last_layer_num=data.get("last_layer_num"),
  7569. last_progress=data.get("last_progress"),
  7570. )
  7571. except Exception as e:
  7572. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7573. await _release_archived_spoolman_slots(printer_id)
  7574. log_timing("Filament usage tracking")
  7575. if not archive_id:
  7576. # The printer's own calibration run has no archive by design, so this
  7577. # arrives here every time one finishes. Returning before the no-archive
  7578. # notification keeps a calibration from being announced as a finished
  7579. # print. Everything above this point has already run — the plate-clear
  7580. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7581. # notification is skipped.
  7582. if is_internal_printer_job(filename, subtask_name):
  7583. logger.info(
  7584. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7585. filename,
  7586. subtask_name,
  7587. )
  7588. return
  7589. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7590. # Still send print-complete/failed/stopped notifications even without an archive.
  7591. # Try to enrich with queue/library-file data so user-specific emails work too.
  7592. async def _notify_no_archive():
  7593. try:
  7594. async with async_session() as db:
  7595. from backend.app.models.library import LibraryFile
  7596. from backend.app.models.print_queue import PrintQueueItem
  7597. from backend.app.models.printer import Printer
  7598. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7599. printer_obj = result.scalar_one_or_none()
  7600. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7601. # Only the queue item this completion itself closed (the
  7602. # reconciliation above, which checks the run belongs to it).
  7603. # A print started outside Bambuddy closed none, and must not
  7604. # borrow an earlier job's owner, email or times.
  7605. no_archive_data: dict | None = None
  7606. try:
  7607. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7608. if queue_item:
  7609. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7610. # How long it really ran, as the archive path reports it (#1198).
  7611. started = to_naive_utc(queue_item.started_at)
  7612. ended = to_naive_utc(queue_item.completed_at)
  7613. # Not for a completion reconciled at reconnect: it
  7614. # ended at an unknown time while the printer was
  7615. # offline, and "now" is the reconnect (DB-C9).
  7616. if (
  7617. not data.get("_reconciled")
  7618. and started
  7619. and ended
  7620. and (ended - started).total_seconds() > 0
  7621. ):
  7622. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7623. # Estimated time: the queue item caches it from its
  7624. # archive or library file; otherwise read the library
  7625. # file's metadata (LibraryFile has no column for it).
  7626. if queue_item.print_time_seconds:
  7627. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7628. elif queue_item.library_file_id:
  7629. lib_result = await db.execute(
  7630. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7631. )
  7632. lib_file = lib_result.scalar_one_or_none()
  7633. estimate = (
  7634. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7635. )
  7636. if estimate:
  7637. no_archive_data["print_time_seconds"] = estimate
  7638. except Exception as lookup_err:
  7639. logger.debug(
  7640. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7641. )
  7642. # Enrich with usage tracker results (captured in enclosing scope)
  7643. if usage_results:
  7644. if no_archive_data is None:
  7645. no_archive_data = {}
  7646. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7647. if total_from_usage > 0:
  7648. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7649. no_archive_data["usage_results"] = usage_results
  7650. # Try MQTT remaining_time for print duration when no queue/library data
  7651. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7652. mqtt_remaining = data.get("remaining_time")
  7653. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7654. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7655. ps = data.get("status", "completed")
  7656. logger.info(
  7657. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7658. )
  7659. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7660. await notification_service.on_print_complete(
  7661. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7662. )
  7663. else:
  7664. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7665. # Send user-specific email if we have a created_by_id
  7666. if no_archive_data and no_archive_data.get("created_by_id"):
  7667. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7668. await _dispatch_user_print_email(
  7669. ps,
  7670. no_archive_data["created_by_id"],
  7671. p_name,
  7672. raw_filename,
  7673. db,
  7674. )
  7675. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7676. except Exception as e:
  7677. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7678. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7679. return
  7680. log_timing("Archive lookup")
  7681. # Update archive status
  7682. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7683. try:
  7684. async with async_session() as db:
  7685. service = ArchiveService(db)
  7686. status = data.get("status", "completed")
  7687. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7688. if hms_errors:
  7689. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7690. failure_reason = derive_failure_reason(status, hms_errors)
  7691. if data.get("_reconciled"):
  7692. # A reconciled completion closes out a stale archive at
  7693. # reconnect — it is not a user action, so don't mislabel it
  7694. # "userCancelled". It shares the stale-cleanup path's key
  7695. # (issue #2974) and records that the real end time is unknown,
  7696. # which is also why its logged duration is 0 (#2592).
  7697. failure_reason = "noStatusUpdate"
  7698. elif data.get("_kill_switch"):
  7699. # Not the user's cancel: the kill switch stopped a print that did
  7700. # not come from Bambuddy.
  7701. failure_reason = "killSwitch"
  7702. if failure_reason:
  7703. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7704. elif status == "failed" and hms_errors:
  7705. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7706. await service.update_archive_status(
  7707. archive_id,
  7708. status=status,
  7709. completed_at=(
  7710. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7711. ),
  7712. failure_reason=failure_reason,
  7713. )
  7714. logger.info(
  7715. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7716. )
  7717. await ws_manager.send_archive_updated(
  7718. {
  7719. "id": archive_id,
  7720. "status": status,
  7721. }
  7722. )
  7723. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7724. # MQTT relay - publish archive updated
  7725. try:
  7726. await mqtt_relay.on_archive_updated(
  7727. archive_id=archive_id,
  7728. print_name=filename or subtask_name,
  7729. status=status,
  7730. )
  7731. except Exception:
  7732. pass # Don't fail if MQTT fails
  7733. except Exception as e:
  7734. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7735. # Continue with other operations even if archive update fails
  7736. log_timing("Archive status update")
  7737. # Apply finance wallet charge or release reservations once. For all partial
  7738. # terminal states (failed, aborted at the printer display, or cancelled via
  7739. # Bambuddy) use this run's measured spool delta, falling back to the last
  7740. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7741. # estimate and therefore cannot represent an interrupted run.
  7742. try:
  7743. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7744. async with async_session() as db:
  7745. from backend.app.models.archive import PrintArchive
  7746. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7747. archive = await db.get(PrintArchive, archive_id)
  7748. if archive and billing_run_id is None:
  7749. billing_run_id = getattr(archive, "billing_run_id", None)
  7750. if archive and archive.created_by_id is None and _print_user_info:
  7751. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7752. await db.flush()
  7753. run_status = data.get("status", "completed")
  7754. last_progress = data.get("last_progress")
  7755. if last_progress is None:
  7756. last_progress = data.get("progress")
  7757. actual_run_grams = _compute_run_filament_grams(
  7758. run_status,
  7759. billing_planned_grams,
  7760. last_progress,
  7761. usage_results,
  7762. )
  7763. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7764. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7765. charged = await apply_print_charge_for_archive(
  7766. db,
  7767. archive_id,
  7768. charged_user_id=billing_user_id,
  7769. cost_center_id=(
  7770. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7771. ),
  7772. print_queue_id=queue_item_id,
  7773. print_run_id=billing_run_id,
  7774. base_cost_override=billing_base_cost,
  7775. filament_usage=filament_usage,
  7776. )
  7777. await db.commit()
  7778. if charged:
  7779. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7780. except Exception as e:
  7781. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7782. printer_info = printer_manager.get_printer(printer_id)
  7783. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7784. billing_filename = filename or subtask_name or "Unknown"
  7785. billing_error = str(e)
  7786. try:
  7787. await ws_manager.broadcast(
  7788. {
  7789. "type": "billing_charge_failed",
  7790. "printer_id": printer_id,
  7791. "printer_name": billing_printer_name,
  7792. "filename": billing_filename,
  7793. "archive_id": archive_id,
  7794. }
  7795. )
  7796. except Exception as notification_error:
  7797. logger.error(
  7798. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7799. archive_id,
  7800. notification_error,
  7801. )
  7802. async def _notify_billing_charge_failed() -> None:
  7803. try:
  7804. async with async_session() as notification_db:
  7805. await notification_service.on_billing_charge_failed(
  7806. printer_id,
  7807. billing_printer_name,
  7808. billing_filename,
  7809. archive_id,
  7810. billing_error,
  7811. notification_db,
  7812. )
  7813. except Exception as provider_error:
  7814. logger.error(
  7815. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7816. archive_id,
  7817. provider_error,
  7818. exc_info=True,
  7819. )
  7820. spawn_background_task(
  7821. _notify_billing_charge_failed(),
  7822. name=f"billing-charge-failed-{archive_id}",
  7823. )
  7824. log_timing("Finance charge update")
  7825. # Write independent print log entry (separate table, never touches archives)
  7826. try:
  7827. async with async_session() as db:
  7828. from backend.app.models.archive import PrintArchive
  7829. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7830. archive = await db.get(PrintArchive, archive_id)
  7831. if archive:
  7832. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7833. # source archive row rather than creating a new one, so an
  7834. # archive that was auto-created from a printer-initiated
  7835. # print (created_by_id=NULL) would otherwise stay unattributed
  7836. # forever. When we have a print-session user AND the archive
  7837. # has no attribution yet, credit the current user. Never
  7838. # overwrite an existing attribution — the original uploader
  7839. # keeps ownership.
  7840. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7841. if archive.created_by_id is None and _print_user_id is not None:
  7842. archive.created_by_id = _print_user_id
  7843. p_info = printer_manager.get_printer(printer_id)
  7844. # Per-run actuals — written to PrintLogEntry so stats reflect
  7845. # what THIS print actually used, not the source archive's
  7846. # first-run values (#1378). Helper handles the partial-print
  7847. # math (failed / cancelled / stopped get scaled to progress
  7848. # or to tracked spool deltas).
  7849. _run_status = data.get("status", "completed")
  7850. # #2614: scope the per-run estimate to the printed plate. For a
  7851. # multi-plate 3MF dispatched one plate at a time, the archive's
  7852. # filament/cost are the whole-file totals; the PrintLogEntry must
  7853. # reflect only this plate. No effect on single-plate archives (the
  7854. # plate estimate equals the whole-file value) or on the tracker
  7855. # path (measured spool deltas win in _compute_run_filament_grams).
  7856. _est_full_path = (
  7857. app_settings.base_dir / archive.file_path if archive.file_path else None
  7858. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7859. # The plate that printed, as billing reads it: a reprint of
  7860. # another plate must not log the archive's first plate.
  7861. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7862. archive,
  7863. _est_full_path,
  7864. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7865. )
  7866. _run_grams = _compute_run_filament_grams(
  7867. _run_status,
  7868. _est_grams,
  7869. data.get("last_progress", data.get("progress")),
  7870. usage_results,
  7871. )
  7872. # Per-run cost — prefer usage_results sum. For partial prints
  7873. # we deliberately skip the topup-to-estimate logic in
  7874. # usage_tracker (which assumes the print completed); the raw
  7875. # tracked-spool sum is closer to what THIS run actually cost.
  7876. _run_cost: float | None = None
  7877. if usage_results:
  7878. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7879. if _run_cost is None and _run_status != "completed":
  7880. _run_cost = spoolman_run_cost
  7881. if _run_cost is None and _run_status == "completed":
  7882. _run_cost = _est_cost
  7883. from backend.app.models.printer import Printer as _Printer
  7884. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7885. run_entry = await write_log_entry(
  7886. db,
  7887. archive_id=archive.id,
  7888. # Captured by _update_queue_status above; None for
  7889. # printer-initiated prints with no queue row. Batch
  7890. # cost/energy roll-up joins on it (#342).
  7891. queue_item_id=queue_item_id,
  7892. status=_run_status,
  7893. print_name=archive.print_name,
  7894. printer_name=p_info.name if p_info else None,
  7895. printer_id=printer_id,
  7896. started_at=archive.started_at,
  7897. completed_at=archive.completed_at,
  7898. filament_type=archive.filament_type,
  7899. filament_color=archive.filament_color,
  7900. filament_used_grams=_run_grams,
  7901. cost=_run_cost,
  7902. wear_cost_per_hour=_wear_rate,
  7903. failure_reason=archive.failure_reason,
  7904. thumbnail_path=archive.thumbnail_path,
  7905. created_by_id=archive.created_by_id,
  7906. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7907. # Reconciled completions have an unknown real end time —
  7908. # log 0 duration instead of the whole disconnect gap (#2592).
  7909. reconciled=bool(data.get("_reconciled")),
  7910. )
  7911. await record_archive_wear(db, archive, run_entry)
  7912. await db.commit()
  7913. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7914. except Exception as e:
  7915. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7916. log_timing("Print log entry")
  7917. # Run slow operations as background tasks to avoid blocking the event loop
  7918. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7919. async def _background_energy_calculation():
  7920. """Calculate and save energy usage in background.
  7921. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7922. backend restart no longer loses per-print energy data).
  7923. """
  7924. try:
  7925. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7926. async with async_session() as db:
  7927. from backend.app.models.archive import PrintArchive
  7928. archive = await db.get(PrintArchive, archive_id)
  7929. if archive is None:
  7930. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7931. return
  7932. starting_kwh = archive.energy_start_kwh
  7933. if starting_kwh is None:
  7934. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7935. return
  7936. candidates = await energy_plug_candidates(db, printer_id)
  7937. if not candidates:
  7938. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7939. return
  7940. # Same ordering as the start reading, so the delta below is
  7941. # against the counter that produced `starting_kwh` (#2859).
  7942. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7943. if selected is None:
  7944. logger.warning(
  7945. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7946. printer_id,
  7947. ", ".join(plug.name for plug in candidates),
  7948. )
  7949. return
  7950. plug, energy = selected
  7951. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7952. energy_used = round(energy["total"] - starting_kwh, 4)
  7953. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7954. if energy_used < 0:
  7955. logger.warning(
  7956. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7957. archive_id,
  7958. starting_kwh,
  7959. energy["total"],
  7960. )
  7961. return
  7962. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7963. # Each hour of the print at the price of that hour (#1251). If
  7964. # that fails, the last price known, as before, rather than no
  7965. # energy at all. Read first: the session may be unusable after.
  7966. last_price = await stored_price(db)
  7967. try:
  7968. energy_cost_value = round(
  7969. await print_energy_cost(
  7970. db,
  7971. plug_id=archive.energy_start_plug_id,
  7972. start_at=archive.energy_start_at,
  7973. start_kwh=starting_kwh,
  7974. start_price=archive.energy_start_price,
  7975. end_kwh=energy["total"],
  7976. end_plug_id=plug.id,
  7977. price_now=await current_price(db),
  7978. ),
  7979. 3,
  7980. )
  7981. except Exception as e:
  7982. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7983. energy_cost_value = round(energy_used * last_price, 3)
  7984. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7985. # reprint doesn't visually clobber the source archive's energy data
  7986. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7987. from sqlalchemy import func
  7988. from backend.app.models.print_log import PrintLogEntry
  7989. existing_runs = await db.scalar(
  7990. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7991. )
  7992. if (existing_runs or 0) <= 1:
  7993. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7994. # we just wrote for THIS print. Either way it's the first run.
  7995. archive.energy_kwh = energy_used
  7996. archive.energy_cost = energy_cost_value
  7997. # Backfill the latest PrintLogEntry for this archive with energy
  7998. # (write_log_entry above ran before this background task completed,
  7999. # so energy fields are still NULL on that row).
  8000. latest_run = await db.execute(
  8001. select(PrintLogEntry)
  8002. .where(PrintLogEntry.archive_id == archive_id)
  8003. .order_by(PrintLogEntry.id.desc())
  8004. .limit(1)
  8005. )
  8006. run_row = latest_run.scalar_one_or_none()
  8007. if run_row is not None:
  8008. run_row.energy_kwh = energy_used
  8009. run_row.energy_cost = energy_cost_value
  8010. await db.commit()
  8011. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8012. except Exception as e:
  8013. logger.warning("[ENERGY-BG] Failed: %s", e)
  8014. async def _background_finish_photo() -> str | None:
  8015. """Capture finish photo in background. Returns photo filename if captured."""
  8016. # #2547: set once this function has raised the plate itself (the
  8017. # timelapse path, where the moment producer returned without doing it).
  8018. # Declared out here so the `finally` can lower it again no matter where
  8019. # the capture below fails.
  8020. plate_restored_z: float | None = None
  8021. try:
  8022. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8023. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8024. # Read phase: settings + printer + archive in a short session, released
  8025. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8026. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8027. # tens of seconds; holding this session across it pinned one pooled
  8028. # connection idle-in-transaction per finishing print (issue #2572).
  8029. async with async_session() as db:
  8030. from backend.app.api.routes.settings import get_setting
  8031. from backend.app.models.archive import PrintArchive
  8032. from backend.app.models.printer import Printer
  8033. capture_enabled = await get_setting(db, "capture_finish_photo")
  8034. if capture_enabled is not None and capture_enabled.lower() != "true":
  8035. return None
  8036. if not archive_id:
  8037. return None
  8038. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8039. archive = (
  8040. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8041. ).scalar_one_or_none()
  8042. if not printer or not archive:
  8043. return None
  8044. import uuid
  8045. from datetime import datetime
  8046. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8047. if not archive.file_path:
  8048. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8049. archive_dir = resolve_archive_dir(archive)
  8050. photo_filename = None
  8051. # Prefer the timelapse last-frame source when a timelapse was
  8052. # recording — it captures the moment after the toolhead parks
  8053. # but before the bed drops, which the live-camera grab below
  8054. # would miss (#1397). Skipped for external cameras (those have
  8055. # their own framing and don't see a Bambu timelapse). Only
  8056. # runs when the USER explicitly enabled timelapse for this
  8057. # print — #1721 removed Bambuddy's force-on at dispatch
  8058. # because it caused per-layer nozzle parking on Smooth-mode
  8059. # slicer profiles.
  8060. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8061. printer.external_camera_enabled and printer.external_camera_url
  8062. )
  8063. timelapse_still_pending = False
  8064. if prefer_timelapse_source:
  8065. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8066. archive_id=archive_id,
  8067. archive_dir=archive_dir,
  8068. rotation=getattr(printer, "camera_rotation", 0),
  8069. )
  8070. # #1721: replacement framing path — on_finish_photo_moment
  8071. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8072. # parked, bed not yet dropped) and cached the JPEG bytes in
  8073. # _stage22_finish_frames. Consume them now so the saved photo
  8074. # has the better framing instead of the post-bed-drop angle
  8075. # the live-camera fallback below would give.
  8076. if not photo_filename:
  8077. # #1790: on the FINISH-state fallback path the producer
  8078. # task is dispatched back-to-back with this consumer, so
  8079. # a bare pop would race past with an empty result and
  8080. # the RTSP fallback below would collide with the
  8081. # producer's still-in-flight grab (single-client RTSP
  8082. # on Bambu printers). Wait for the producer to finish
  8083. # or give up before touching the cache.
  8084. #
  8085. # #2547: 20s was enough when the producer only ever grabbed a
  8086. # frame. It now also raises the plate first, which costs the
  8087. # settle window before the grab even starts — so the budget has
  8088. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8089. # under the notification's own photo wait below.
  8090. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8091. if in_flight is not None:
  8092. try:
  8093. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8094. except TimeoutError:
  8095. logger.warning(
  8096. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8097. printer_id,
  8098. )
  8099. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8100. if cached_frame:
  8101. # Already rotated by the producer (#2708) — rotating again
  8102. # here would undo the fix on the banked-frame path, whose
  8103. # bytes reach the cache having been rotated once already.
  8104. photos_dir = archive_dir / "photos"
  8105. photos_dir.mkdir(parents=True, exist_ok=True)
  8106. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8107. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8108. photo_path = photos_dir / photo_filename
  8109. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8110. logger.info(
  8111. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8112. photo_filename,
  8113. len(cached_frame),
  8114. )
  8115. # #2547: the timelapse path reaches the live grab below whenever the
  8116. # video hasn't landed in time — the documented usual outcome on
  8117. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8118. # returned early for those prints without raising the plate, so
  8119. # without this the photo that actually ships in the notification is
  8120. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8121. # asked us to fix. The archive still gets the better video frame
  8122. # later; this is about the image the user is sent.
  8123. #
  8124. # Gated on `timelapse_was_active` precisely because that is the
  8125. # condition under which the producer skipped. On every other path it
  8126. # has already raised and lowered the plate, and repeating that here
  8127. # would be a second pointless round trip.
  8128. if (
  8129. not photo_filename
  8130. and data.get("timelapse_was_active")
  8131. and not print_dispatch_context.end_gcode_injected(printer_id)
  8132. ):
  8133. try:
  8134. async with async_session() as db:
  8135. from backend.app.api.routes.settings import get_setting
  8136. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8137. if restore_setting is None or restore_setting.lower() == "true":
  8138. max_z = await _max_z_for_current_print(
  8139. printer_id, data, logger, bound_archive_id, notify_plate_id
  8140. )
  8141. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8142. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8143. plate_restored_z = max_z
  8144. except Exception as e:
  8145. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8146. # Fallback chain: external camera → buffered live frame →
  8147. # fresh RTSP capture. Only runs if the timelapse path above
  8148. # didn't already produce a photo.
  8149. # Chamber light for the live capture below (#1655).
  8150. async with camera_light(printer if not photo_filename else None):
  8151. if not photo_filename:
  8152. if printer.external_camera_enabled and printer.external_camera_url:
  8153. logger.info("[PHOTO-BG] Using external camera")
  8154. from backend.app.api.routes.camera import live_frame_for_capture
  8155. from backend.app.services.external_camera import capture_frame
  8156. # #2707: the second half of the finish-photo failure — the
  8157. # pre-capture and this fallback both collided with the live
  8158. # view. None here continues down the fallback chain.
  8159. defer, buffered = live_frame_for_capture(printer_id)
  8160. if defer:
  8161. frame_data = buffered
  8162. else:
  8163. frame_data = await capture_frame(
  8164. printer.external_camera_url,
  8165. printer.external_camera_type or "mjpeg",
  8166. snapshot_url=printer.external_camera_snapshot_url,
  8167. )
  8168. if frame_data:
  8169. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8170. photos_dir = archive_dir / "photos"
  8171. photos_dir.mkdir(parents=True, exist_ok=True)
  8172. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8173. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8174. photo_path = photos_dir / photo_filename
  8175. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8176. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8177. else:
  8178. # Check if camera stream is active - use buffered frame to avoid freeze
  8179. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8180. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8181. active_chamber_for_printer = [
  8182. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8183. ]
  8184. buffered_frame = get_buffered_frame(printer_id)
  8185. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8186. # Use frame from active stream
  8187. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8188. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8189. photos_dir = archive_dir / "photos"
  8190. photos_dir.mkdir(parents=True, exist_ok=True)
  8191. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8192. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8193. photo_path = photos_dir / photo_filename
  8194. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8195. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8196. else:
  8197. # No active stream - capture new frame
  8198. from backend.app.services.camera import capture_finish_photo
  8199. photo_filename = await capture_finish_photo(
  8200. printer_id=printer_id,
  8201. ip_address=printer.ip_address,
  8202. access_code=printer.access_code,
  8203. model=printer.model,
  8204. archive_dir=archive_dir,
  8205. rotation=getattr(printer, "camera_rotation", 0),
  8206. )
  8207. # Write phase: attach the photo in a fresh short-lived session.
  8208. if photo_filename:
  8209. async with async_session() as db:
  8210. from backend.app.models.archive import PrintArchive
  8211. arch = await db.get(PrintArchive, archive_id)
  8212. if arch is not None:
  8213. photos = arch.photos or []
  8214. photos.append(photo_filename)
  8215. arch.photos = photos
  8216. await db.commit()
  8217. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8218. # The short wait above is bounded so a slow printer can't hold up
  8219. # the print-complete notification, which is what the caller is
  8220. # blocking on. When it ran out with the video still on its way,
  8221. # keep waiting off to the side and add the better frame to the
  8222. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8223. # users, whose videos routinely take minutes to transfer, never get
  8224. # the pre-bed-drop framing this path exists to provide.
  8225. #
  8226. # Spawned here rather than at the point the wait gave up: both this
  8227. # function and the upgrade do a read-modify-write on `photos`, and
  8228. # the live-camera fallback above can take tens of seconds. Starting
  8229. # the upgrade before that write means the two can interleave and one
  8230. # silently drops the other's entry, leaving a JPEG on disk that the
  8231. # gallery never lists.
  8232. if timelapse_still_pending:
  8233. spawn_background_task(
  8234. _upgrade_finish_photo_from_timelapse(
  8235. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8236. ),
  8237. name=f"finish-photo-upgrade-{archive_id}",
  8238. )
  8239. return photo_filename
  8240. except Exception as e:
  8241. logger.warning("[PHOTO-BG] Failed: %s", e)
  8242. return None
  8243. finally:
  8244. # #2547: we raised the plate, so we owe the move back down — even if
  8245. # the capture in between threw. Otherwise the user finds the print
  8246. # pinned under the nozzle.
  8247. if plate_restored_z is not None:
  8248. try:
  8249. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8250. except Exception as e:
  8251. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8252. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8253. # Photo capture task - result will be used by notifications
  8254. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8255. log_timing("Background tasks scheduled (energy, photo)")
  8256. # Also run smart plug, notifications, and maintenance as background tasks
  8257. print_status = data.get("status", "completed")
  8258. async def _background_smart_plug():
  8259. """Handle smart plug automation in background."""
  8260. try:
  8261. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8262. async with async_session() as db:
  8263. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8264. logger.info("[AUTO-OFF-BG] Completed")
  8265. except Exception as e:
  8266. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8267. async def _background_notifications(finish_photo_filename: str | None = None):
  8268. """Send print complete notifications in background."""
  8269. try:
  8270. logger.info(
  8271. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8272. )
  8273. async with async_session() as db:
  8274. from backend.app.models.archive import PrintArchive
  8275. from backend.app.models.printer import Printer
  8276. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8277. printer = result.scalar_one_or_none()
  8278. printer_name = printer.name if printer else f"Printer {printer_id}"
  8279. archive_data = None
  8280. if archive_id:
  8281. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8282. archive = archive_result.scalar_one_or_none()
  8283. if archive:
  8284. # Actual elapsed time from started_at/completed_at when both are
  8285. # populated (every terminal status sets completed_at after #1198).
  8286. # Falls back to None so the notification path can decide whether to
  8287. # render the slicer estimate as a last resort.
  8288. actual_time_seconds = None
  8289. # Unknown for a completion reconciled at reconnect: the
  8290. # print ended while the printer was offline and
  8291. # completed_at is the reconnect, so the gap would read
  8292. # as the duration -- 14 h for a night offline (DB-C9).
  8293. if archive.started_at and archive.completed_at and not data.get("_reconciled"):
  8294. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8295. if elapsed > 0:
  8296. actual_time_seconds = int(elapsed)
  8297. archive_data = {
  8298. "print_time_seconds": archive.print_time_seconds,
  8299. "actual_time_seconds": actual_time_seconds,
  8300. "actual_filament_grams": archive.filament_used_grams,
  8301. "failure_reason": archive.failure_reason,
  8302. "created_by_id": archive.created_by_id,
  8303. }
  8304. # Scale filament usage for partial prints
  8305. if print_status != "completed" and archive.filament_used_grams:
  8306. progress = data.get("progress") or 0
  8307. scale = _partial_progress_scale(progress)
  8308. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8309. archive_data["progress"] = progress
  8310. # Pass per-slot data from archive.extra_data
  8311. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8312. slots = archive.extra_data["filament_slots"]
  8313. if print_status != "completed":
  8314. scale = _partial_progress_scale(data.get("progress"))
  8315. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8316. archive_data["filament_slots"] = slots
  8317. # Scope project-summed totals down to the plate that was
  8318. # actually printed — see _scope_notification_archive_data_to_plate
  8319. # for the why (#1785).
  8320. archive_data = _scope_notification_archive_data_to_plate(
  8321. archive_data,
  8322. archive.file_path,
  8323. notify_plate_id,
  8324. print_status,
  8325. data.get("progress"),
  8326. app_settings.base_dir,
  8327. )
  8328. # Enrich filament_grams from usage_results when archive has no 3MF data
  8329. if not archive_data.get("actual_filament_grams") and usage_results:
  8330. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8331. if total_from_usage > 0:
  8332. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8333. # Pass usage tracker results for AMS slot info in notifications
  8334. if usage_results:
  8335. archive_data["usage_results"] = usage_results
  8336. # Add finish photo URL and image bytes if available
  8337. if finish_photo_filename:
  8338. photo_url, photo_bytes = await _finish_photo_for_notification(
  8339. db, archive, archive_id, finish_photo_filename
  8340. )
  8341. if photo_url:
  8342. archive_data["finish_photo_url"] = photo_url
  8343. if photo_bytes:
  8344. archive_data["image_data"] = photo_bytes
  8345. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8346. await notification_service.on_print_complete(
  8347. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8348. )
  8349. else:
  8350. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8351. # Post-print outcome confirmation (#1898). Runs in this
  8352. # background task so the finish photo fetched above rides
  8353. # along with the prompt.
  8354. if print_status == "completed" and archive_id:
  8355. await _dispatch_outcome_confirmation_safely(
  8356. db, printer_id, printer_name, data, archive_id, archive_data
  8357. )
  8358. # Send user-specific email notification
  8359. if archive_data:
  8360. created_by_id = archive_data.get("created_by_id")
  8361. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8362. await _dispatch_user_print_email(
  8363. print_status,
  8364. created_by_id,
  8365. printer_name,
  8366. raw_filename,
  8367. db,
  8368. image_data=archive_data.get("image_data"),
  8369. finish_photo_url=archive_data.get("finish_photo_url"),
  8370. )
  8371. logger.info("[NOTIFY-BG] Completed")
  8372. except Exception as e:
  8373. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8374. async def _background_maintenance_check():
  8375. """Check for maintenance due in background."""
  8376. if print_status != "completed":
  8377. return
  8378. try:
  8379. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8380. async with async_session() as db:
  8381. from backend.app.models.printer import Printer
  8382. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8383. printer = result.scalar_one_or_none()
  8384. printer_name = printer.name if printer else f"Printer {printer_id}"
  8385. await ensure_default_types(db)
  8386. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8387. attention = [
  8388. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8389. ]
  8390. items_needing_attention = [
  8391. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8392. for item in attention
  8393. ]
  8394. if items_needing_attention:
  8395. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8396. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8397. # MQTT relay - publish maintenance alerts
  8398. for item in attention:
  8399. current_value, threshold, unit = maintenance_alert_values(item)
  8400. try:
  8401. await mqtt_relay.on_maintenance_alert(
  8402. printer_id=printer_id,
  8403. printer_name=printer_name,
  8404. maintenance_type=item.maintenance_type_name,
  8405. current_value=current_value,
  8406. threshold=threshold,
  8407. unit=unit,
  8408. )
  8409. except Exception:
  8410. pass # Don't fail if MQTT fails
  8411. else:
  8412. logger.info("[MAINT-BG] Completed (no items need attention)")
  8413. except Exception as e:
  8414. logger.warning("[MAINT-BG] Failed: %s", e)
  8415. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8416. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8417. # Notification task waits for photo capture to complete first (with timeout).
  8418. # When a timelapse was recording, photo sourcing polls the per-print
  8419. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8420. # carries the correct bed-up photo instead of falling through to the
  8421. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8422. #
  8423. # #2547: both budgets now have to cover a plate restore as well.
  8424. #
  8425. # Without timelapse, the wait is on the moment producer, which raises the
  8426. # plate before its grab — so this has to outlast that producer's own budget.
  8427. #
  8428. # With timelapse, the capture polls up to
  8429. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8430. # falls back to a live grab, which is the case that raises the plate. At the
  8431. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8432. # restore would have moved the plate for a photo nobody waited for.
  8433. photo_wait_timeout = (
  8434. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8435. if data.get("timelapse_was_active")
  8436. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8437. )
  8438. async def _photo_then_notify():
  8439. """Wait for photo capture, then send notification with photo URL."""
  8440. finish_photo = None
  8441. try:
  8442. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8443. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8444. except TimeoutError:
  8445. logger.warning(
  8446. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8447. photo_wait_timeout,
  8448. )
  8449. except Exception as e:
  8450. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8451. try:
  8452. await _background_notifications(finish_photo)
  8453. except Exception as e:
  8454. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8455. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8456. # Stitch external camera layer timelapse if session was active
  8457. print_status = data.get("status", "completed")
  8458. async def _background_layer_timelapse():
  8459. """Stitch layer timelapse and attach to archive."""
  8460. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8461. try:
  8462. if print_status == "completed":
  8463. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8464. # The run the frames belong to, read before the stitch: it can
  8465. # take long enough for the archive to start printing again.
  8466. run_started_at = None
  8467. if archive_id:
  8468. async with async_session() as db:
  8469. run_archive = await ArchiveService(db).get_archive(archive_id)
  8470. run_started_at = run_archive.started_at if run_archive else None
  8471. timelapse_path = await tl_complete(printer_id)
  8472. if timelapse_path and archive_id:
  8473. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  8474. elif timelapse_path:
  8475. # Timelapse created but no archive - just clean up
  8476. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8477. else:
  8478. # Print failed or cancelled - cancel timelapse session
  8479. cancel_session(printer_id)
  8480. logger.info(
  8481. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8482. )
  8483. except Exception as e:
  8484. logger.warning("[LAYER-TL] Failed: %s", e)
  8485. # A completed print's session left _active_sessions when its stitch
  8486. # began: the one there now belongs to the next print, which may have
  8487. # started during the stitch, and must not lose its frames.
  8488. if print_status != "completed":
  8489. try:
  8490. cancel_session(printer_id)
  8491. except Exception:
  8492. pass # Best-effort timelapse session cancellation on error
  8493. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8494. log_timing("All background tasks scheduled")
  8495. # Auto-scan for timelapse if recording was active during the print
  8496. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8497. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8498. # Schedule timelapse scan as background task with retries
  8499. # The printer needs time to encode the video after print completion
  8500. baseline = _timelapse_baselines.pop(printer_id, None)
  8501. spawn_background_task(
  8502. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8503. name=f"scan-timelapse-{archive_id}",
  8504. )
  8505. log_timing("Timelapse scan scheduled")
  8506. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8507. # AMS sensor history recording
  8508. _ams_history_task: asyncio.Task | None = None
  8509. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8510. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8511. def _retention_days(stored: str | None, default: int) -> int:
  8512. """A history retention setting as days to keep: at least 1, the default
  8513. when unset or unreadable. A stored 0 or less (the API took one before it
  8514. had a minimum) would put the cutoff at now and delete all history."""
  8515. try:
  8516. return max(1, int(stored)) if stored is not None else default
  8517. except (TypeError, ValueError):
  8518. return default
  8519. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8520. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8521. _ams_alarm_cooldown: dict[str, datetime] = {}
  8522. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8523. # (printer_id, ams_id) already reported as sending the drop index and no
  8524. # percentage. Logged once each so a supported printer that turns out to do this
  8525. # shows up in a support bundle rather than as a user wondering where the
  8526. # humidity reading went -- see the note at the read site below (#3140).
  8527. _ams_index_only_logged: set[tuple[int, int]] = set()
  8528. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8529. """Temperature at which the AMS alarm fires, falling back to the display band.
  8530. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8531. when a notification was sent as well, which is why a room above it made the
  8532. alarm fire once an hour for as long as the weather lasted -- and the only way
  8533. to stop that was to raise the display band and lose the colour that says the
  8534. unit is warm (#2905).
  8535. Unset resolves to the fair threshold, so an install that never sets one is
  8536. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8537. so that arrives here as a string and is handled by the same branch as any
  8538. other unparseable value -- there is no separate sentinel to keep in sync.
  8539. A non-positive value is refused rather than honoured: zero would alarm
  8540. permanently, and it is far more likely to be a cleared field than a
  8541. deliberate choice.
  8542. """
  8543. if raw_alarm_value is None:
  8544. return fair_threshold
  8545. try:
  8546. value = float(raw_alarm_value)
  8547. except (TypeError, ValueError):
  8548. return fair_threshold
  8549. if not math.isfinite(value) or value <= 0:
  8550. return fair_threshold
  8551. return value
  8552. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8553. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8554. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8555. # partway through a cool-down would otherwise resume alarming about heat the
  8556. # user asked for — the same internal-timestamp-row pattern as
  8557. # support.py's debug_logging_enabled_at.
  8558. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8559. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8560. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8561. # matters when it never does.
  8562. AMS_DRYING_GRACE_MINUTES = 120
  8563. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8564. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8565. Anything older than the grace cap would expire on its next visit anyway, so
  8566. discarding it here costs nothing and stops rows for deleted printers from
  8567. accumulating.
  8568. Stamps ahead of now get two defences, because a box whose clock jumps
  8569. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8570. ones are discarded outright, and the rest are clamped to now. Without the
  8571. clamp the cap would measure from a moment that has not happened yet and hold
  8572. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8573. after a clock jump is a far better failure than an alarm silently disabled
  8574. for hours.
  8575. """
  8576. from backend.app.models.settings import Settings
  8577. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8578. setting = result.scalar_one_or_none()
  8579. if not setting or not setting.value:
  8580. return {}
  8581. try:
  8582. raw = json.loads(setting.value)
  8583. except (ValueError, TypeError):
  8584. return {} # Corrupted row → no latch, alarms behave as they did before
  8585. if not isinstance(raw, dict):
  8586. return {}
  8587. now = datetime.now(timezone.utc)
  8588. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8589. latch: dict[str, datetime] = {}
  8590. for key, value in raw.items():
  8591. try:
  8592. stamp = datetime.fromisoformat(str(value))
  8593. except (ValueError, TypeError):
  8594. continue
  8595. if stamp.tzinfo is None:
  8596. stamp = stamp.replace(tzinfo=timezone.utc)
  8597. if not (now - window <= stamp <= now + window):
  8598. continue
  8599. # Nothing may sit in the future: suppression is measured as now minus
  8600. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8601. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8602. latch[str(key)] = min(stamp, now)
  8603. return latch
  8604. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8605. """Persist the latch, writing only when it actually changed.
  8606. Adds the session change but does not commit — the caller's own commit
  8607. carries it, so the latch lands in the same transaction as the sensor rows
  8608. that produced it.
  8609. """
  8610. from backend.app.models.settings import Settings
  8611. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8612. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8613. setting = result.scalar_one_or_none()
  8614. if setting is None:
  8615. # Don't create the row on installs that never dry anything.
  8616. if payload != "{}":
  8617. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8618. elif setting.value != payload:
  8619. setting.value = payload
  8620. def _ams_has_filament(ams_data: dict) -> bool:
  8621. """True if this AMS unit has at least one tray slot holding filament.
  8622. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8623. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8624. still report sensor readings, but those readings are ambient and not
  8625. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8626. humidity/temperature alarms on this check so empty units don't generate
  8627. hourly noise. Sensor history still records regardless so the UI charts
  8628. stay continuous.
  8629. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8630. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8631. """
  8632. bits = ams_data.get("tray_exist_bits")
  8633. if isinstance(bits, str) and bits.strip():
  8634. try:
  8635. return int(bits, 16) > 0
  8636. except ValueError:
  8637. pass
  8638. trays = ams_data.get("tray")
  8639. if isinstance(trays, list):
  8640. return any(
  8641. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8642. )
  8643. return False
  8644. async def record_ams_history():
  8645. """Background task to record AMS humidity and temperature data."""
  8646. logger = logging.getLogger(__name__)
  8647. # Wait a short time for MQTT connections to establish on startup
  8648. await asyncio.sleep(10)
  8649. while True:
  8650. try:
  8651. from backend.app.models.ams_history import AMSSensorHistory
  8652. from backend.app.models.printer import Printer
  8653. from backend.app.models.settings import Settings
  8654. async with async_session() as db:
  8655. # Get all active printers
  8656. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8657. printers = result.scalars().all()
  8658. # Get alarm thresholds from settings
  8659. humidity_threshold = 60.0 # Default: fair threshold
  8660. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8661. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8662. setting = result.scalar_one_or_none()
  8663. if setting:
  8664. try:
  8665. humidity_threshold = float(setting.value)
  8666. except (ValueError, TypeError):
  8667. pass # Keep default threshold if stored value is invalid
  8668. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8669. setting = result.scalar_one_or_none()
  8670. if setting:
  8671. try:
  8672. temp_fair_threshold = float(setting.value)
  8673. except (ValueError, TypeError):
  8674. pass # Keep default threshold if stored value is invalid
  8675. # The alarm gets its own threshold, seeded from the resolved fair
  8676. # value so an install that has never set one behaves exactly as
  8677. # it did before (#2905). ams_temp_fair decides when the card turns
  8678. # amber; 35 C is a reasonable place to change a colour and not a
  8679. # reasonable place to page someone. A room above it makes the
  8680. # alarm fire once an hour for as long as the weather lasts, and
  8681. # the only way to stop it was to raise the display band and lose
  8682. # the colour that says the unit is warm.
  8683. #
  8684. # An unset value is stored as the literal "None", which the except
  8685. # below swallows the same way it swallows garbage -- so the
  8686. # fallback costs nothing and needs no sentinel of its own.
  8687. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8688. setting = result.scalar_one_or_none()
  8689. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8690. temp_fair_threshold, setting.value if setting else None
  8691. )
  8692. # Per-filament humidity threshold overrides (#1605) — resolved
  8693. # per-AMS below from the loaded tray types. Reuses the same
  8694. # resolver as the auto-drying scheduler so behavior stays in
  8695. # lockstep across both consumers.
  8696. from backend.app.services.print_scheduler import PrintScheduler
  8697. per_type_humidity_thresholds: dict[str, int] = {}
  8698. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8699. setting = result.scalar_one_or_none()
  8700. if setting and setting.value:
  8701. try:
  8702. raw = json.loads(setting.value)
  8703. if isinstance(raw, dict):
  8704. for k, v in raw.items():
  8705. try:
  8706. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8707. v
  8708. )
  8709. except (TypeError, ValueError):
  8710. continue
  8711. except (ValueError, TypeError):
  8712. pass # Invalid JSON → no overrides, fall through to global threshold
  8713. # Per-AMS drying latch (#1802), loaded once per pass and written
  8714. # back below only if a unit changed it.
  8715. drying_latch = await _load_ams_drying_latch(db)
  8716. drying_latch_before = dict(drying_latch)
  8717. recorded_count = 0
  8718. for printer in printers:
  8719. # Get current state from printer manager
  8720. state = printer_manager.get_status(printer.id)
  8721. if not state or not state.connected or not state.raw_data:
  8722. continue # Skip disconnected printers - don't use stale data
  8723. raw_data = state.raw_data
  8724. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8725. continue
  8726. # Record data for each AMS unit
  8727. for ams_data in raw_data["ams"]:
  8728. ams_id = int(ams_data.get("id", 0))
  8729. # Percentage only. The 1-5 index is inverted, so
  8730. # charting it as a percentage drew the wettest units as
  8731. # the driest (#3140); a unit that reports no percentage
  8732. # leaves a gap in the chart instead. See
  8733. # utils/ams_humidity.
  8734. humidity = ams_humidity_percent(ams_data)
  8735. # No supported printer is known to send the index
  8736. # alone -- the report came from unsupported firmware,
  8737. # and no install has been seen using the old fallback.
  8738. # "Known" is doing work there, so say so once per unit:
  8739. # the alternative is a silent blank card.
  8740. if humidity is None and ams_data.get("humidity") is not None:
  8741. unit_key = (printer.id, ams_id)
  8742. if unit_key not in _ams_index_only_logged:
  8743. _ams_index_only_logged.add(unit_key)
  8744. logger.info(
  8745. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8746. "percentage. The index is inverted and is not shown as a percentage "
  8747. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8748. "Please report this with the printer and AMS firmware versions.",
  8749. printer.name,
  8750. ams_id,
  8751. )
  8752. # Get temperature
  8753. temperature = None
  8754. temp_str = ams_data.get("temp")
  8755. if temp_str is not None:
  8756. try:
  8757. temperature = float(temp_str)
  8758. except (ValueError, TypeError):
  8759. pass # Skip unparseable temperature value
  8760. # Skip if no data
  8761. if humidity is None and temperature is None:
  8762. continue
  8763. # Record the data point
  8764. history = AMSSensorHistory(
  8765. printer_id=printer.id,
  8766. ams_id=ams_id,
  8767. humidity=humidity,
  8768. # Both columns hold the same reading now that the
  8769. # index can no longer reach ``humidity``. Writing it
  8770. # through the same value also stops a genuine 0%
  8771. # from being stored as NULL, which the old truthiness
  8772. # test did.
  8773. humidity_raw=humidity,
  8774. temperature=temperature,
  8775. )
  8776. db.add(history)
  8777. recorded_count += 1
  8778. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8779. is_ams_ht = ams_id >= 128
  8780. if is_ams_ht:
  8781. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8782. else:
  8783. ams_label = f"AMS-{chr(65 + ams_id)}"
  8784. # Skip alarm dispatch for empty AMS units — humidity /
  8785. # temperature readings are ambient with no filament to
  8786. # protect, and the hourly notification just becomes
  8787. # noise. Sensor history was already recorded above so
  8788. # the UI charts stay continuous (#1619). Per-AMS check
  8789. # so a multi-AMS setup with one loaded + one empty
  8790. # still alarms on the loaded unit.
  8791. if not _ams_has_filament(ams_data):
  8792. continue
  8793. # Resolve per-filament humidity threshold for this AMS
  8794. # unit (#1605). Falls back to the global ams_humidity_fair
  8795. # when no per-type overrides are configured.
  8796. trays = ams_data.get("tray", []) or []
  8797. effective_humidity_threshold = float(
  8798. PrintScheduler.resolve_humidity_threshold(
  8799. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8800. )
  8801. )
  8802. # Check humidity alarm (only if above threshold)
  8803. if humidity is not None and humidity > effective_humidity_threshold:
  8804. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8805. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8806. now = datetime.now(timezone.utc)
  8807. if (
  8808. last_alarm is None
  8809. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8810. ):
  8811. _ams_alarm_cooldown[cooldown_key] = now
  8812. logger.info(
  8813. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8814. )
  8815. try:
  8816. # Call different notification method based on AMS type
  8817. if is_ams_ht:
  8818. await notification_service.on_ams_ht_humidity_high(
  8819. printer.id,
  8820. printer.name,
  8821. ams_label,
  8822. humidity,
  8823. effective_humidity_threshold,
  8824. db,
  8825. )
  8826. else:
  8827. await notification_service.on_ams_humidity_high(
  8828. printer.id,
  8829. printer.name,
  8830. ams_label,
  8831. humidity,
  8832. effective_humidity_threshold,
  8833. db,
  8834. )
  8835. except Exception as e:
  8836. logger.warning("Failed to send humidity alarm: %s", e)
  8837. # A drying cycle heats the unit far past ams_temp_fair on
  8838. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8839. # AMS-HT, against a 35 C default — so the alarm fired
  8840. # once an hour for the whole cycle and kept firing while
  8841. # the unit cooled back down (#1802). Latch on the
  8842. # firmware's own drying state and hold until the reading
  8843. # returns to normal. Humidity is deliberately left alone:
  8844. # it falls during drying, which is the whole point.
  8845. latch_key = f"{printer.id}:{ams_id}"
  8846. # The latch releases at `threshold`, so it takes the alarm
  8847. # number too. Handing it the display band would strand the
  8848. # latch on any unit that settles back above it -- a room
  8849. # where the AMS rests at 37.7 C never returns under a 35 C
  8850. # band, so the latch could only expire on the grace cap
  8851. # rather than releasing when the unit had actually cooled.
  8852. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8853. drying_active=is_drying_active(ams_data),
  8854. temperature=temperature,
  8855. threshold=temp_alarm_threshold,
  8856. latched_at=drying_latch.get(latch_key),
  8857. now=datetime.now(timezone.utc),
  8858. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8859. )
  8860. if new_latch is None:
  8861. drying_latch.pop(latch_key, None)
  8862. else:
  8863. drying_latch[latch_key] = new_latch
  8864. # Check temperature alarm (only if above threshold)
  8865. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8866. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8867. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8868. now = datetime.now(timezone.utc)
  8869. if (
  8870. last_alarm is None
  8871. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8872. ):
  8873. _ams_alarm_cooldown[cooldown_key] = now
  8874. logger.info(
  8875. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8876. f"{temperature}°C > {temp_alarm_threshold}°C"
  8877. )
  8878. try:
  8879. # Call different notification method based on AMS type
  8880. if is_ams_ht:
  8881. # The reported threshold has to be the one
  8882. # that fired, or the message says "> 35 °C"
  8883. # while firing at 45.
  8884. await notification_service.on_ams_ht_temperature_high(
  8885. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8886. )
  8887. else:
  8888. await notification_service.on_ams_temperature_high(
  8889. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8890. )
  8891. except Exception as e:
  8892. logger.warning("Failed to send temperature alarm: %s", e)
  8893. if drying_latch != drying_latch_before:
  8894. await _save_ams_drying_latch(db, drying_latch)
  8895. await db.commit()
  8896. if recorded_count > 0:
  8897. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8898. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8899. global _ams_cleanup_counter
  8900. _ams_cleanup_counter += 1
  8901. if _ams_cleanup_counter >= 288:
  8902. _ams_cleanup_counter = 0
  8903. # Get retention days from settings
  8904. from backend.app.models.settings import Settings
  8905. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8906. setting = result.scalar_one_or_none()
  8907. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  8908. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8909. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8910. await db.commit()
  8911. if result.rowcount > 0:
  8912. logger.info(
  8913. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8914. )
  8915. # Wait until next recording interval
  8916. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8917. except asyncio.CancelledError:
  8918. break
  8919. except Exception as e:
  8920. logger.warning("AMS history recording failed: %s", e)
  8921. await asyncio.sleep(60) # Wait a bit before retrying
  8922. def start_ams_history_recording():
  8923. """Start the AMS history recording background task."""
  8924. global _ams_history_task
  8925. if _ams_history_task is None:
  8926. _ams_history_task = asyncio.create_task(record_ams_history())
  8927. logging.getLogger(__name__).info("AMS history recording started")
  8928. def stop_ams_history_recording():
  8929. """Stop the AMS history recording background task."""
  8930. global _ams_history_task
  8931. if _ams_history_task:
  8932. _ams_history_task.cancel()
  8933. _ams_history_task = None
  8934. logging.getLogger(__name__).info("AMS history recording stopped")
  8935. # Printer sensor history recording (nozzle / bed / chamber)
  8936. _printer_sensor_history_task: asyncio.Task | None = None
  8937. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8938. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8939. _printer_sensor_cleanup_counter = 0
  8940. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8941. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8942. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8943. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8944. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8945. _SENSOR_TARGET_KEYS = {
  8946. "nozzle": "nozzle_target",
  8947. "nozzle_2": "nozzle_2_target",
  8948. "bed": "bed_target",
  8949. "chamber": "chamber_target",
  8950. }
  8951. async def record_printer_sensor_history():
  8952. """Background task to record nozzle / bed / chamber readings.
  8953. Pulls from `state.temperatures` (already normalised across all printer
  8954. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8955. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8956. """
  8957. logger = logging.getLogger(__name__)
  8958. await asyncio.sleep(10)
  8959. while True:
  8960. try:
  8961. from backend.app.models.printer import Printer
  8962. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8963. from backend.app.models.settings import Settings
  8964. async with async_session() as db:
  8965. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8966. printers = result.scalars().all()
  8967. recorded_count = 0
  8968. for printer in printers:
  8969. state = printer_manager.get_status(printer.id)
  8970. if not state or not state.connected:
  8971. continue
  8972. temps = getattr(state, "temperatures", None) or {}
  8973. if not isinstance(temps, dict):
  8974. continue
  8975. for kind in _SENSOR_KINDS:
  8976. if kind not in temps:
  8977. continue
  8978. try:
  8979. value = float(temps[kind])
  8980. except (ValueError, TypeError):
  8981. continue
  8982. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8983. target_val: float | None = None
  8984. if target_raw is not None:
  8985. try:
  8986. target_val = float(target_raw)
  8987. except (ValueError, TypeError):
  8988. target_val = None
  8989. db.add(
  8990. PrinterSensorHistory(
  8991. printer_id=printer.id,
  8992. sensor_kind=kind,
  8993. value=value,
  8994. target=target_val,
  8995. )
  8996. )
  8997. recorded_count += 1
  8998. await db.commit()
  8999. if recorded_count > 0:
  9000. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9001. # Periodic cleanup — once every ~24h at this interval.
  9002. global _printer_sensor_cleanup_counter
  9003. _printer_sensor_cleanup_counter += 1
  9004. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9005. if _printer_sensor_cleanup_counter >= cleanup_every:
  9006. _printer_sensor_cleanup_counter = 0
  9007. result = await db.execute(
  9008. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9009. )
  9010. setting = result.scalar_one_or_none()
  9011. retention_days = _retention_days(
  9012. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9013. )
  9014. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9015. cleanup = await db.execute(
  9016. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9017. )
  9018. await db.commit()
  9019. if cleanup.rowcount > 0:
  9020. logger.info(
  9021. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9022. cleanup.rowcount,
  9023. retention_days,
  9024. )
  9025. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9026. except asyncio.CancelledError:
  9027. break
  9028. except Exception as e:
  9029. logger.warning("Printer sensor history recording failed: %s", e)
  9030. await asyncio.sleep(60)
  9031. def start_printer_sensor_history_recording():
  9032. global _printer_sensor_history_task
  9033. if _printer_sensor_history_task is None:
  9034. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9035. logging.getLogger(__name__).info("Printer sensor history recording started")
  9036. def stop_printer_sensor_history_recording():
  9037. global _printer_sensor_history_task
  9038. if _printer_sensor_history_task:
  9039. _printer_sensor_history_task.cancel()
  9040. _printer_sensor_history_task = None
  9041. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9042. # Printer runtime tracking
  9043. _runtime_tracking_task: asyncio.Task | None = None
  9044. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9045. # Printers the runtime tracker has seen connected since startup. One of them
  9046. # going offline clears its timestamp, so the time it was away is not counted
  9047. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9048. # connecting after a restart -- keeps it for a grace period: a print that ran
  9049. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9050. _runtime_seen_connected: set[int] = set()
  9051. # A printer never seen connected this long after the tracker started is
  9052. # offline, not still connecting: its stored timestamp predates a gap too.
  9053. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9054. async def track_printer_runtime():
  9055. """Background task to track printer active runtime (RUNNING state only).
  9056. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9057. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9058. which track mechanical wear. Pause time has no motion and no wear, so
  9059. counting it inflates maintenance warnings (#1521).
  9060. """
  9061. logger = logging.getLogger(__name__)
  9062. # Wait for MQTT connections to establish on startup
  9063. await asyncio.sleep(15)
  9064. started = time.monotonic()
  9065. while True:
  9066. try:
  9067. from backend.app.models.printer import Printer
  9068. # Fetch printer IDs in a short-lived read-only session
  9069. async with async_session() as db:
  9070. result = await db.execute(
  9071. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9072. Printer.is_active.is_(True)
  9073. )
  9074. )
  9075. printer_rows = result.all()
  9076. now = datetime.now(timezone.utc)
  9077. updated_count = 0
  9078. # Update each printer in its own short session to minimise write-lock
  9079. # hold time and avoid blocking critical commits like queue status
  9080. # updates (#897).
  9081. for pid, pname, runtime_secs, last_update in printer_rows:
  9082. state = printer_manager.get_status(pid)
  9083. if not state:
  9084. logger.debug("[%s] Runtime tracking: no state available", pname)
  9085. continue
  9086. if not state.connected:
  9087. logger.debug("[%s] Runtime tracking: not connected", pname)
  9088. offline = pid in _runtime_seen_connected or (
  9089. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9090. )
  9091. if offline and last_update is not None:
  9092. try:
  9093. async with async_session() as db:
  9094. printer = await db.get(Printer, pid)
  9095. if printer:
  9096. printer.last_runtime_update = None
  9097. await db.commit()
  9098. except Exception as e:
  9099. # Still marked: the next offline tick tries again.
  9100. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9101. continue
  9102. _runtime_seen_connected.discard(pid)
  9103. continue
  9104. _runtime_seen_connected.add(pid)
  9105. needs_commit = False
  9106. new_runtime = runtime_secs
  9107. new_last_update = last_update
  9108. if state.state == "RUNNING":
  9109. if last_update:
  9110. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9111. elapsed = (now - lu).total_seconds()
  9112. if elapsed > 0:
  9113. new_runtime = runtime_secs + int(elapsed)
  9114. updated_count += 1
  9115. needs_commit = True
  9116. logger.debug(
  9117. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9118. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9119. )
  9120. else:
  9121. needs_commit = True
  9122. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9123. new_last_update = now
  9124. else:
  9125. if last_update is not None:
  9126. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9127. new_last_update = None
  9128. needs_commit = True
  9129. if needs_commit:
  9130. try:
  9131. async with async_session() as db:
  9132. result = await db.execute(select(Printer).where(Printer.id == pid))
  9133. printer = result.scalar_one_or_none()
  9134. if printer:
  9135. printer.runtime_seconds = new_runtime
  9136. printer.last_runtime_update = new_last_update
  9137. await db.commit()
  9138. except Exception as e:
  9139. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9140. if updated_count > 0:
  9141. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9142. except asyncio.CancelledError:
  9143. logger.info("Runtime tracking cancelled")
  9144. break
  9145. except Exception as e:
  9146. logger.warning("Runtime tracking failed: %s", e)
  9147. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9148. def start_runtime_tracking():
  9149. """Start the printer runtime tracking background task."""
  9150. global _runtime_tracking_task
  9151. if _runtime_tracking_task is None:
  9152. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9153. logging.getLogger(__name__).info("Printer runtime tracking started")
  9154. def stop_runtime_tracking():
  9155. """Stop the printer runtime tracking background task."""
  9156. global _runtime_tracking_task
  9157. if _runtime_tracking_task:
  9158. _runtime_tracking_task.cancel()
  9159. _runtime_tracking_task = None
  9160. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9161. # SpoolBuddy device watchdog
  9162. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9163. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9164. async def _spoolbuddy_watchdog_loop():
  9165. """Periodic check for SpoolBuddy devices that have gone offline."""
  9166. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9167. while True:
  9168. try:
  9169. await spoolbuddy_watchdog()
  9170. except asyncio.CancelledError:
  9171. break
  9172. except Exception as e:
  9173. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9174. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9175. def start_spoolbuddy_watchdog():
  9176. global _spoolbuddy_watchdog_task
  9177. if _spoolbuddy_watchdog_task is None:
  9178. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9179. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9180. def stop_spoolbuddy_watchdog():
  9181. global _spoolbuddy_watchdog_task
  9182. if _spoolbuddy_watchdog_task:
  9183. _spoolbuddy_watchdog_task.cancel()
  9184. _spoolbuddy_watchdog_task = None
  9185. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9186. # Dead-MQTT-session recovery
  9187. #
  9188. # check_staleness() covers the "connected but silent" half-broken session. It
  9189. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9190. # is the only thing left watching at that point. When paho stops making
  9191. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9192. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9193. # offline with the UI open the whole time, recovered only when something
  9194. # happened to nudge it.
  9195. #
  9196. # This loop is that backstop. It only touches printers that had a working
  9197. # session and lost it, and only when the MQTT port still answers — a printer
  9198. # that is simply switched off is left to paho, since rebuilding a client
  9199. # against an unreachable host achieves nothing and would fill the log every
  9200. # night.
  9201. _connection_watchdog_task: asyncio.Task | None = None
  9202. CONNECTION_WATCHDOG_INTERVAL = 60
  9203. # How long a printer must have been silent before we stop trusting paho.
  9204. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9205. # so a session that is recovering on its own is never interrupted.
  9206. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9207. # Per-printer floor between rebuild attempts.
  9208. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9209. _connection_watchdog_last_attempt: dict[int, float] = {}
  9210. async def _recover_dead_printer_sessions() -> int:
  9211. """Rebuild MQTT clients that have been offline too long to still be trying.
  9212. Returns the number of printers a rebuild was attempted for (for tests and
  9213. for the caller's logging). Never raises: one unreachable printer must not
  9214. stop the sweep for the rest of the farm.
  9215. """
  9216. logger = logging.getLogger(__name__)
  9217. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9218. now = time.monotonic()
  9219. recovered = 0
  9220. for printer_id, client in list(printer_manager._clients.items()):
  9221. try:
  9222. if client.state.connected:
  9223. _connection_watchdog_last_attempt.pop(printer_id, None)
  9224. continue
  9225. # Time since the last inbound message is the age of the last known
  9226. # good session — no extra bookkeeping needed, and it is the same
  9227. # clock is_stale() reads. 0 means this client has never had one:
  9228. # that is the initial-connect path, where paho retrying is the
  9229. # correct and only behaviour, so leave it be.
  9230. last_msg = client._last_message_time
  9231. if not last_msg:
  9232. continue
  9233. offline_for = time.time() - last_msg
  9234. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9235. continue
  9236. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9237. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9238. continue
  9239. if not await check_port(client.ip_address, PORT_MQTT):
  9240. # Switched off, unplugged, or off the network. Paho's retry is
  9241. # the right handler; say so at debug level and move on.
  9242. logger.debug(
  9243. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9244. "— leaving the reconnect to paho",
  9245. printer_id,
  9246. offline_for,
  9247. )
  9248. _connection_watchdog_last_attempt[printer_id] = now
  9249. continue
  9250. _connection_watchdog_last_attempt[printer_id] = now
  9251. recovered += 1
  9252. logger.warning(
  9253. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9254. "rebuilding the client with a fresh session (last connect error: %s)",
  9255. printer_id,
  9256. offline_for,
  9257. PORT_MQTT,
  9258. client.last_connect_error or "none recorded",
  9259. )
  9260. # Async context, so this takes the hard-reset path: fresh client_id,
  9261. # paho's QoS 1 queue dropped. That matters — a project_file left
  9262. # unacked on the dead session would otherwise replay into the new
  9263. # one and trip 0500_4003 on the printer (#1136).
  9264. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9265. except Exception as e:
  9266. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9267. return recovered
  9268. async def _connection_watchdog_loop():
  9269. logger = logging.getLogger(__name__)
  9270. # Let the initial connects settle before judging anyone offline.
  9271. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9272. while True:
  9273. try:
  9274. await _recover_dead_printer_sessions()
  9275. except asyncio.CancelledError:
  9276. break
  9277. except Exception as e:
  9278. logger.warning("Connection watchdog sweep failed: %s", e)
  9279. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9280. def start_connection_watchdog():
  9281. global _connection_watchdog_task
  9282. if _connection_watchdog_task is None:
  9283. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9284. logging.getLogger(__name__).info("Printer connection watchdog started")
  9285. def stop_connection_watchdog():
  9286. global _connection_watchdog_task
  9287. if _connection_watchdog_task:
  9288. _connection_watchdog_task.cancel()
  9289. _connection_watchdog_task = None
  9290. _connection_watchdog_last_attempt.clear()
  9291. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9292. # Camera stream orphan cleanup
  9293. _camera_cleanup_task: asyncio.Task | None = None
  9294. CAMERA_CLEANUP_INTERVAL = 60
  9295. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9296. # kept frames of a failed stitch go after a day, not at the next restart.
  9297. TIMELAPSE_CLEANUP_EVERY = 60
  9298. async def _camera_cleanup_loop():
  9299. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9300. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9301. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9302. rounds = 0
  9303. while True:
  9304. try:
  9305. rounds += 1
  9306. await cleanup_orphaned_streams()
  9307. except asyncio.CancelledError:
  9308. break
  9309. except Exception as e:
  9310. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9311. try:
  9312. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9313. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9314. except asyncio.CancelledError:
  9315. break
  9316. except Exception as e:
  9317. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9318. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9319. def start_camera_cleanup():
  9320. global _camera_cleanup_task
  9321. if _camera_cleanup_task is None:
  9322. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9323. logging.getLogger(__name__).info("Camera stream cleanup started")
  9324. def stop_camera_cleanup():
  9325. global _camera_cleanup_task
  9326. if _camera_cleanup_task:
  9327. _camera_cleanup_task.cancel()
  9328. _camera_cleanup_task = None
  9329. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9330. # ---------------------------------------------------------------------------
  9331. # Expected-print TTL eviction
  9332. # ---------------------------------------------------------------------------
  9333. def _evict_stale_expected_prints() -> None:
  9334. """Remove entries from _expected_prints / _expected_print_creators that are
  9335. older than _EXPECTED_PRINT_TTL_SECONDS.
  9336. This prevents unbounded growth when a print is registered (via
  9337. register_expected_print) but on_print_start never fires — e.g. because the
  9338. printer disconnects, the app restarts, or the print is started directly from
  9339. the printer panel without going through the queue.
  9340. """
  9341. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9342. # (e.g. NTP sync, DST changes).
  9343. # A print that ended without its archive being found at completion leaves
  9344. # its id here; only running prints are owned.
  9345. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9346. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9347. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9348. if not stale_keys:
  9349. return
  9350. evicted_archive_ids: set[int] = set()
  9351. for key in stale_keys:
  9352. archive_id = _expected_prints.pop(key, None)
  9353. if archive_id is not None:
  9354. evicted_archive_ids.add(archive_id)
  9355. _expected_print_creators.pop(key, None)
  9356. _expected_print_registered_at.pop(key, None)
  9357. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9358. # that have no remaining live keys in _expected_prints (all variants
  9359. # were just evicted) and are not printing right now. Print start pops
  9360. # only the names the printer reported, so the "<base>.gcode" variant
  9361. # outlives it; without the printing check its eviction two hours after
  9362. # dispatch threw away a running print's plate, AMS mapping and cost
  9363. # centre, which completion still reads (#3275).
  9364. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9365. for archive_id in evicted_archive_ids:
  9366. if archive_id not in live_archive_ids:
  9367. _print_ams_mappings.pop(archive_id, None)
  9368. _print_cost_center_ids.pop(archive_id, None)
  9369. _print_plate_ids.pop(archive_id, None)
  9370. logging.getLogger(__name__).info(
  9371. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9372. )
  9373. async def _expected_prints_cleanup_loop() -> None:
  9374. """Background task: periodically evict stale expected-print entries."""
  9375. while True:
  9376. try:
  9377. _evict_stale_expected_prints()
  9378. except asyncio.CancelledError:
  9379. raise
  9380. except Exception as e:
  9381. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9382. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9383. def start_expected_prints_cleanup() -> None:
  9384. global _expected_prints_cleanup_task
  9385. if _expected_prints_cleanup_task is None:
  9386. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9387. logging.getLogger(__name__).info("Expected prints cleanup started")
  9388. def stop_expected_prints_cleanup() -> None:
  9389. global _expected_prints_cleanup_task
  9390. if _expected_prints_cleanup_task:
  9391. _expected_prints_cleanup_task.cancel()
  9392. _expected_prints_cleanup_task = None
  9393. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9394. # ---------------------------------------------------------------------------
  9395. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9396. # ---------------------------------------------------------------------------
  9397. _auth_cleanup_task: asyncio.Task | None = None
  9398. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9399. async def _run_auth_cleanup() -> None:
  9400. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9401. from backend.app.core.database import async_session
  9402. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9403. from backend.app.models.user_totp import UserTOTP
  9404. now = datetime.now(timezone.utc)
  9405. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9406. try:
  9407. async with async_session() as db:
  9408. stale_cutoff = now - timedelta(hours=1)
  9409. result = await db.execute(
  9410. select(UserTOTP).where(
  9411. UserTOTP.is_enabled.is_(False),
  9412. UserTOTP.created_at < stale_cutoff,
  9413. )
  9414. )
  9415. stale_records = result.scalars().all()
  9416. if stale_records:
  9417. for rec in stale_records:
  9418. await db.delete(rec)
  9419. await db.commit()
  9420. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9421. except Exception as e:
  9422. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9423. # Remove expired revoked-JTI entries (they are no longer needed once the
  9424. # original token's exp has passed — the token would be rejected by JWT
  9425. # signature verification regardless).
  9426. try:
  9427. async with async_session() as db:
  9428. await db.execute(
  9429. delete(AuthEphemeralToken).where(
  9430. AuthEphemeralToken.token_type == "revoked_jti",
  9431. AuthEphemeralToken.expires_at < now,
  9432. )
  9433. )
  9434. await db.commit()
  9435. except Exception as e:
  9436. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9437. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9438. # Events outside this window can never affect rate-limit decisions — they only
  9439. # consume DB space. Use the same window constant as the rate limiter so the
  9440. # two are always in sync.
  9441. try:
  9442. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9443. async with async_session() as db:
  9444. await db.execute(
  9445. delete(AuthRateLimitEvent).where(
  9446. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9447. )
  9448. )
  9449. await db.commit()
  9450. except Exception as e:
  9451. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9452. async def _auth_cleanup_loop() -> None:
  9453. """Periodic background task: run auth cleanup every hour."""
  9454. while True:
  9455. try:
  9456. await _run_auth_cleanup()
  9457. except asyncio.CancelledError:
  9458. break
  9459. except Exception as e:
  9460. logging.warning("Auth cleanup loop error: %s", e)
  9461. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9462. def start_auth_cleanup() -> None:
  9463. global _auth_cleanup_task
  9464. if _auth_cleanup_task is None:
  9465. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9466. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9467. def stop_auth_cleanup() -> None:
  9468. global _auth_cleanup_task
  9469. if _auth_cleanup_task:
  9470. _auth_cleanup_task.cancel()
  9471. _auth_cleanup_task = None
  9472. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9473. @asynccontextmanager
  9474. async def lifespan(app: FastAPI):
  9475. # Startup
  9476. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9477. # anything else can spawn tasks that might trip it.
  9478. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9479. install_proactor_reset_filter()
  9480. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9481. # what turned descriptor exhaustion into a corrupted database (#2883).
  9482. from backend.app.core.fd_limit import raise_open_file_limit
  9483. raise_open_file_limit()
  9484. # Before init_db, so the warning is near the top of the log rather than
  9485. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9486. warn_if_running_on_uvloop()
  9487. await init_db()
  9488. # Browser download tokens expire after five minutes. Remove abandoned
  9489. # prepared ZIPs at startup as well as before each new preparation so a
  9490. # quiet appliance cannot retain an unusable bundle indefinitely.
  9491. try:
  9492. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9493. await prune_stale_printer_file_bundles()
  9494. except Exception as exc:
  9495. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9496. # After migrations, so the is_env_managed column exists. Never raises --
  9497. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9498. # startup (see apply_env_oidc_provider).
  9499. from backend.app.core.oidc_env import apply_env_oidc_provider
  9500. async with async_session() as oidc_db:
  9501. await apply_env_oidc_provider(oidc_db)
  9502. # Close out batches that finished before `completed` was a reachable status
  9503. # (#342). Without this the Batches tab opens on every batch created since
  9504. # the feature shipped, all still marked active. Never blocks startup.
  9505. try:
  9506. from backend.app.services.print_batch import backfill_batch_statuses
  9507. async with async_session() as batch_db:
  9508. await backfill_batch_statuses(batch_db)
  9509. except Exception as exc:
  9510. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9511. # Register an app-scoped httpx client for Bambu Cloud services so
  9512. # per-request BambuCloudService instances reuse the same connection pool
  9513. # (important for routes like /cloud/filament-info that chain many
  9514. # get_setting_detail calls). The shared client stores no region/token
  9515. # state, so the per-request ownership pattern that fixed the region-bleed
  9516. # bug is preserved.
  9517. import httpx as _httpx
  9518. from backend.app.services.bambu_cloud import set_shared_http_client
  9519. from backend.app.services.model_providers.makerworld.service import (
  9520. set_shared_http_client as set_shared_makerworld_http_client,
  9521. )
  9522. from backend.app.services.orca_cloud import (
  9523. set_shared_http_client as set_shared_orca_http_client,
  9524. )
  9525. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9526. set_shared_http_client(_shared_cloud_http_client)
  9527. # Reuse the same connection pool for MakerWorld — different host, same
  9528. # keep-alive pool saves a TLS handshake per request.
  9529. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9530. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9531. # each spun up (and never closed) its own client, leaking sockets.
  9532. set_shared_orca_http_client(_shared_cloud_http_client)
  9533. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9534. # This can happen when a print was cancelled mid-print on versions before this fix.
  9535. try:
  9536. async with async_session() as db:
  9537. from backend.app.models.print_queue import PrintQueueItem
  9538. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9539. aborted_items = result.scalars().all()
  9540. if aborted_items:
  9541. for item in aborted_items:
  9542. item.status = "cancelled"
  9543. await db.commit()
  9544. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9545. except Exception as e:
  9546. logging.warning("Failed to fix aborted queue items: %s", e)
  9547. # Restore debug logging state from previous session
  9548. await init_debug_logging()
  9549. # Set up printer manager callbacks
  9550. loop = asyncio.get_event_loop()
  9551. printer_manager.set_event_loop(loop)
  9552. printer_manager.set_status_change_callback(on_printer_status_change)
  9553. printer_manager.set_print_start_callback(on_print_start)
  9554. printer_manager.set_print_complete_callback(on_print_complete)
  9555. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9556. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9557. printer_manager.set_ams_change_callback(on_ams_change)
  9558. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9559. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9560. await printer_manager.load_awaiting_plate_clear_from_db()
  9561. # Layer change callback for external camera timelapse
  9562. async def on_layer_change(printer_id: int, layer_num: int):
  9563. """Capture timelapse frame on layer change + first layer notification."""
  9564. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9565. await tl_layer_change(printer_id, layer_num)
  9566. # #1867: bank a recent in-print frame so the finish-photo path has a
  9567. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9568. # #2547 added `on_print_progress` as a second driver — this one alone
  9569. # stops firing once the final layer begins.
  9570. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9571. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9572. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9573. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9574. # nozzle clean), so a bare layer_num check can fire minutes before the
  9575. # first real extrusion. We require gcode_state == RUNNING and
  9576. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9577. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9578. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9579. # edge fires later; _first_layer_notified stays clear until we actually send
  9580. # so a deferred re-evaluation can win. See issue #1837.
  9581. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9582. client = printer_manager.get_client(printer_id)
  9583. state = client.state if client else None
  9584. if not state or state.state != "RUNNING":
  9585. return
  9586. if state.mc_print_sub_stage not in (None, 0):
  9587. return
  9588. _first_layer_notified[printer_id] = True
  9589. try:
  9590. async with async_session() as db:
  9591. from backend.app.models.printer import Printer
  9592. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9593. printer = result.scalar_one_or_none()
  9594. if not printer:
  9595. return
  9596. printer_name = printer.name
  9597. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9598. total_layers = state.total_layers if state else 0
  9599. image_data = await _capture_snapshot_for_notification(
  9600. printer_id, printer, logging.getLogger(__name__)
  9601. )
  9602. await notification_service.on_first_layer_complete(
  9603. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9604. )
  9605. except Exception as e:
  9606. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9607. printer_manager.set_layer_change_callback(on_layer_change)
  9608. async def on_print_progress(printer_id: int, percent: int):
  9609. """#2547: keep the in-print frame bank fresh through the final layer.
  9610. `on_layer_change` stops the moment the last layer starts, which on the
  9611. H2C capture that closed #2547 left the bank stale for the three minutes
  9612. that layer took. Progress is the only field that keeps advancing there,
  9613. and it freezes before the End G-code runs — so banking on it stays
  9614. inside the print and never sees a swapped plate.
  9615. """
  9616. client = printer_manager.get_client(printer_id)
  9617. state = client.state if client else None
  9618. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9619. printer_manager.set_print_progress_callback(on_print_progress)
  9620. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9621. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9622. waiter = _bed_cool_waiters.get(printer_id)
  9623. if not waiter:
  9624. return
  9625. threshold = waiter["threshold"]
  9626. if bed_temp > threshold:
  9627. return
  9628. # Bed is at or below threshold — fire notification and remove waiter
  9629. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9630. if not waiter_info:
  9631. return # Another callback already handled it
  9632. bed_cool_logger = logging.getLogger(__name__)
  9633. bed_cool_logger.info(
  9634. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9635. bed_temp,
  9636. printer_id,
  9637. threshold,
  9638. )
  9639. try:
  9640. printer_info = printer_manager.get_printer(printer_id)
  9641. p_name = printer_info.name if printer_info else "Unknown"
  9642. async with async_session() as db:
  9643. await notification_service.on_bed_cooled(
  9644. printer_id=printer_id,
  9645. printer_name=p_name,
  9646. bed_temp=bed_temp,
  9647. threshold=threshold,
  9648. filename=waiter_info["filename"],
  9649. db=db,
  9650. )
  9651. except Exception as e:
  9652. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9653. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9654. async def on_drying_complete(printer_id: int, ams_id: int):
  9655. """Smart-plug auto-off-after-drying trigger (#1349).
  9656. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9657. manager walks all plugs linked to this printer and turns off only
  9658. the ones with ``auto_off_after_drying`` enabled, after their
  9659. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9660. dual-AMS dry that ends within the same MQTT push) call this once
  9661. per unit — the manager's ``_cancel_pending_off`` collapses
  9662. repeated scheduling on the same plug to one timer, so duplicate
  9663. fires are safe.
  9664. """
  9665. try:
  9666. async with async_session() as db:
  9667. await smart_plug_manager.on_drying_complete(printer_id, db)
  9668. except Exception as e:
  9669. logging.getLogger(__name__).warning(
  9670. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9671. printer_id,
  9672. ams_id,
  9673. e,
  9674. )
  9675. printer_manager.set_drying_complete_callback(on_drying_complete)
  9676. async def on_drying_cycle_end(printer_id: int, cycle):
  9677. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9678. from backend.app.services.spool_drying import record_drying_cycle
  9679. try:
  9680. async with async_session() as db:
  9681. await record_drying_cycle(db, printer_id, cycle)
  9682. except Exception as e:
  9683. logging.getLogger(__name__).warning(
  9684. "Failed to record drying for printer %d (AMS %d): %s",
  9685. printer_id,
  9686. cycle.ams_id,
  9687. e,
  9688. )
  9689. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9690. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9691. """Surface the read-back result of a spool assignment to the UI (#2582).
  9692. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9693. echoed back the filament id we pushed. We relay that as a websocket
  9694. event so the frontend can toast "loaded" / "assignment didn't take"
  9695. instead of the historic silent fire-and-forget, which made the
  9696. AMS→Studio hand-off feel random to users.
  9697. """
  9698. try:
  9699. from backend.app.services.spool_assignment_notifications import (
  9700. _slot_label_from_global_tray,
  9701. )
  9702. if ams_id == 255:
  9703. global_id = 254 + tray_id
  9704. elif ams_id >= 128:
  9705. global_id = ams_id
  9706. else:
  9707. global_id = ams_id * 4 + tray_id
  9708. slot_label = _slot_label_from_global_tray(global_id)
  9709. printer_info = printer_manager.get_printer(printer_id)
  9710. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9711. await ws_manager.broadcast(
  9712. {
  9713. "type": "spool_assignment_verified",
  9714. "printer_id": printer_id,
  9715. "printer_name": printer_name,
  9716. "ams_id": ams_id,
  9717. "tray_id": tray_id,
  9718. "slot": slot_label,
  9719. "verified": verified,
  9720. # Present on success: False means the filament setting landed
  9721. # but the K-profile (cali_idx) did not — the reporter's exact
  9722. # "loaded but no flow profile" symptom.
  9723. "kprofile_applied": detail.get("kprofile_applied", True),
  9724. # Present on failure: whether any tray telemetry was seen in
  9725. # the window (distinguishes "printer silent" from "printer
  9726. # stored something else").
  9727. "saw_tray": detail.get("saw_tray", False),
  9728. }
  9729. )
  9730. except Exception as e:
  9731. logging.getLogger(__name__).warning(
  9732. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9733. printer_id,
  9734. ams_id,
  9735. tray_id,
  9736. e,
  9737. )
  9738. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9739. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9740. """Persist a mid-print tray change for completion-time attribution.
  9741. AMS filament backup switches trays without telling the slicer, so the
  9742. tray-change log is the only record of which spool fed which layers.
  9743. Keeping it only in memory meant a restart mid-print charged everything
  9744. to the tray that finished the job.
  9745. """
  9746. try:
  9747. from backend.app.services.usage_tracker import record_tray_change
  9748. async with async_session() as db:
  9749. await record_tray_change(db, printer_id, tray_global, layer_num)
  9750. except Exception as e:
  9751. logging.getLogger(__name__).warning(
  9752. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9753. printer_id,
  9754. tray_global,
  9755. layer_num,
  9756. e,
  9757. )
  9758. printer_manager.set_tray_change_callback(on_tray_change)
  9759. # Initialize MQTT relay from settings
  9760. async with async_session() as db:
  9761. from backend.app.api.routes.settings import get_setting
  9762. mqtt_settings = {
  9763. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9764. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9765. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9766. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9767. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9768. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9769. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9770. }
  9771. await mqtt_relay.configure(mqtt_settings)
  9772. # Restore MQTT smart plug subscriptions
  9773. if mqtt_settings.get("mqtt_enabled"):
  9774. from backend.app.models.smart_plug import SmartPlug
  9775. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9776. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9777. mqtt_plugs = result.scalars().all()
  9778. restored = 0
  9779. for plug in mqtt_plugs:
  9780. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9781. restored += 1
  9782. if restored:
  9783. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9784. # Connect to all active printers
  9785. async with async_session() as db:
  9786. await init_printer_connections(db)
  9787. # Auto-connect to Spoolman if enabled
  9788. async with async_session() as db:
  9789. from backend.app.api.routes.settings import get_setting
  9790. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9791. spoolman_url = await get_setting(db, "spoolman_url")
  9792. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9793. try:
  9794. client = await init_spoolman_client(spoolman_url)
  9795. if await client.health_check():
  9796. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9797. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9798. field_ok = await client.ensure_tag_extra_field()
  9799. if not field_ok:
  9800. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9801. # Register the BambuStudio slicer-preset fields used by the
  9802. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9803. # unknown extra keys, so these must exist before any update
  9804. # that touches them.
  9805. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9806. if not await client.ensure_extra_field(field_name):
  9807. logging.warning(
  9808. "Spoolman extra field %r registration failed — "
  9809. "spool slicer-preset edits will return 502",
  9810. field_name,
  9811. )
  9812. else:
  9813. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9814. except Exception as e:
  9815. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9816. # Start the print scheduler
  9817. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9818. # Start the smart plug scheduler for time-based on/off
  9819. smart_plug_manager.start_scheduler()
  9820. # Start the Home Assistant sensor poller (#1148)
  9821. ha_sensor_manager.start()
  9822. location_ha_sensor_manager.start()
  9823. # Resume any pending auto-offs that were interrupted by restart
  9824. await smart_plug_manager.resume_pending_auto_offs()
  9825. # Start the notification digest scheduler
  9826. notification_service.start_digest_scheduler()
  9827. notify_live_activities.start()
  9828. notify_widgets.start()
  9829. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9830. # provider in reactions/both mode; the notification routes resync them.
  9831. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9832. # until the next provider save, not the whole startup.
  9833. try:
  9834. await telegram_reaction_poller.start()
  9835. except Exception as e:
  9836. logging.warning("Telegram reaction poller did not start: %s", e)
  9837. # Start the GitHub backup scheduler
  9838. await github_backup_service.start_scheduler()
  9839. # Start the local backup scheduler
  9840. await local_backup_service.start_scheduler()
  9841. await obico_detection_service.start()
  9842. # Start the library trash sweeper (#1008)
  9843. await library_trash_service.start_scheduler()
  9844. # Start the archive auto-purge sweeper (#1008 follow-up)
  9845. await archive_purge_service.start_scheduler()
  9846. # Start AMS history recording
  9847. start_ams_history_recording()
  9848. # Start printer sensor (nozzle / bed / chamber) history recording
  9849. start_printer_sensor_history_recording()
  9850. # Start printer runtime tracking
  9851. start_runtime_tracking()
  9852. # Start SpoolBuddy device watchdog
  9853. start_spoolbuddy_watchdog()
  9854. # Start camera stream orphan cleanup
  9855. start_camera_cleanup()
  9856. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9857. start_connection_watchdog()
  9858. # One-shot sweep for timelapse session directories orphaned by a crash
  9859. # or restart that happened mid-print (in-memory session tracking can't
  9860. # survive that, and nothing else reaps the leftover frames/output file)
  9861. try:
  9862. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9863. removed = cleanup_orphaned_timelapse_sessions()
  9864. if removed:
  9865. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9866. except Exception as e:
  9867. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9868. # Start expected-print TTL eviction (prevents memory leak when prints are
  9869. # registered but on_print_start never fires)
  9870. start_expected_prints_cleanup()
  9871. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9872. start_auth_cleanup()
  9873. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9874. from backend.app.services import announcements as announcements_service
  9875. announcements_service.start()
  9876. from backend.app.services.printer_media import start_printer_download_cleanup
  9877. start_printer_download_cleanup()
  9878. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9879. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9880. from backend.app.services.loop_watchdog import start_loop_watchdog
  9881. start_loop_watchdog()
  9882. # Initialize virtual printer manager and sync from DB
  9883. from backend.app.services.virtual_printer import virtual_printer_manager
  9884. virtual_printer_manager.set_session_factory(async_session)
  9885. virtual_printer_manager.set_printer_manager(printer_manager)
  9886. try:
  9887. await virtual_printer_manager.sync_from_db()
  9888. logging.info("Virtual printer manager synced from database")
  9889. except Exception as e:
  9890. logging.warning("Failed to sync virtual printers: %s", e)
  9891. yield
  9892. # Shutdown
  9893. print_scheduler.stop()
  9894. smart_plug_manager.stop_scheduler()
  9895. ha_sensor_manager.stop()
  9896. location_ha_sensor_manager.stop()
  9897. notification_service.stop_digest_scheduler()
  9898. await notify_live_activities.close()
  9899. await notify_widgets.close()
  9900. await telegram_reaction_poller.aclose()
  9901. github_backup_service.stop_scheduler()
  9902. local_backup_service.stop_scheduler()
  9903. library_trash_service.stop_scheduler()
  9904. archive_purge_service.stop_scheduler()
  9905. obico_detection_service.stop()
  9906. stop_ams_history_recording()
  9907. stop_printer_sensor_history_recording()
  9908. stop_runtime_tracking()
  9909. stop_spoolbuddy_watchdog()
  9910. stop_camera_cleanup()
  9911. stop_connection_watchdog()
  9912. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9913. stop_loop_watchdog()
  9914. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9915. # cleanly rather than waiting on a queue that nothing will ever fill.
  9916. try:
  9917. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9918. await shutdown_all_broadcasters()
  9919. except Exception as e:
  9920. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9921. stop_expected_prints_cleanup()
  9922. stop_auth_cleanup()
  9923. from backend.app.services import announcements as announcements_service
  9924. announcements_service.stop()
  9925. from backend.app.services.printer_media import stop_printer_download_cleanup
  9926. await stop_printer_download_cleanup()
  9927. printer_manager.disconnect_all()
  9928. slot_unlink_grace.reset()
  9929. await close_spoolman_client()
  9930. # Stop all virtual printer services
  9931. await virtual_printer_manager.stop_all()
  9932. await mqtt_smart_plug_service.disconnect(timeout=2)
  9933. await mqtt_relay.disconnect(timeout=2)
  9934. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9935. set_shared_http_client(None)
  9936. set_shared_makerworld_http_client(None)
  9937. set_shared_orca_http_client(None)
  9938. await _shared_cloud_http_client.aclose()
  9939. # Checkpoint WAL (SQLite only) and close all database connections
  9940. from backend.app.core.db_dialect import is_sqlite
  9941. if is_sqlite():
  9942. try:
  9943. async with engine.begin() as conn:
  9944. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9945. logging.info("WAL checkpoint completed")
  9946. except Exception as e:
  9947. logging.warning("WAL checkpoint failed: %s", e)
  9948. await engine.dispose()
  9949. app = FastAPI(
  9950. title=app_settings.app_name,
  9951. description="Archive and manage Bambu Lab 3MF files",
  9952. version=APP_VERSION,
  9953. lifespan=lifespan,
  9954. )
  9955. # Added first so it sits innermost, next to the routes: a refused header's value
  9956. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9957. app.add_middleware(RefusedHeaderResponseMask)
  9958. def _json_safe(value):
  9959. """The validation errors with every non-finite number written as text."""
  9960. if isinstance(value, float) and not math.isfinite(value):
  9961. return str(value)
  9962. if isinstance(value, dict):
  9963. return {key: _json_safe(item) for key, item in value.items()}
  9964. if isinstance(value, list | tuple):
  9965. return [_json_safe(item) for item in value]
  9966. return value
  9967. @app.exception_handler(RequestValidationError)
  9968. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  9969. """FastAPI's own 422, except that it survives a non-finite number.
  9970. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  9971. them), and the default handler echoes the input back in its errors,
  9972. which JSON cannot hold: the request ended in an error instead of a 422.
  9973. """
  9974. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  9975. # =============================================================================
  9976. # Authentication Middleware - Secures ALL API routes by default
  9977. # =============================================================================
  9978. # Public routes that don't require authentication even when auth is enabled
  9979. PUBLIC_API_ROUTES = {
  9980. # Auth routes needed before/during login
  9981. "/api/v1/auth/status",
  9982. "/api/v1/auth/login",
  9983. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9984. # Advanced auth status needed for login page
  9985. "/api/v1/auth/advanced-auth/status",
  9986. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9987. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9988. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9989. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9990. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9991. # OIDC routes that must be reachable without a JWT
  9992. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9993. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9994. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9995. # Connected apps: the app's server swaps a code for the user's identity,
  9996. # authenticated by its client secret rather than a login token.
  9997. "/api/v1/connect/token",
  9998. # Version check for updates (no sensitive data)
  9999. "/api/v1/updates/version",
  10000. # Metrics endpoint handles its own prometheus_token authentication
  10001. "/api/v1/metrics",
  10002. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10003. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10004. # hostname / timezone / locale and the chrony NTP-gate state. The
  10005. # response contains user-set defaults and a public sync flag — no
  10006. # secrets. Without this entry the global auth middleware returns 401
  10007. # before the route handler runs, regardless of the route's own
  10008. # "no auth required" intent.
  10009. "/api/v1/system/appliance",
  10010. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10011. # authenticates with a long-lived ``camwall``-scoped token in the query
  10012. # string — exactly like the camera streams two lists below, and for the same
  10013. # reason (no header to put a JWT in). "Public" here only means the middleware
  10014. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10015. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10016. # plain ``camera_stream`` token does NOT open this door.
  10017. "/api/v1/camwall/printers",
  10018. # Overlay branding: the route enforces overlay-scoped token authentication.
  10019. "/api/v1/overlay-branding/logo",
  10020. }
  10021. # Route prefixes that are public (for routes with dynamic segments)
  10022. PUBLIC_API_PREFIXES = [
  10023. # WebSocket connections handle their own auth
  10024. "/api/v1/ws",
  10025. # OIDC authorize redirects — include provider_id in path
  10026. "/api/v1/auth/oidc/authorize/",
  10027. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10028. # a phone with no session, so no header can carry a JWT — the single-use
  10029. # capability token in the path IS the credential (same reasoning as the
  10030. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10031. # good/reject on the one archive the token was minted for.
  10032. "/api/v1/archives/confirm/",
  10033. ]
  10034. # Route patterns that are public (read-only display data)
  10035. # These are checked with "in path" - needed because browsers load images/videos
  10036. # via <img src> and <video src> which don't include Authorization headers
  10037. PUBLIC_API_PATTERNS = [
  10038. # Thumbnails
  10039. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10040. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10041. # Images and media
  10042. "/photos/", # /archives/{id}/photos/{filename}
  10043. "/project-image/", # /archives/{id}/project-image/{path}
  10044. "/qrcode", # /archives/{id}/qrcode
  10045. "/timelapse", # /archives/{id}/timelapse (video)
  10046. "/cover", # /printers/{id}/cover
  10047. "/icon", # /external-links/{id}/icon
  10048. # Camera (streams loaded via <img> tag)
  10049. "/camera/stream", # /printers/{id}/camera/stream
  10050. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10051. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10052. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10053. # string (same reasoning as the camera streams above — no header to carry a
  10054. # JWT). "Public" only means the middleware steps aside; the route still runs
  10055. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10056. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10057. "/overlay-status", # /printers/{id}/overlay-status
  10058. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10059. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10060. # download token in the URL path instead.
  10061. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10062. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10063. # and these patterns match by substring. Without its own entry the middleware
  10064. # 401s the slicer's header-less request before the route's token check runs,
  10065. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10066. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10067. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10068. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10069. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10070. ]
  10071. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10072. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10073. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10074. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10075. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10076. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10077. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10078. Invalid entries are dropped with a warning rather than failing startup, so
  10079. a typo in one origin doesn't take the whole deployment down.
  10080. """
  10081. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10082. if not raw:
  10083. return ()
  10084. valid: list[str] = []
  10085. for item in raw.split(","):
  10086. candidate = item.strip()
  10087. if not candidate:
  10088. continue
  10089. try:
  10090. parsed = urlparse(candidate)
  10091. except ValueError as e:
  10092. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10093. continue
  10094. if parsed.scheme not in ("http", "https"):
  10095. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10096. continue
  10097. if not parsed.netloc:
  10098. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10099. continue
  10100. if parsed.path and parsed.path != "/":
  10101. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10102. continue
  10103. if parsed.query or parsed.fragment:
  10104. _security_headers_logger.warning(
  10105. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10106. )
  10107. continue
  10108. if "*" in parsed.netloc:
  10109. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10110. continue
  10111. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10112. if valid:
  10113. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10114. return tuple(valid)
  10115. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10116. def _frame_ancestors(default_value: str) -> str:
  10117. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10118. ``default_value`` is the strict directive used when the operator has not
  10119. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10120. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10121. Settings URL builder's preview). When trusted origins
  10122. are configured, ``'self'`` is always included so same-origin embedding never
  10123. breaks even if an operator forgets to add their own origin to the list.
  10124. """
  10125. if _TRUSTED_FRAME_ORIGINS:
  10126. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10127. return f"frame-ancestors {default_value};"
  10128. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10129. # patterns are anchored on the exact emitted name so the relaxed policies
  10130. # below can never apply to any other asset.
  10131. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10132. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10133. # -> /assets/pdf.worker.min-<hash>.js
  10134. # Vite also emits a one-line chunk under the second name that only exports the
  10135. # worker's URL. The page imports it as a module, and a module script is run
  10136. # under the importing document's policy, never its own response's, so it
  10137. # matching as well changes nothing.
  10138. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10139. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10140. @app.middleware("http")
  10141. async def security_headers_middleware(request, call_next):
  10142. """Add standard HTTP security headers to every response."""
  10143. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10144. # changes nothing for Bambuddy's own pages — index.html has no inline
  10145. # scripts since the SW registration moved to /sw-register.js. The reason
  10146. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10147. # script injected into the HTML on the edge, with a fresh hash on every
  10148. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10149. # it clones the same nonce onto its injected <script>, and the inline
  10150. # script passes the policy without us needing 'unsafe-inline'. See
  10151. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10152. csp_nonce = secrets.token_urlsafe(16)
  10153. # Routes that render their own HTML need it too, or their inline script is
  10154. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10155. # one that does: it submits its own form so a verdict still costs one tap.
  10156. request.state.csp_nonce = csp_nonce
  10157. response = await call_next(request)
  10158. response.headers["X-Content-Type-Options"] = "nosniff"
  10159. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10160. # browsers honour CSP frame-ancestors instead, and the legacy
  10161. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10162. # When operators have explicitly allowlisted trusted frame origins (#1191
  10163. # — typically Home Assistant on a different port), drop X-Frame-Options
  10164. # and let the CSP-side frame-ancestors directive govern embedding.
  10165. if not _TRUSTED_FRAME_ORIGINS:
  10166. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10167. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10168. # Content-Security-Policy for the React SPA.
  10169. # Notes:
  10170. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10171. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10172. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10173. # - media-src blob:: timelapse video player uses Blob URLs.
  10174. # - font-src data:: some icon fonts are embedded as data URIs.
  10175. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10176. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10177. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10178. # default CSP would render a blank page.
  10179. response.headers["Content-Security-Policy"] = (
  10180. "default-src 'self'; "
  10181. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10182. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10183. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10184. "connect-src 'self'; "
  10185. "font-src 'self' data: https://fonts.gstatic.com; "
  10186. "worker-src 'self' blob:; "
  10187. "object-src 'none'; "
  10188. "base-uri 'self'; " + _frame_ancestors("'none'")
  10189. )
  10190. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10191. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10192. # its emscripten/embind glue generates invoker functions with `new
  10193. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10194. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10195. # own response — not the document's — so relaxing it here confines
  10196. # eval to that DOM-less worker context. The document policy below
  10197. # stays nonce-strict, and this response header has no effect when the
  10198. # file is merely fetched (a fetch's CSP is enforced against the
  10199. # requesting document, not the resource's own headers).
  10200. response.headers["Content-Security-Policy"] = (
  10201. "default-src 'self'; "
  10202. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10203. "connect-src 'self'; "
  10204. "object-src 'none'; "
  10205. "base-uri 'self'; " + _frame_ancestors("'none'")
  10206. )
  10207. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10208. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10209. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10210. # rule as the STEP worker above: the policy that governs a dedicated
  10211. # worker is the one delivered with its own script, so the wasm compile
  10212. # has to be permitted here rather than on the document. Unlike the STEP
  10213. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10214. response.headers["Content-Security-Policy"] = (
  10215. "default-src 'self'; "
  10216. "script-src 'self' 'wasm-unsafe-eval'; "
  10217. "connect-src 'self'; "
  10218. "object-src 'none'; "
  10219. "base-uri 'self'; " + _frame_ancestors("'none'")
  10220. )
  10221. else:
  10222. # The streaming overlay is embedded same-origin by the URL builder's
  10223. # preview in Settings (#1422), so this branch allows 'self'.
  10224. # Embedding from anywhere else is still refused: 'self'
  10225. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10226. # a clickjacking page on another host is blocked exactly as before.
  10227. # (The overlay draws status over a camera feed and its only interactive
  10228. # element is the logo link, so there is nothing to bait a click into
  10229. # even from a same-origin framer.) Cross-origin embedding of the
  10230. # overlay — Home Assistant on another port — remains what
  10231. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10232. # allowlist in.
  10233. #
  10234. # The connected-app consent page (/connect/authorize) gets the same
  10235. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10236. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10237. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10238. # requires every ancestor to be this origin, so a foreign page -- a
  10239. # sidebar link's site included -- still cannot frame the consent
  10240. # screen to bait a click.
  10241. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10242. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10243. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10244. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10245. # the policy served with their own script, so each gets it in its own
  10246. # branch above and the document policy stays as strict as it was.
  10247. response.headers["Content-Security-Policy"] = (
  10248. "default-src 'self'; "
  10249. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10250. "style-src 'self' 'unsafe-inline'; "
  10251. "img-src 'self' data: blob:; "
  10252. "media-src 'self' blob:; "
  10253. "connect-src 'self' ws: wss:; "
  10254. "font-src 'self' data:; "
  10255. "object-src 'none'; "
  10256. "base-uri 'self'; "
  10257. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10258. )
  10259. if request.url.scheme == "https":
  10260. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10261. return response
  10262. @app.middleware("http")
  10263. async def auth_middleware(request, call_next):
  10264. """Enforce authentication on all API routes when auth is enabled.
  10265. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10266. regardless of whether individual routes have auth dependencies.
  10267. """
  10268. from starlette.responses import JSONResponse
  10269. path = request.url.path
  10270. # Only apply to API routes
  10271. if not path.startswith("/api/"):
  10272. return await call_next(request)
  10273. # Allow public routes
  10274. if path in PUBLIC_API_ROUTES:
  10275. return await call_next(request)
  10276. # Allow public prefixes
  10277. for prefix in PUBLIC_API_PREFIXES:
  10278. if path.startswith(prefix):
  10279. return await call_next(request)
  10280. # Allow public patterns (read-only display data like thumbnails)
  10281. for pattern in PUBLIC_API_PATTERNS:
  10282. if pattern in path:
  10283. return await call_next(request)
  10284. # Check if auth is enabled. Fail CLOSED on any exception during the
  10285. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10286. # an attacker who could force a DB exception (e.g. file-descriptor
  10287. # exhaustion via login flood) bypass auth on every protected endpoint.
  10288. # Only the probe is guarded: the request itself runs outside the try, so an
  10289. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10290. try:
  10291. async with async_session() as db:
  10292. from backend.app.core.auth import is_auth_enabled
  10293. auth_enabled = await is_auth_enabled(db)
  10294. except Exception:
  10295. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10296. return JSONResponse(
  10297. status_code=503,
  10298. content={"detail": "Authentication service temporarily unavailable"},
  10299. )
  10300. if not auth_enabled:
  10301. # Auth disabled, allow all requests
  10302. return await call_next(request)
  10303. # Auth is enabled - require valid token
  10304. auth_header = request.headers.get("Authorization")
  10305. x_api_key = request.headers.get("X-API-Key")
  10306. # Check for API key auth first
  10307. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10308. # API key authentication - let the request through to be validated by route handler
  10309. # API keys are validated per-route since they have different permission levels
  10310. return await call_next(request)
  10311. # Check for JWT auth
  10312. if not auth_header or not auth_header.startswith("Bearer "):
  10313. return JSONResponse(
  10314. status_code=401,
  10315. content={"detail": "Authentication required"},
  10316. headers={"WWW-Authenticate": "Bearer"},
  10317. )
  10318. # Validate JWT token
  10319. import jwt
  10320. try:
  10321. from backend.app.core.auth import (
  10322. ALGORITHM,
  10323. SECRET_KEY,
  10324. _is_token_fresh,
  10325. get_user_by_username,
  10326. is_jti_revoked,
  10327. )
  10328. token = auth_header.replace("Bearer ", "")
  10329. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10330. username = payload.get("sub")
  10331. if not username:
  10332. raise ValueError("No username in token")
  10333. jti = payload.get("jti")
  10334. if not jti:
  10335. raise ValueError("No jti in token")
  10336. iat = payload.get("iat")
  10337. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10338. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10339. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10340. async with async_session() as db:
  10341. if await is_jti_revoked(jti, db):
  10342. return JSONResponse(
  10343. status_code=401,
  10344. content={"detail": "Token has been revoked"},
  10345. headers={"WWW-Authenticate": "Bearer"},
  10346. )
  10347. user = await get_user_by_username(db, username)
  10348. if not user or not user.is_active:
  10349. return JSONResponse(
  10350. status_code=401,
  10351. content={"detail": "User not found or inactive"},
  10352. headers={"WWW-Authenticate": "Bearer"},
  10353. )
  10354. if not _is_token_fresh(iat, user):
  10355. return JSONResponse(
  10356. status_code=401,
  10357. content={"detail": "Token no longer valid"},
  10358. headers={"WWW-Authenticate": "Bearer"},
  10359. )
  10360. except jwt.ExpiredSignatureError:
  10361. return JSONResponse(
  10362. status_code=401,
  10363. content={"detail": "Token has expired"},
  10364. headers={"WWW-Authenticate": "Bearer"},
  10365. )
  10366. except (jwt.InvalidTokenError, ValueError):
  10367. return JSONResponse(
  10368. status_code=401,
  10369. content={"detail": "Invalid token"},
  10370. headers={"WWW-Authenticate": "Bearer"},
  10371. )
  10372. except Exception:
  10373. # Not a bad token but a failure checking it (database, pool): refuse,
  10374. # as for the probe above, rather than answer 401 -- the frontend reads
  10375. # a 401 from /auth/me as final and signs the user out.
  10376. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10377. return JSONResponse(
  10378. status_code=503,
  10379. content={"detail": "Authentication service temporarily unavailable"},
  10380. )
  10381. return await call_next(request)
  10382. @app.middleware("http")
  10383. async def trace_id_middleware(request, call_next):
  10384. """Stamp every HTTP request with a trace ID and echo it back.
  10385. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10386. @app.middleware decorators LIFO, so the last-decorated runs first
  10387. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10388. which means auth-middleware log lines (and every line emitted on the
  10389. way down to and back from the route handler) all carry the same
  10390. trace ID. If we put it before auth, auth's logs would be stamped
  10391. with the *previous* request's ID — useless for correlation.
  10392. Honours an inbound ``X-Trace-Id`` header so callers running their
  10393. own tracing can correlate their span IDs with our log lines, but
  10394. only if the value passes the whitelist gate in
  10395. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10396. rejected (too long, contains control chars, etc.) silently triggers
  10397. a freshly minted server-side ID rather than failing the request.
  10398. The minted (or echoed) ID is set on a ContextVar so that every log
  10399. record emitted during the request — application logs *and* uvicorn's
  10400. access log — carries it via TraceIDFilter, and is also written to
  10401. the ``X-Trace-Id`` response header so clients can pin a server-side
  10402. log search to the exact request they made.
  10403. """
  10404. from backend.app.core.trace import (
  10405. generate_trace_id,
  10406. normalise_inbound_trace_id,
  10407. trace_id_var,
  10408. )
  10409. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10410. trace_id = inbound if inbound is not None else generate_trace_id()
  10411. token = trace_id_var.set(trace_id)
  10412. try:
  10413. response = await call_next(request)
  10414. finally:
  10415. # Reset the ContextVar so a record emitted in a totally
  10416. # unrelated background task that just happens to inherit this
  10417. # context doesn't keep referencing this request's ID forever.
  10418. # In practice ContextVar.reset is best-effort under asyncio
  10419. # task-spawn semantics, but the cost is one attribute write so
  10420. # we may as well do it.
  10421. trace_id_var.reset(token)
  10422. response.headers["X-Trace-Id"] = trace_id
  10423. return response
  10424. # API routes
  10425. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10426. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10427. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10428. app.include_router(users.router, prefix=app_settings.api_prefix)
  10429. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10430. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10431. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10432. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10433. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10434. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10435. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10436. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10437. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10438. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10439. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10440. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10441. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10442. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10443. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10444. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10445. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10446. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10447. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10448. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10449. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10450. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10451. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10452. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10453. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10454. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10455. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10456. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10457. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10458. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10459. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10460. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10461. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10462. app.include_router(library.router, prefix=app_settings.api_prefix)
  10463. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10464. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10465. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10466. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10467. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10468. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10469. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10470. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10471. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10472. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10473. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10474. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10475. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10476. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10477. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10478. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10479. app.include_router(system.router, prefix=app_settings.api_prefix)
  10480. app.include_router(support.router, prefix=app_settings.api_prefix)
  10481. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10482. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10483. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10484. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10485. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10486. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10487. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10488. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10489. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10490. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10491. # Serve static files (React build)
  10492. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10493. # Compressed, and cached for good where Vite hashed the name (#3175).
  10494. app.mount(
  10495. "/assets",
  10496. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10497. name="assets",
  10498. )
  10499. if (app_settings.static_dir / "img").exists():
  10500. app.mount(
  10501. "/img",
  10502. StaticFiles(directory=app_settings.static_dir / "img"),
  10503. name="img",
  10504. )
  10505. if (app_settings.static_dir / "icons").exists():
  10506. app.mount(
  10507. "/icons",
  10508. StaticFiles(directory=app_settings.static_dir / "icons"),
  10509. name="icons",
  10510. )
  10511. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10512. # falls through to the SPA catch-all and returns index.html, which the
  10513. # browser's font sanitizer rejects ("downloadable font: rejected by
  10514. # sanitizer").
  10515. if (app_settings.static_dir / "fonts").exists():
  10516. app.mount(
  10517. "/fonts",
  10518. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10519. name="fonts",
  10520. )
  10521. @app.get("/")
  10522. async def serve_frontend():
  10523. """Serve the React frontend."""
  10524. index_file = app_settings.static_dir / "index.html"
  10525. if index_file.exists():
  10526. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10527. return {
  10528. "message": "Bambuddy API",
  10529. "docs": "/docs",
  10530. "frontend": "Build and place React app in /static directory",
  10531. }
  10532. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10533. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10534. # forever, but the HTML wrapping it is the only file that knows which hash
  10535. # is current. Without explicit cache-control headers Chromium decides
  10536. # heuristically (typically 10% of the time since Last-Modified) and on
  10537. # long-running kiosks happily serves stale HTML across browser restarts.
  10538. # That stale HTML references an old bundle hash, the old bundle is also
  10539. # in the disk cache, and the user ends up running pre-update JS forever
  10540. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10541. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10542. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10543. @app.get("/health")
  10544. async def health_check():
  10545. """Health check endpoint."""
  10546. return {"status": "healthy"}
  10547. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10548. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10549. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10550. # in deployment debugging.
  10551. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10552. async def serve_manifest():
  10553. """Serve PWA manifest."""
  10554. manifest_file = app_settings.static_dir / "manifest.json"
  10555. if manifest_file.exists():
  10556. return FileResponse(manifest_file, media_type="application/manifest+json")
  10557. return {"error": "Manifest not found"}
  10558. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10559. async def serve_service_worker():
  10560. """Serve service worker."""
  10561. sw_file = app_settings.static_dir / "sw.js"
  10562. if sw_file.exists():
  10563. return FileResponse(
  10564. sw_file,
  10565. media_type="application/javascript",
  10566. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10567. )
  10568. return {"error": "Service worker not found"}
  10569. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10570. async def serve_sw_register():
  10571. """Serve the service-worker registration bootstrap script.
  10572. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10573. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10574. """
  10575. reg_file = app_settings.static_dir / "sw-register.js"
  10576. if reg_file.exists():
  10577. return FileResponse(reg_file, media_type="application/javascript")
  10578. return {"error": "sw-register.js not found"}
  10579. # ── GCode viewer static files ────────────────────────────────────────────────
  10580. # Catch-all route for React Router (must be last)
  10581. @app.get("/{full_path:path}")
  10582. async def serve_spa(full_path: str):
  10583. """Serve React app for client-side routing."""
  10584. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10585. if full_path.startswith("api/"):
  10586. from fastapi import HTTPException
  10587. raise HTTPException(status_code=404, detail="Not found")
  10588. index_file = app_settings.static_dir / "index.html"
  10589. if index_file.exists():
  10590. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10591. return {"error": "Frontend not built"}