main.py 558 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523
  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 urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, inspect as sa_inspect, or_, select, text, update
  19. from sqlalchemy.exc import IntegrityError
  20. from sqlalchemy.orm.exc import StaleDataError
  21. from backend.app.api.routes import (
  22. ams_history,
  23. announcements,
  24. api_keys,
  25. archive_purge,
  26. archives,
  27. auth,
  28. bug_report,
  29. camera,
  30. camwall,
  31. cloud,
  32. connected_apps,
  33. discovery,
  34. external_links,
  35. filaments,
  36. finance,
  37. firmware,
  38. github_backup,
  39. groups,
  40. ha_sensors,
  41. inventory,
  42. kprofiles,
  43. labels,
  44. library,
  45. library_tags,
  46. library_trash,
  47. library_variants,
  48. local_backup,
  49. local_presets,
  50. location_ha_sensors,
  51. maintenance,
  52. makerworld,
  53. manyfold,
  54. metrics,
  55. mfa,
  56. notification_templates,
  57. notifications,
  58. obico,
  59. orca_cloud,
  60. overlay_branding,
  61. pending_uploads,
  62. pipeline_runs,
  63. print_log,
  64. print_queue,
  65. printer_locations,
  66. printer_sensor_history,
  67. printers,
  68. projects,
  69. scheduled_dryings,
  70. settings as settings_routes,
  71. slice_jobs,
  72. slicer_pipelines,
  73. slicer_presets,
  74. smart_plugs,
  75. sponsor_prompt,
  76. spoolbuddy,
  77. spoolman,
  78. spoolman_inventory,
  79. support,
  80. system,
  81. updates,
  82. user_notifications,
  83. users,
  84. virtual_printers,
  85. webhook,
  86. websocket,
  87. )
  88. from backend.app.api.routes.maintenance import (
  89. _get_printer_maintenance_internal,
  90. ensure_default_types,
  91. maintenance_alert_values,
  92. )
  93. from backend.app.api.routes.support import init_debug_logging
  94. from backend.app.core.config import APP_VERSION, settings as app_settings
  95. from backend.app.core.database import async_session, engine, init_db
  96. from backend.app.core.static_assets import AssetStaticFiles
  97. from backend.app.core.tasks import spawn_background_task
  98. from backend.app.core.websocket import ws_manager
  99. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  100. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  101. from backend.app.services.archive_cost_estimate import (
  102. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  103. )
  104. from backend.app.services.archive_purge import archive_purge_service
  105. from backend.app.services.bambu_ftp import (
  106. FileNotOnPrinterError,
  107. cache_3mf_download,
  108. clear_3mf_cache,
  109. download_file_async,
  110. download_file_try_paths_async,
  111. ftps_handshake_blocked,
  112. get_cached_3mf,
  113. get_ftp_retry_settings,
  114. normalize_3mf_name,
  115. with_ftp_retry,
  116. )
  117. from backend.app.services.bambu_mqtt import PrinterState
  118. from backend.app.services.camera_light import camera_light
  119. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  120. from backend.app.services.github_backup import github_backup_service
  121. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  122. from backend.app.services.library_trash import library_trash_service
  123. from backend.app.services.local_backup import local_backup_service
  124. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  125. from backend.app.services.mqtt_relay import mqtt_relay
  126. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  127. from backend.app.services.notification_service import notification_service
  128. from backend.app.services.notify_live_activities import notify_live_activities
  129. from backend.app.services.notify_widgets import notify_widgets
  130. from backend.app.services.obico_detection import obico_detection_service
  131. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  132. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  133. from backend.app.services.print_scheduler import scheduler as print_scheduler
  134. from backend.app.services.print_storage import (
  135. REASON_FTP_TRANSFER_FAILED,
  136. REASON_FTPS_COOLOFF,
  137. external_storage_present,
  138. ftp_probe_paths,
  139. print_file_reachable_over_ftp,
  140. )
  141. from backend.app.services.printer_manager import (
  142. init_printer_connections,
  143. parse_plate_id,
  144. printer_manager,
  145. printer_state_to_dict,
  146. resolve_plate_id,
  147. )
  148. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  149. from backend.app.services.slot_nozzle import (
  150. nozzle_diameter_for_extruder,
  151. nozzle_flow_for_extruder,
  152. resolve_slot_nozzle,
  153. )
  154. from backend.app.services.smart_plug_manager import smart_plug_manager
  155. from backend.app.services.spool_assignment_notifications import (
  156. notify_missing_spool_assignments_on_print_start,
  157. )
  158. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  159. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  160. from backend.app.services.spoolman_tracking import (
  161. cleanup_tracking as _cleanup_spoolman_tracking,
  162. report_usage as _report_spoolman_usage,
  163. store_print_data as _store_spoolman_print_data,
  164. )
  165. from backend.app.services.telegram_reactions import telegram_reaction_poller
  166. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  167. from backend.app.utils.ams_humidity import ams_humidity_percent
  168. from backend.app.utils.filament_types import printer_filament_type
  169. from backend.app.utils.fts_routing import extruder_for_inlet
  170. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  171. from backend.app.utils.print_jobs import is_internal_printer_job
  172. # =============================================================================
  173. # Dependency Check - runs before other imports to give helpful error messages
  174. # =============================================================================
  175. def _start_error_server(missing_packages: list):
  176. """Start a minimal HTTP server to display dependency errors in browser."""
  177. import os
  178. import signal
  179. from http.server import BaseHTTPRequestHandler, HTTPServer
  180. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  181. html = f"""<!DOCTYPE html>
  182. <html>
  183. <head>
  184. <title>Bambuddy - Setup Required</title>
  185. <style>
  186. body {{
  187. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  188. background: #0f172a; color: #e2e8f0;
  189. display: flex; justify-content: center; align-items: center;
  190. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  191. }}
  192. .container {{
  193. background: #1e293b; border-radius: 12px; padding: 40px;
  194. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  195. }}
  196. h1 {{ color: #f87171; margin-bottom: 10px; }}
  197. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  198. .packages {{
  199. background: #0f172a; border-radius: 8px; padding: 20px;
  200. margin: 20px 0; text-align: left;
  201. }}
  202. .packages ul {{ margin: 0; padding-left: 20px; }}
  203. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  204. .command {{
  205. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  206. margin: 15px 0; font-family: monospace; color: #4ade80;
  207. text-align: left; overflow-x: auto;
  208. }}
  209. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  210. </style>
  211. </head>
  212. <body>
  213. <div class="container">
  214. <h1>Setup Required</h1>
  215. <h2>Missing Python packages</h2>
  216. <div class="packages"><ul>{packages_html}</ul></div>
  217. <p>To fix, run this command on your server:</p>
  218. <div class="command">pip install -r requirements.lock</div>
  219. <p>Or if using a virtual environment:</p>
  220. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  221. <p class="note">After installing, restart Bambuddy:<br>
  222. <code>sudo systemctl restart bambuddy</code></p>
  223. </div>
  224. </body>
  225. </html>"""
  226. class ErrorHandler(BaseHTTPRequestHandler):
  227. def do_GET(self):
  228. self.send_response(503)
  229. self.send_header("Content-type", "text/html")
  230. self.end_headers()
  231. self.wfile.write(html.encode())
  232. def log_message(self, format, *args):
  233. print(f"[Error Server] {args[0]}")
  234. port = int(os.environ.get("PORT", 8000))
  235. print(f"\nStarting error server on http://0.0.0.0:{port}")
  236. print("Visit this URL in your browser to see the error details.\n")
  237. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  238. def shutdown(signum, frame):
  239. print("\nShutting down error server...")
  240. raise SystemExit(0)
  241. signal.signal(signal.SIGTERM, shutdown)
  242. signal.signal(signal.SIGINT, shutdown)
  243. server.serve_forever()
  244. def check_dependencies():
  245. """Check that all required packages are installed."""
  246. missing = []
  247. # Map of import name -> package name (for pip install)
  248. required = {
  249. "jwt": "PyJWT",
  250. "fastapi": "fastapi",
  251. "uvicorn": "uvicorn",
  252. "sqlalchemy": "sqlalchemy",
  253. "aiosqlite": "aiosqlite",
  254. "pydantic": "pydantic",
  255. "paho.mqtt": "paho-mqtt",
  256. }
  257. for module, package in required.items():
  258. try:
  259. __import__(module)
  260. except ImportError:
  261. missing.append(package)
  262. if missing:
  263. print("\n" + "=" * 60)
  264. print("ERROR: Missing required Python packages!")
  265. print("=" * 60)
  266. print(f"\nMissing packages: {', '.join(missing)}")
  267. print("\nTo fix, run:")
  268. print(" pip install -r requirements.lock")
  269. print("\nOr if using a virtual environment:")
  270. print(" ./venv/bin/pip install -r requirements.lock")
  271. print("=" * 60 + "\n")
  272. _start_error_server(missing)
  273. check_dependencies()
  274. # =============================================================================
  275. # Import settings first for logging configuration
  276. # Configure logging based on settings
  277. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  278. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  279. log_level = getattr(logging, log_level_str, logging.INFO)
  280. # Trace ID column ([-] when no request scope is active — startup, MQTT
  281. # callbacks, scheduled tasks not chained from a request — so the column
  282. # stays visually aligned and missing values are obvious in grep). See
  283. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  284. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  285. # Create root logger
  286. root_logger = logging.getLogger()
  287. root_logger.setLevel(log_level)
  288. # Trace-ID injection: this filter populates record.trace_id from the
  289. # per-request ContextVar so the format string above can reference it.
  290. # Attached to each HANDLER (not the root logger) because Python's
  291. # logging semantics only invoke a logger's filters on records that
  292. # *originated* at that logger — records propagated up from child
  293. # loggers (every named logger in the app) never trigger root's filter.
  294. # Putting it on the handlers means every record any handler emits gets
  295. # trace_id injected just before the formatter runs, regardless of which
  296. # logger created the record. Without this, the formatter raises
  297. # KeyError on every child-logger record and the record is silently
  298. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  299. # partially" bug we hit. See backend/app/core/trace.py for the
  300. # ContextVar the filter reads.
  301. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  302. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  303. from backend.app.core.trace import TraceIDFilter
  304. _trace_id_filter = TraceIDFilter()
  305. # Console handler - always enabled
  306. console_handler = logging.StreamHandler()
  307. console_handler.setLevel(log_level)
  308. console_handler.setFormatter(logging.Formatter(log_format))
  309. console_handler.addFilter(_trace_id_filter)
  310. # A refused header's value (often a token) masked before the line is written.
  311. _refused_header_filter = RefusedHeaderRedactFilter()
  312. console_handler.addFilter(_refused_header_filter)
  313. root_logger.addHandler(console_handler)
  314. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  315. """Send uvicorn's own loggers to bambuddy.log as well.
  316. Both ship with propagate=False, so the root handler never sees them.
  317. uvicorn.access is the record of which endpoint changed server state;
  318. uvicorn.error is where an unhandled route error is logged with its
  319. traceback ("Exception in ASGI application").
  320. """
  321. for name in ("uvicorn.access", "uvicorn.error"):
  322. logging.getLogger(name).addHandler(handler)
  323. # File handler - only in production or if explicitly enabled
  324. if app_settings.log_to_file:
  325. log_file = app_settings.log_dir / "bambuddy.log"
  326. file_handler = RotatingFileHandler(
  327. log_file,
  328. maxBytes=app_settings.log_max_bytes,
  329. backupCount=app_settings.log_backup_count,
  330. encoding="utf-8",
  331. )
  332. file_handler.setLevel(log_level)
  333. file_handler.setFormatter(logging.Formatter(log_format))
  334. file_handler.addFilter(_trace_id_filter)
  335. file_handler.addFilter(_refused_header_filter)
  336. root_logger.addHandler(file_handler)
  337. logging.info("Logging to file: %s", log_file)
  338. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  339. # access logger with propagate=False by default, so without this attach
  340. # there is no on-disk record of which endpoint triggered a server-state
  341. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  342. # for exactly this reason. Filtered to write methods only
  343. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  344. # frontend don't churn the rotation window faster than it's useful.
  345. from backend.app.core.logging_filters import (
  346. CancelledPoolNoiseFilter,
  347. WriteRequestsOnlyFilter,
  348. )
  349. _attach_file_handler_to_uvicorn(file_handler)
  350. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  351. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  352. # Uvicorn's access logger has propagate=False (its own default), so the
  353. # root-attached TraceIDFilter never sees these records. Attach a
  354. # second instance directly so HTTP access lines carry the same trace
  355. # ID column as the application logs they correlate with.
  356. uvicorn_access_logger.addFilter(TraceIDFilter())
  357. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  358. # BaseHTTPMiddleware cancelling the inner task scope on client
  359. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  360. # underlying transaction leak; this filter only suppresses the residual
  361. # log records that pre-existing pools still emit during their cleanup.
  362. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  363. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  364. # handler (console included), whether or not file logging is on.
  365. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  366. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  367. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  368. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  369. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  370. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  371. # keys in the query). Same as the runtime log-level toggle in support.py.
  372. logging.getLogger("httpcore").setLevel(logging.WARNING)
  373. logging.getLogger("httpx").setLevel(logging.WARNING)
  374. # aiosqlite logs every statement with its parameters at DEBUG.
  375. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  376. # Reduce noise from third-party libraries in production
  377. if not app_settings.debug:
  378. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  379. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  380. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  381. # Track active prints: {(printer_id, filename): archive_id}
  382. _active_prints: dict[tuple[int, str], int] = {}
  383. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  384. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  385. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  386. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  387. # instead of running its own grab-now chain when present, so the finish photo
  388. # captures the better-framed pre-bed-drop moment without us having to force
  389. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  390. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  391. #
  392. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  393. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  394. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  395. # bank and the others are not — so the consumer can't tell them apart and
  396. # must not rotate again.
  397. _stage22_finish_frames: dict[int, bytes] = {}
  398. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  399. # `finally` block (whether it captured a frame or not). The consumer in
  400. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  401. # so the FINISH-state fallback path — where moment and completion are dispatched
  402. # back-to-back — doesn't race past the producer with an empty pop, and the
  403. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  404. # grab (Bambu printers allow only one RTSP client at a time).
  405. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  406. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  407. # layer-change and on print-progress advances (#2547) while the model is still
  408. # printing, then consumed by the FINISH-state finish-photo path when the
  409. # dispatcher recorded that it injected End G-code into this print. Bambu
  410. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  411. # plate-swap) has run, so a live grab there would capture the swapped/empty
  412. # plate.
  413. #
  414. # The load-bearing property: both drivers are print telemetry that stops before
  415. # the End G-code executes — no further layer_num increases, and mc_percent
  416. # freezes — so the last banked frame is always the finished print before the
  417. # swap. Anything added as a third driver must hold that same property.
  418. _inprint_frame_bank: dict[int, bytes] = {}
  419. # Monotonic timestamp of the last banked frame per printer — throttles banking
  420. # so tall prints don't add a camera grab on every layer.
  421. _inprint_frame_bank_ts: dict[int, float] = {}
  422. # Minimum seconds between banked frames, except the final object layer which
  423. # always refreshes for the best framing.
  424. _INPRINT_BANK_MIN_INTERVAL = 25.0
  425. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  426. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  427. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  428. # the first connected status update for that connection; transitions back
  429. # to False whenever we observe `state.connected = False` so the next
  430. # reconnect re-arms reconciliation. Keyed by printer_id.
  431. _printer_reconciled_since_connect: dict[int, bool] = {}
  432. # Same edge, same keying, for priming the printer's calibration table exactly
  433. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  434. # is otherwise filled only when someone opens the Profiles page or Configure
  435. # Slot, when a GitHub backup runs, or when the printer happens to answer
  436. # somebody else's query on the report topic. Until then the AMS slot card has
  437. # no K value to show on the printers whose trays carry none of their own
  438. # (#2854 — H2-series report cali_idx and nothing more).
  439. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  440. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  441. # {(printer_id, filename): archive_id}
  442. _expected_prints: dict[tuple[int, str], int] = {}
  443. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  444. # Used by usage tracker to map 3MF slots to physical AMS trays
  445. _print_ams_mappings: dict[int, list[int]] = {}
  446. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  447. _print_cost_center_ids: dict[int, int] = {}
  448. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  449. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  450. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  451. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  452. # for the queue path. Cleared on print completion or TTL eviction.
  453. _print_plate_ids: dict[int, int] = {}
  454. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  455. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  456. _last_progress_milestone: dict[int, int] = {}
  457. # Track whether first layer complete notification has been sent for current print
  458. _first_layer_notified: dict[int, bool] = {}
  459. # Track whether we already sent a kill-switch stop for the current unauthorized print
  460. _unauthorized_print_kill_sent: set[int] = set()
  461. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  462. # lookup briefly so an unknown active print does not query the database on
  463. # every status frame. A short TTL keeps settings changes responsive.
  464. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  465. _kill_switch_setting_cache: tuple[bool, float] | None = None
  466. # Provider notification started when the kill switch stops a print. The later
  467. # MQTT print-complete callback awaits this task and only sends its regular
  468. # provider notification when the immediate attempt failed.
  469. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  470. # HMS faults already notified, with when each was last seen:
  471. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  472. # fault that flickers beside a held notice was forgotten on every gap and
  473. # notified on every return (#3226). The window is long because the measured
  474. # gaps reach 64 s.
  475. _notified_hms_errors: dict[int, dict[str, float]] = {}
  476. _HMS_CLEAR_GRACE_SECONDS = 600.0
  477. # The print state each printer was last seen in, and the faults recorded before
  478. # it last changed, which are forgotten as soon as they are gone (see
  479. # _take_new_hms_faults).
  480. _hms_print_state: dict[int, str] = {}
  481. _hms_forget_when_gone: dict[int, set[str]] = {}
  482. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  483. # Used for snapshot-diff detection at print completion
  484. _timelapse_baselines: dict[int, set[str]] = {}
  485. # Track printers waiting for bed to cool after print completion.
  486. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  487. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  488. _bed_cool_waiters: dict[int, dict] = {}
  489. # Track printers where the user explicitly stopped the print from the queue UI.
  490. # When on_print_complete fires with status "failed" for these printers we treat it
  491. # as "cancelled" (stopped by user) so the correct notification email is sent.
  492. _user_stopped_printers: set[int] = set()
  493. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  494. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  495. # holds the previous observation so we only fire on the True → False edge (a
  496. # False → False repeat doesn't notify; an initial False at startup doesn't
  497. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  498. # holds the per-printer pending asyncio task that fires the notification
  499. # after a debounce window — cancelled if the printer reconnects before the
  500. # window elapses, so transient MQTT blips don't flood the user.
  501. _printer_last_connected: dict[int, bool] = {}
  502. # Printers whose relay offline event went out, so the reconnect publishes the
  503. # matching online event and a blip shorter than the debounce publishes neither.
  504. _printer_offline_published: set[int] = set()
  505. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  506. # Debounce: a printer must stay offline this long before we notify. Sized
  507. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  508. # so a single stale-trigger cooldown isn't enough to fire — only a real
  509. # offline that survives one reconnect attempt notifies.
  510. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  511. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  512. # when status="failed" to label the print's failure_reason in archives.
  513. #
  514. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  515. # which is wrong on two counts:
  516. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  517. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  518. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  519. # the public wiki) as part of its user-cancel sequence. Matching on the module
  520. # alone caused user-cancellations to be archived as "Layer shift" failures.
  521. # We now match by full short code only — anything not in this map leaves
  522. # failure_reason=None rather than guessing.
  523. # Values are the canonical camelCase failure-reason keys, NOT display labels
  524. # (issue #2974). The vocabulary is enforced on writes by
  525. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  526. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  527. # Statistics breakdown. Storing a label here instead put a second spelling of
  528. # the same cause into one column: the Failure Analysis widget groups on the raw
  529. # value, so a print the backend classified and an identical one a user
  530. # classified counted as two different reasons, and the label form could never
  531. # be translated because there was no key for ``t()`` to resolve.
  532. _HMS_FAILURE_REASONS: dict[str, str] = {
  533. # Layer shift / step loss
  534. "0300_4057": "layerShift",
  535. "0300_4068": "layerShift",
  536. "0300_800C": "layerShift",
  537. # Filament runout (printer-side & per-AMS-slot)
  538. "0300_8004": "filamentRunout",
  539. "0700_8011": "filamentRunout",
  540. "0701_8011": "filamentRunout",
  541. "0702_8011": "filamentRunout",
  542. "0703_8011": "filamentRunout",
  543. "0704_8011": "filamentRunout",
  544. "0705_8011": "filamentRunout",
  545. "0706_8011": "filamentRunout",
  546. "0707_8011": "filamentRunout",
  547. "07FF_8011": "filamentRunout",
  548. # Clogged nozzle / extruder
  549. "0300_4006": "cloggedNozzle",
  550. "0300_8016": "cloggedNozzle",
  551. "0300_801C": "cloggedNozzle",
  552. "0700_8003": "cloggedNozzle",
  553. "0700_8007": "cloggedNozzle",
  554. "0700_8013": "cloggedNozzle",
  555. "0701_8003": "cloggedNozzle",
  556. "0701_8007": "cloggedNozzle",
  557. "0701_8013": "cloggedNozzle",
  558. "0702_8003": "cloggedNozzle",
  559. # AI print monitoring — spaghetti / the model coming off the plate.
  560. # `spaghettiDetached` is a key the archive editor already offers for this
  561. # failure mode, not a new one, so a derived reason opens the dropdown on
  562. # that option rather than blank — and survives the next save, which clears
  563. # any value the editor does not recognise.
  564. #
  565. # A module-0x0C row is safe here despite the warning above: that warning is
  566. # about matching on the module alone, and 0C00_8042 is a full short code
  567. # with a documented meaning ("The AI print monitor has detected a spaghetti
  568. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  569. # cannot collide.
  570. #
  571. # 0300_8003's own text ends "before continuing your print", but on an X2D
  572. # it arrives with the print already paused, offering only
  573. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  574. #
  575. # Two neighbours are left out on purpose, so this does not get re-derived:
  576. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  577. # reads as a warning about a print that is still running, not a halt.
  578. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  579. # the waste chute. That is not the print failing.
  580. #
  581. # That line is drawn from the text, not from `severity`, because severity
  582. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  583. # module/error word with no level in it, and bambu_mqtt.py gives every
  584. # print_error entry a flat severity=3. Matching on the short code alone is
  585. # the right shape for derive_failure_reason, not an omission.
  586. "0300_8003": "spaghettiDetached",
  587. "0C00_8042": "spaghettiDetached",
  588. }
  589. def _hms_short_code(attr: int, code: int | str) -> str:
  590. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  591. if isinstance(code, str):
  592. code_int = int(code.replace("0x", ""), 16) if code else 0
  593. else:
  594. code_int = int(code or 0)
  595. attr_int = int(attr or 0)
  596. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  597. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  598. """Derive the failure_reason key for an archived print.
  599. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  600. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  601. no HMS code matches (don't guess — null is honest). The keys are the
  602. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  603. translated at render time.
  604. """
  605. if status in ("aborted", "cancelled"):
  606. return "userCancelled"
  607. if status != "failed":
  608. return None
  609. for err in hms_errors or []:
  610. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  611. if short_code in _HMS_FAILURE_REASONS:
  612. return _HMS_FAILURE_REASONS[short_code]
  613. return None
  614. # Track created_by_id for expected prints so the user email can be sent even when
  615. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  616. # {(printer_id, filename): created_by_id}
  617. _expected_print_creators: dict[tuple[int, str], int] = {}
  618. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  619. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  620. # updates for the same printer in quick succession (~30 ms apart, observed in
  621. # the wild on H2D + dual AMS).
  622. #
  623. # Without this serialisation, two concurrent on_ams_change callbacks each read
  624. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  625. # the second commit hits
  626. # IntegrityError: duplicate key value violates unique constraint
  627. # "spool_assignment_printer_id_ams_id_tray_id_key"
  628. # SQLite's WAL serial-write semantics had been silently swallowing the race
  629. # until optional Postgres support landed (asyncpg allows true concurrent
  630. # transactions and surfaces the constraint violation).
  631. #
  632. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  633. # assign) are inside the lock. The Spoolman sync block further down stays
  634. # concurrent because it's network-bound and idempotent.
  635. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  636. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  637. """Return the per-printer assignment lock, creating it on first use."""
  638. lock = _ams_assignment_locks.get(printer_id)
  639. if lock is None:
  640. lock = asyncio.Lock()
  641. _ams_assignment_locks[printer_id] = lock
  642. return lock
  643. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  644. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  645. # tag tuple changes for the slot. Cleared when the slot is reported empty
  646. # so remove + reinsert reliably re-prompts the UI.
  647. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  648. async def _broadcast_unknown_tag(
  649. *,
  650. printer_id: int,
  651. ams_id: int,
  652. tray_id: int,
  653. tag_uid: str,
  654. tray_uuid: str,
  655. tray_type: str | None = None,
  656. tray_color: str | None = None,
  657. tray_sub_brands: str | None = None,
  658. tray_count: int | None = None,
  659. ) -> None:
  660. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  661. _logger = logging.getLogger(__name__)
  662. slot_key = (ams_id, tray_id)
  663. tag_key = (tag_uid or "", tray_uuid or "")
  664. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  665. if per_printer.get(slot_key) == tag_key:
  666. _logger.debug(
  667. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  668. printer_id,
  669. ams_id,
  670. tray_id,
  671. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  672. )
  673. return
  674. _logger.info(
  675. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  676. printer_id,
  677. ams_id,
  678. tray_id,
  679. tray_type,
  680. tray_color,
  681. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  682. )
  683. # Broadcast first; only commit the dedup if the WS write succeeds.
  684. # If broadcast raises, the next MQTT push retries instead of being
  685. # permanently silenced by a poisoned dedup entry.
  686. await ws_manager.broadcast(
  687. {
  688. "type": "unknown_tag",
  689. "printer_id": printer_id,
  690. "ams_id": ams_id,
  691. "tray_id": tray_id,
  692. "tag_uid": tag_uid,
  693. "tray_uuid": tray_uuid,
  694. "tray_type": tray_type,
  695. "tray_color": tray_color,
  696. "tray_sub_brands": tray_sub_brands,
  697. "tray_count": tray_count,
  698. }
  699. )
  700. per_printer[slot_key] = tag_key
  701. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  702. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  703. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  704. if per_printer is None:
  705. return
  706. per_printer.pop((ams_id, tray_id), None)
  707. # TTL for expected-print entries: evict registrations older than this to prevent
  708. # unbounded growth when a print is registered but never starts (e.g. printer
  709. # disconnect, app restart, print started from the printer panel).
  710. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  711. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  712. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  713. # Cleanup loop interval
  714. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  715. _expected_prints_cleanup_task: asyncio.Task | None = None
  716. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  717. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  718. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  719. possible_keys: list[tuple[int, str]] = []
  720. filename = (state.gcode_file or state.current_print or "").strip()
  721. subtask_name = (state.subtask_name or "").strip()
  722. if subtask_name:
  723. possible_keys.append((printer_id, subtask_name))
  724. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  725. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  726. if filename:
  727. base_name = filename.rsplit("/", 1)[-1]
  728. if base_name.endswith(".gcode.3mf"):
  729. root_name = base_name[: -len(".gcode.3mf")]
  730. possible_keys.append((printer_id, root_name))
  731. possible_keys.append((printer_id, base_name))
  732. possible_keys.append((printer_id, f"{root_name}.gcode"))
  733. possible_keys.append((printer_id, f"{root_name}.3mf"))
  734. elif base_name.endswith(".3mf"):
  735. root_name = base_name[: -len(".3mf")]
  736. possible_keys.append((printer_id, root_name))
  737. possible_keys.append((printer_id, base_name))
  738. elif base_name.endswith(".gcode"):
  739. root_name = base_name[: -len(".gcode")]
  740. possible_keys.append((printer_id, root_name))
  741. possible_keys.append((printer_id, f"{root_name}.3mf"))
  742. possible_keys.append((printer_id, base_name))
  743. else:
  744. possible_keys.append((printer_id, base_name))
  745. possible_keys.append((printer_id, f"{base_name}.3mf"))
  746. return possible_keys
  747. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  748. """The id of who started the print, unless that user has been deleted since.
  749. Deleting a user forgets them in printer_manager, but a print that ended a
  750. moment before still holds them.
  751. """
  752. if not print_user or print_user.get("user_id") is None:
  753. return None
  754. from backend.app.models.user import User
  755. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  756. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  757. """Check the cheap, process-local print ownership signals."""
  758. if printer_manager.get_current_print_user(printer_id):
  759. return True
  760. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  761. async def _is_printer_kill_switch_enabled_cached() -> bool:
  762. """Return the kill-switch setting without querying on every MQTT frame."""
  763. global _kill_switch_setting_cache
  764. now = time.monotonic()
  765. if _kill_switch_setting_cache is not None:
  766. enabled, expires_at = _kill_switch_setting_cache
  767. if now < expires_at:
  768. return enabled
  769. async with async_session() as db:
  770. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  771. enabled = await is_printer_kill_switch_enabled(db)
  772. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  773. return enabled
  774. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  775. """Resolve whether the current print was started by Bambuddy.
  776. ``None`` means identity is not yet safe to decide. The kill switch must
  777. defer in that case: stopping a print is irreversible, and the first status
  778. frames after a restart may arrive before all subtask fields are populated.
  779. """
  780. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  781. return True
  782. possible_keys = _build_status_print_keys(printer_id, state)
  783. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  784. # is on disk. subtask_id is minted per print and pins the answer to the job
  785. # actually running, rather than to an unrelated one that reuses a filename.
  786. raw_subtask_id = getattr(state, "subtask_id", None)
  787. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  788. if subtask_id in ("", "0"):
  789. return None
  790. from backend.app.models.archive import PrintArchive
  791. result = await db.execute(
  792. select(PrintArchive)
  793. .where(
  794. PrintArchive.printer_id == printer_id,
  795. PrintArchive.status == "printing",
  796. PrintArchive.subtask_id == subtask_id,
  797. )
  798. .order_by(PrintArchive.created_at.desc())
  799. .limit(1)
  800. )
  801. archive = result.scalar_one_or_none()
  802. # An archive row on its own proves nothing: `on_print_start` archives every
  803. # print it observes, including ones started from Bambu Studio or Handy, and
  804. # stamps them with the same status and subtask_id. Authorizing on its mere
  805. # existence would disable the kill switch the moment the 3MF finishes
  806. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  807. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  808. # (carried over from the queue item that started it).
  809. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  810. # Rehydrate the fast in-memory path for subsequent status frames. Include
  811. # both the archive filename and every normalized key reported by MQTT.
  812. _active_prints[(printer_id, archive.filename)] = archive.id
  813. for key in possible_keys:
  814. _active_prints[key] = archive.id
  815. return True
  816. # No dispatch marker. Before calling this someone else's print, check whether
  817. # Bambuddy has a job of its own running on this printer: a library-file
  818. # dispatch has no archive at send time, and an archive created seconds later
  819. # by `on_print_start` carries neither marker. The queue row, which the
  820. # scheduler commits to status="printing" before the MQTT send, is the one
  821. # durable record every Bambuddy print has. It cannot be tied to this
  822. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  823. # print is irreversible, and refusing to act costs nothing but a log line.
  824. from backend.app.models.print_queue import PrintQueueItem
  825. dispatched_here = await db.scalar(
  826. select(PrintQueueItem.id)
  827. .where(
  828. PrintQueueItem.printer_id == printer_id,
  829. PrintQueueItem.status == "printing",
  830. )
  831. .limit(1)
  832. )
  833. if dispatched_here is not None:
  834. return None
  835. return False
  836. async def _send_kill_switch_provider_notification(
  837. printer_id: int,
  838. printer_name: str,
  839. data: dict,
  840. ) -> bool:
  841. """Send the immediate print-stopped provider notification.
  842. Returning a success flag lets the normal MQTT completion path retry when
  843. this early notification could not be delivered.
  844. """
  845. logger = logging.getLogger(__name__)
  846. try:
  847. async with async_session() as db:
  848. await notification_service.on_print_complete(
  849. printer_id,
  850. printer_name,
  851. "stopped",
  852. data,
  853. db,
  854. )
  855. return True
  856. except Exception as e:
  857. logger.warning(
  858. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  859. printer_id,
  860. e,
  861. )
  862. return False
  863. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  864. """Wait for an immediate kill-switch notification, if one was scheduled."""
  865. if task is None:
  866. return False
  867. try:
  868. return await task
  869. except Exception as e:
  870. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  871. return False
  872. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  873. """Capture the smart plug lifetime counter on the archive at print start.
  874. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  875. tracking survives a backend restart mid-print. The print-end handler reads
  876. this value back from the DB and computes the delta against the current
  877. plug counter.
  878. """
  879. _logger = logging.getLogger(__name__)
  880. try:
  881. candidates = await energy_plug_candidates(db, printer_id)
  882. if not candidates:
  883. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  884. return False
  885. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  886. if selected is None:
  887. # Naming the plugs matters here: with several linked to one printer
  888. # this is the difference between "the meter is offline" and "you
  889. # linked only accessories" (#2859).
  890. _logger.warning(
  891. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  892. printer_id,
  893. archive.id,
  894. ", ".join(plug.name for plug in candidates),
  895. )
  896. return False
  897. plug, energy = selected
  898. archive.energy_start_kwh = float(energy["total"])
  899. # With the plug's snapshots, what lets the cost follow the price over
  900. # the print rather than take the price at its end (#1251). A price that
  901. # can't be had must not cost the print its energy reading.
  902. archive.energy_start_at = utcnow_naive()
  903. archive.energy_start_plug_id = plug.id
  904. try:
  905. from backend.app.services.energy_price import current_price
  906. archive.energy_start_price = await current_price(db)
  907. except Exception as e:
  908. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  909. archive.energy_start_price = None
  910. await db.commit()
  911. _logger.info(
  912. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  913. f" ({context})" if context else "",
  914. archive.id,
  915. plug.name,
  916. energy["total"],
  917. )
  918. return True
  919. except Exception as e:
  920. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  921. return False
  922. def forget_print_creator(user_id: int) -> None:
  923. """The print-start emails of a deleted user's jobs go to nobody, not to
  924. whoever is given the id next (SQLite reuses it)."""
  925. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  926. del _expected_print_creators[key]
  927. async def forget_printer(printer_id: int) -> None:
  928. """Drop what is kept for a deleted printer's id, here and in the services.
  929. SQLite used to give the id to the next printer created, which inherited it
  930. all: the running print's owner (its prints passed the kill switch and were
  931. billed to that user), the plate-clear gate, pending and suppressed
  932. notifications, the camera feed, the plate references. Ids are no longer
  933. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  934. stay. Called after the delete is committed, and again by work that was in
  935. flight and wrote state back.
  936. Every printer-keyed map of this module is listed here or, with the reason,
  937. in tests/unit/test_forget_printer.py.
  938. """
  939. from backend.app.api.routes import camera
  940. from backend.app.services import (
  941. bambu_ftp,
  942. kprofile_drift,
  943. layer_timelapse,
  944. plate_detection,
  945. print_dispatch_context,
  946. usage_tracker,
  947. )
  948. from backend.app.services.notify_live_activities import notify_live_activities
  949. from backend.app.services.obico_detection import obico_detection_service
  950. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  951. archive_ids = set()
  952. for tracked in (_active_prints, _expected_prints):
  953. for key in [key for key in tracked if key[0] == printer_id]:
  954. archive_ids.add(tracked.pop(key))
  955. for archive_id in archive_ids:
  956. _print_ams_mappings.pop(archive_id, None)
  957. _print_cost_center_ids.pop(archive_id, None)
  958. _print_plate_ids.pop(archive_id, None)
  959. for tracked in (_expected_print_creators, _expected_print_registered_at):
  960. for key in [key for key in tracked if key[0] == printer_id]:
  961. del tracked[key]
  962. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  963. _ams_index_only_logged.discard(key)
  964. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  965. del _ams_alarm_cooldown[key]
  966. # Pending work that would act on the id: an offline notice, a 3MF retry.
  967. # A kill-switch notice is about a stop that happened and is left to finish.
  968. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  969. task = tasks.pop(printer_id, None)
  970. if task is not None:
  971. task.cancel()
  972. for keyed in (
  973. _stage22_finish_frames,
  974. _stage22_finish_in_flight,
  975. _inprint_frame_bank,
  976. _inprint_frame_bank_ts,
  977. _printer_reconciled_since_connect,
  978. _printer_kprofiles_primed_since_connect,
  979. _last_progress_milestone,
  980. _first_layer_notified,
  981. _kill_switch_notification_tasks,
  982. _notified_hms_errors,
  983. _hms_print_state,
  984. _hms_forget_when_gone,
  985. _timelapse_baselines,
  986. _bed_cool_waiters,
  987. _printer_last_connected,
  988. _unknown_tag_last_broadcast,
  989. _last_status_broadcast,
  990. _connection_watchdog_last_attempt,
  991. ):
  992. keyed.pop(printer_id, None)
  993. for marked in (
  994. _unauthorized_print_kill_sent,
  995. _user_stopped_printers,
  996. _printer_offline_published,
  997. _nozzle_count_updated,
  998. ):
  999. marked.discard(printer_id)
  1000. printer_manager.forget_printer(printer_id)
  1001. print_dispatch_context.clear(printer_id)
  1002. kprofile_drift.forget_printer(printer_id, deleted=True)
  1003. layer_timelapse.cancel_session(printer_id)
  1004. usage_tracker.forget_printer(printer_id)
  1005. obico_detection_service.forget_printer(printer_id)
  1006. bambu_ftp.clear_3mf_cache(printer_id)
  1007. await camera.forget_printer(printer_id)
  1008. printers.clear_cover_cache(printer_id)
  1009. print_scheduler.forget_printer(printer_id)
  1010. notify_live_activities.forget_printer(printer_id)
  1011. plate_detection.remove_printer_references(printer_id)
  1012. def register_expected_print(
  1013. printer_id: int,
  1014. filename: str,
  1015. archive_id: int,
  1016. ams_mapping: list[int] | None = None,
  1017. created_by_id: int | None = None,
  1018. cost_center_id: int | None = None,
  1019. plate_id: int | None = None,
  1020. ):
  1021. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1022. # Store with multiple filename variations to catch different naming patterns
  1023. _expected_prints[(printer_id, filename)] = archive_id
  1024. # Also store without .3mf extension if present
  1025. if filename.endswith(".3mf"):
  1026. base = filename[:-4]
  1027. _expected_prints[(printer_id, base)] = archive_id
  1028. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1029. # Store AMS mapping for usage tracking at print completion
  1030. if ams_mapping is not None:
  1031. _print_ams_mappings[archive_id] = ams_mapping
  1032. if cost_center_id is not None:
  1033. _print_cost_center_ids[archive_id] = cost_center_id
  1034. # Store plate_id for usage tracking when this is a single-plate dispatch from
  1035. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  1036. # file's filament total to the spool instead of just the printed plate (#1697).
  1037. if plate_id is not None:
  1038. _print_plate_ids[archive_id] = plate_id
  1039. # Store created_by_id so the user start email can be sent even when the archive
  1040. # itself has no created_by_id (e.g. library-file-based queue prints)
  1041. if created_by_id is not None:
  1042. _expected_print_creators[(printer_id, filename)] = created_by_id
  1043. if filename.endswith(".3mf"):
  1044. base = filename[:-4]
  1045. _expected_print_creators[(printer_id, base)] = created_by_id
  1046. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1047. # Record registration time for TTL-based eviction
  1048. _registered_at = time.monotonic()
  1049. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1050. if filename.endswith(".3mf"):
  1051. base = filename[:-4]
  1052. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1053. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1054. logging.getLogger(__name__).info(
  1055. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1056. )
  1057. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1058. """Undo :func:`register_expected_print` when the print never went out.
  1059. Registration has to happen *before* the MQTT print command, because the
  1060. printer can report the print before the line after the send executes. So
  1061. every path that registers and then fails to send — a cancel winning the
  1062. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1063. between — leaves an expectation for a print that will never arrive.
  1064. The TTL sweep evicts those after two hours, which is far longer than it
  1065. takes a user to react to a failed dispatch by pressing print again: that
  1066. reprint would be folded into the *old* archive and take the stale
  1067. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1068. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1069. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1070. are keyed by archive, not by file, so they may only be dropped once no
  1071. live key still points at that archive.
  1072. """
  1073. keys = [(printer_id, filename)]
  1074. if filename.endswith(".3mf"):
  1075. base = filename[:-4]
  1076. keys.append((printer_id, base))
  1077. keys.append((printer_id, f"{base}.gcode"))
  1078. removed = False
  1079. for key in keys:
  1080. if _expected_prints.pop(key, None) is not None:
  1081. removed = True
  1082. _expected_print_creators.pop(key, None)
  1083. _expected_print_registered_at.pop(key, None)
  1084. if archive_id not in set(_expected_prints.values()):
  1085. _print_ams_mappings.pop(archive_id, None)
  1086. _print_cost_center_ids.pop(archive_id, None)
  1087. _print_plate_ids.pop(archive_id, None)
  1088. if removed:
  1089. logging.getLogger(__name__).info(
  1090. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1091. printer_id,
  1092. filename,
  1093. archive_id,
  1094. )
  1095. def _compute_run_filament_grams(
  1096. status: str,
  1097. archive_filament_used_grams: float | None,
  1098. progress: float | int | None,
  1099. usage_results: list[dict] | None,
  1100. ) -> float | None:
  1101. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1102. Priority for every status:
  1103. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1104. weight delta — same source that drives "Total Consumed" on the
  1105. Inventory page, so Stats and Inventory totals stay aligned).
  1106. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1107. back to the canonical "this print used X" value).
  1108. 3. For partial statuses: ``estimate * progress%``.
  1109. 4. ``None`` if nothing is known.
  1110. """
  1111. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1112. if tracked_grams > 0:
  1113. return round(tracked_grams, 1)
  1114. if status == "completed":
  1115. return archive_filament_used_grams
  1116. if archive_filament_used_grams:
  1117. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1118. if scale > 0:
  1119. return round(archive_filament_used_grams * scale, 1)
  1120. return None
  1121. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1122. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1123. stored_ams_mapping = data.get("ams_mapping")
  1124. if not stored_ams_mapping and archive_id:
  1125. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1126. return stored_ams_mapping
  1127. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1128. """Resolve plate_id for print start without consuming stored direct-Print state.
  1129. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1130. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1131. read it back at print-start without popping (the entry is popped on print
  1132. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1133. """
  1134. if archive_id is None:
  1135. return None
  1136. return _print_plate_ids.get(archive_id)
  1137. def _partial_progress_scale(progress: int | float | None) -> float:
  1138. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1139. Used by every site that multiplies a "would-have-used" slicer estimate
  1140. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1141. so the three sites in ``_background_notifications`` (and the per-plate
  1142. override helper) can't drift apart on the coercion shape.
  1143. """
  1144. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1145. def _scope_notification_archive_data_to_plate(
  1146. archive_data: dict,
  1147. archive_file_path: str | None,
  1148. plate_id: int | None,
  1149. print_status: str,
  1150. progress: int | float | None,
  1151. base_dir: Path,
  1152. ) -> dict:
  1153. """Override summed-across-plates totals in ``archive_data`` with the values
  1154. for ``plate_id`` so the completion notification reports what was actually
  1155. printed, not the whole project (#1785).
  1156. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1157. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1158. the archive card's "whole project" headline, wrong for the completion
  1159. notification of a single-plate print. The queue UI already re-reads the
  1160. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1161. notification payload (filament grams, time estimate, per-slot breakdown).
  1162. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1163. no per-plate values — in every fail case the original ``archive_data`` is
  1164. returned unchanged so the notification still sends.
  1165. """
  1166. if plate_id is None or not archive_file_path:
  1167. return archive_data
  1168. from backend.app.utils.threemf_tools import (
  1169. extract_filament_usage_from_3mf,
  1170. extract_print_time_from_3mf,
  1171. )
  1172. archive_path = base_dir / archive_file_path
  1173. if not archive_path.exists():
  1174. return archive_data
  1175. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1176. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1177. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1178. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1179. if plate_time:
  1180. archive_data["print_time_seconds"] = plate_time
  1181. # Gate both the grams headline AND the per-slot breakdown on the same
  1182. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1183. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1184. # to the project-level grams the archive columns already provide rather
  1185. # than ship a project-level headline next to an all-zero per-plate
  1186. # breakdown.
  1187. if plate_grams > 0:
  1188. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1189. archive_data["filament_slots"] = [
  1190. {
  1191. "slot_id": s.get("slot_id"),
  1192. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1193. "type": s.get("type", ""),
  1194. "color": s.get("color", ""),
  1195. }
  1196. for s in plate_slots
  1197. ]
  1198. return archive_data
  1199. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1200. """Best-effort filament metadata from the MQTT print-start snapshot.
  1201. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1202. file during print, see #1533) so the fallback PrintArchive still has
  1203. enough filament info to support the inventory views and AMS-expansion
  1204. planning the operator opens it for. Returns a dict with optional
  1205. ``filament_type`` and ``filament_color`` keys in the same
  1206. comma-separated format the 3MF extractor produces, so the rest of the
  1207. codebase treats the fallback archive identically to a normal one.
  1208. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1209. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1210. entries). When supplied, only the slots actually consumed by this
  1211. print contribute. Without it the function falls back to every loaded
  1212. AMS slot — less accurate but still useful.
  1213. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1214. that the unit tests pass directly, AND the on_print_start callback
  1215. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1216. bambu_mqtt service hands to main.py at runtime. The original
  1217. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1218. handled the inner shape and silently returned ``{}`` for every real
  1219. print start, leaving fallback archives' filament fields NULL — the
  1220. exact regression the fix was meant to close. Reported with a log
  1221. proving the AMS state was right there at
  1222. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1223. """
  1224. result: dict[str, str] = {}
  1225. # Look at the on_print_start wrapper first, then the inner shape.
  1226. raw_data = (data or {}).get("raw_data")
  1227. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1228. if not isinstance(ams_root, dict):
  1229. ams_root = (data or {}).get("ams") or {}
  1230. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1231. if not isinstance(ams_units, list) or not ams_units:
  1232. return result
  1233. # Map global tray id (unit * 4 + tray) → (type, color).
  1234. loaded: dict[int, tuple[str, str]] = {}
  1235. for unit in ams_units:
  1236. if not isinstance(unit, dict):
  1237. continue
  1238. try:
  1239. unit_id = int(unit.get("id", 0))
  1240. except (TypeError, ValueError):
  1241. continue
  1242. for tray in unit.get("tray") or []:
  1243. if not isinstance(tray, dict):
  1244. continue
  1245. try:
  1246. tray_id = int(tray.get("id", 0))
  1247. except (TypeError, ValueError):
  1248. continue
  1249. ttype = (tray.get("tray_type") or "").strip()
  1250. tcolor = (tray.get("tray_color") or "").strip().upper()
  1251. if not ttype:
  1252. continue # Empty / unloaded slot.
  1253. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1254. if not loaded:
  1255. return result
  1256. if ams_mapping:
  1257. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1258. filaments = [loaded[g] for g in used_ids if g in loaded]
  1259. if not filaments:
  1260. return result # Mapping points entirely at slots we have no data for.
  1261. else:
  1262. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1263. types_joined = ",".join(f[0] for f in filaments)
  1264. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1265. # Column limits per backend/app/models/archive.py: filament_type=50,
  1266. # filament_color=200.
  1267. if types_joined:
  1268. result["filament_type"] = types_joined[:50]
  1269. if colors_joined:
  1270. result["filament_color"] = colors_joined[:200]
  1271. return result
  1272. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1273. """Start a layer-timelapse session for *archive_id* when the printer has
  1274. an external camera configured. Returns True if a session was started.
  1275. Three call sites in on_print_start (expected-archive promotion, fallback
  1276. archive creation, fresh-archive creation) used to inline this same
  1277. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1278. on the first pass). Centralising the conditional + call here makes the
  1279. contract testable in isolation and keeps the three sites locked in step.
  1280. """
  1281. if not (printer.external_camera_enabled and printer.external_camera_url):
  1282. return False
  1283. from backend.app.services.layer_timelapse import start_session
  1284. start_session(
  1285. printer_id,
  1286. archive_id,
  1287. printer.external_camera_url,
  1288. printer.external_camera_type or "mjpeg",
  1289. snapshot_url=printer.external_camera_snapshot_url,
  1290. rotation=getattr(printer, "camera_rotation", 0),
  1291. )
  1292. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1293. return True
  1294. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1295. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1296. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1297. — since #2926 — the description the parser already resolved, which is preferred
  1298. when present so the queue's failure reason reads the same as the status
  1299. response. The short code still produces the bracketed label, and still
  1300. resolves the sentence for a caller whose entries predate the field. An entry
  1301. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1302. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1303. label when no description is on file. Returns None for an empty list so
  1304. callers can leave error_message unset.
  1305. """
  1306. if not hms_errors:
  1307. return None
  1308. from backend.app.services.hms_errors import get_error_description
  1309. parts: list[str] = []
  1310. for err in hms_errors:
  1311. try:
  1312. # `_hms_short_code` rather than a local derivation: this one used to
  1313. # format the error without masking it to 16 bits, so an `hms[]` entry
  1314. # whose code carries an alert-level group produced a five-digit label
  1315. # like "0500_3000A" — not a code the user can look up, and never a
  1316. # catalogue key, so the sentence was lost with it.
  1317. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1318. except (TypeError, ValueError):
  1319. continue
  1320. description = err.get("description") or get_error_description(short_code)
  1321. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1322. # groups and is not a code anyone can look up; its full code in the
  1323. # printer screen's four groups is (#2728).
  1324. full_code = str(err.get("full_code") or "")
  1325. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1326. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1327. return "; ".join(parts) if parts else None
  1328. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1329. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1330. print completes successfully. Gated to status=='completed': failed, cancelled
  1331. and aborted prints do not count as usage. Caller is responsible for committing
  1332. the session. No-op when the queue item has no linked library file (e.g. reprints
  1333. from an archive). See #1008."""
  1334. if queue_status != "completed" or item.library_file_id is None:
  1335. return
  1336. from backend.app.models.library import LibraryFile
  1337. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1338. if lib_file is None:
  1339. return
  1340. lib_file.print_count = (lib_file.print_count or 0) + 1
  1341. lib_file.last_printed_at = datetime.now(timezone.utc)
  1342. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1343. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1344. When on_print_complete fires with status 'failed' for a printer in this set we
  1345. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1346. rather than a 'print failed' notification.
  1347. """
  1348. _user_stopped_printers.add(printer_id)
  1349. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1350. _last_status_broadcast: dict[int, str] = {}
  1351. # Track printers where we've updated nozzle_count
  1352. _nozzle_count_updated: set[int] = set()
  1353. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1354. """Wait the debounce window then fire `on_printer_offline` if the printer
  1355. is still offline.
  1356. Scheduled by `on_printer_status_change` on the connected → disconnected
  1357. edge (#1752). Cancelled by the same handler if the printer reconnects
  1358. before the window elapses, so a single MQTT blip + recovery doesn't
  1359. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1360. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1361. route through the same status-change callback, so this covers both.
  1362. """
  1363. logger = logging.getLogger(__name__)
  1364. try:
  1365. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1366. still_offline = not printer_manager.is_connected(printer_id)
  1367. logger.info(
  1368. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1369. printer_id,
  1370. still_offline,
  1371. )
  1372. if not still_offline:
  1373. return
  1374. async with async_session() as db:
  1375. from backend.app.models.printer import Printer
  1376. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1377. printer = result.scalar_one_or_none()
  1378. if not printer:
  1379. logger.warning(
  1380. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1381. printer_id,
  1382. )
  1383. return
  1384. # Recorded only when the relay can publish it, so the reconnect's
  1385. # online event always has an offline before it.
  1386. if mqtt_relay.enabled and mqtt_relay.connected:
  1387. _printer_offline_published.add(printer_id)
  1388. try:
  1389. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1390. except Exception as e:
  1391. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1392. logger.info(
  1393. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1394. printer_id,
  1395. printer.name,
  1396. )
  1397. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1398. except asyncio.CancelledError:
  1399. raise
  1400. except Exception as e:
  1401. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1402. finally:
  1403. _printer_offline_notify_tasks.pop(printer_id, None)
  1404. def _hms_notify_key(error) -> str:
  1405. """What identifies a fault for notification de-duplication.
  1406. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1407. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1408. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1409. and -0006 together) shared a key and only the first was ever notified. An
  1410. entry without a full code falls back to attr and code together.
  1411. """
  1412. full_code = getattr(error, "full_code", "") or ""
  1413. if full_code:
  1414. return full_code.upper()
  1415. return f"{error.attr:08X}:{error.code}"
  1416. def _hms_fault_counts(error) -> bool:
  1417. """Whether a fault counts as a problem: the same rule the frontend's
  1418. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1419. It counts when Bambu publishes text for it or it offers action buttons, and
  1420. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1421. no actions does not count: those are things like "the top cover is open" or
  1422. "the chamber is hot, fan speed increased", which a printer can hold through
  1423. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1424. it always has; those are prompts such as "unable to start drying" (#2728).
  1425. """
  1426. if error.severity < 1:
  1427. return False
  1428. has_actions = bool(getattr(error, "actions", None))
  1429. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1430. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1431. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1432. """The new faults that count (see ``_hms_fault_counts``).
  1433. These go to the MQTT relay; the caller also needs a description before it
  1434. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1435. used to read ``severity >= 2`` when severity held the part byte; on the real
  1436. level that would drop the task-stopping errors (#2728).
  1437. """
  1438. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1439. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1440. """The faults on this printer not notified yet, and record them as notified.
  1441. Tracking is updated before anything is sent, so concurrent status callbacks
  1442. cannot notify the same fault twice. A notified fault is forgotten once it
  1443. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1444. and on is notified once (#3226), while one that clears and comes back much
  1445. later is notified again.
  1446. When ``print_state`` changes (a print resumed, started or finished), every
  1447. fault recorded so far is forgotten the first time it is gone, without the
  1448. wait: a runout fixed before resuming must be notified if it happens again a
  1449. few minutes later, while the printer sits paused. Not only the faults gone
  1450. at the change itself, because the update that flips the state can still
  1451. carry the old fault (a ``print_error`` entry stays until a payload brings
  1452. ``hms``).
  1453. """
  1454. now = time.time()
  1455. current = {_hms_notify_key(e) for e in errors}
  1456. seen = _notified_hms_errors.setdefault(printer_id, {})
  1457. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1458. if print_state is not None:
  1459. print_state = print_state.upper()
  1460. if _hms_print_state.get(printer_id, print_state) != print_state:
  1461. forget_when_gone.update(seen)
  1462. _hms_print_state[printer_id] = print_state
  1463. for key, last_seen in list(seen.items()):
  1464. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1465. del seen[key]
  1466. forget_when_gone.discard(key)
  1467. new = current - seen.keys()
  1468. for key in current:
  1469. seen[key] = now
  1470. if not seen:
  1471. _notified_hms_errors.pop(printer_id, None)
  1472. if not forget_when_gone:
  1473. _hms_forget_when_gone.pop(printer_id, None)
  1474. return _hms_errors_to_notify(errors, new)
  1475. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1476. # "Printing", -1 and 255 are "no stage" (#3211).
  1477. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1478. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1479. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1480. Records it as notified. Called only for a printing state with progress above 0.
  1481. Progress before the first layer is not progress through the print (#3211).
  1482. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1483. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1484. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1485. 75% notification together with Print Started, and since 75 was then on
  1486. record, 25 and 50 could never fire. So nothing counts while the printer
  1487. reports a layer count but has not started layer 1.
  1488. Without a layer count -- a print whose first frame carried no
  1489. ``total_layer_num``, until the pushall that asks for it is answered
  1490. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1491. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1492. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1493. reports neither keeps the old behaviour rather than never notifying.
  1494. """
  1495. if (state.layer_num or 0) < 1:
  1496. if (state.total_layers or 0) > 0:
  1497. return None
  1498. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1499. return None
  1500. progress = state.progress or 0
  1501. current_milestone = 0
  1502. if progress >= 75:
  1503. current_milestone = 75
  1504. elif progress >= 50:
  1505. current_milestone = 50
  1506. elif progress >= 25:
  1507. current_milestone = 25
  1508. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1509. _last_progress_milestone[printer_id] = current_milestone
  1510. return current_milestone
  1511. return None
  1512. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1513. """Handle printer status changes - broadcast via WebSocket."""
  1514. try:
  1515. notify_live_activities.observe(printer_id, state)
  1516. except Exception:
  1517. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1518. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1519. # transitions disconnected → connected — which covers both Bambuddy
  1520. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1521. # `reconcile_stale_active_prints` exactly once for this connection so
  1522. # any archive still in `status="printing"` that can't actually be
  1523. # running anymore (printer IDLE / different subtask / empty subtask)
  1524. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1525. # finished during a disconnect window + a smart-plug power cycle
  1526. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1527. # next boot. Reconciliation runs concurrently — it must not block the
  1528. # WebSocket dedup / broadcast logic below, and the connected edge is
  1529. # marked True BEFORE the await so concurrent status updates inside
  1530. # the same connection don't re-trigger reconciliation.
  1531. #
  1532. # Wait for a real push_status before reconciling (#1679): MQTT
  1533. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1534. # the connection, BEFORE `_request_push_all` round-trips. At that
  1535. # instant the `PrinterState` is still on construction defaults — most
  1536. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1537. # If reconcile spawns here, every in-flight archive falls through to
  1538. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1539. # creates a duplicate archive on the real PRINT COMPLETE and
  1540. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1541. # keeps the #1542 mechanism intact: once the first real push_status
  1542. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1543. # fires again with the flag still False — reconcile then runs against
  1544. # actual evidence.
  1545. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1546. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1547. _printer_reconciled_since_connect[printer_id] = True
  1548. spawn_background_task(
  1549. reconcile_stale_active_prints(printer_id),
  1550. name=f"reconcile-stale-prints-{printer_id}",
  1551. )
  1552. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1553. # Re-arm so the next reconnect triggers reconciliation again.
  1554. _printer_reconciled_since_connect[printer_id] = False
  1555. # Same edge, for the calibration table the AMS card reads its K values from.
  1556. #
  1557. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1558. # tables to ask for. A `state_known` gate alone is not enough: the first
  1559. # real push_status is what makes the state known, and the nozzle fields do
  1560. # not always arrive in it. Latching there would spend this connection's one
  1561. # attempt on a printer that could not yet say what was fitted.
  1562. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1563. if (
  1564. state.connected
  1565. and state_known
  1566. and nozzle_known
  1567. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1568. ):
  1569. _printer_kprofiles_primed_since_connect[printer_id] = True
  1570. spawn_background_task(
  1571. prime_kprofile_table(printer_id),
  1572. name=f"prime-kprofiles-{printer_id}",
  1573. )
  1574. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1575. _printer_kprofiles_primed_since_connect[printer_id] = False
  1576. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1577. # else in the AMS report changing -- a power cycle does it to every slot --
  1578. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1579. # while the printer is idle; needs_check is cheap and throttled per slot.
  1580. # Guarded: nothing here may stop the status broadcast below.
  1581. try:
  1582. if not state.connected:
  1583. kprofile_drift.forget_printer(printer_id)
  1584. elif kprofile_drift.needs_check(printer_id, state):
  1585. spawn_background_task(
  1586. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1587. name=f"reapply-kprofiles-{printer_id}",
  1588. )
  1589. except Exception:
  1590. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1591. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1592. # connected → disconnected. The "back online" channel is already covered
  1593. # by the print-failure notification (firmware reports gcode_state=FAILED
  1594. # on reconnect of an interrupted print), so there is no online
  1595. # notification. The MQTT relay gets both: offline after the debounce, and
  1596. # online on the reconnect that follows a published offline.
  1597. prev_connected = _printer_last_connected.get(printer_id)
  1598. _printer_last_connected[printer_id] = state.connected
  1599. if prev_connected is True and not state.connected:
  1600. existing = _printer_offline_notify_tasks.get(printer_id)
  1601. if existing is None or existing.done():
  1602. logging.getLogger(__name__).info(
  1603. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1604. printer_id,
  1605. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1606. )
  1607. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1608. _maybe_notify_printer_offline(printer_id),
  1609. name=f"printer-offline-notify-{printer_id}",
  1610. )
  1611. elif state.connected:
  1612. # Kept until the relay can actually send online: with its broker down
  1613. # now, the next status update after the reconnect sends it.
  1614. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1615. _printer_offline_published.discard(printer_id)
  1616. printer_info = printer_manager.get_printer(printer_id)
  1617. if printer_info:
  1618. try:
  1619. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1620. except Exception as e:
  1621. logging.getLogger(__name__).warning(
  1622. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1623. )
  1624. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1625. if pending is not None and not pending.done():
  1626. logging.getLogger(__name__).info(
  1627. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1628. printer_id,
  1629. )
  1630. pending.cancel()
  1631. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1632. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1633. temps = state.temperatures or {}
  1634. nozzle_temp = round(temps.get("nozzle", 0))
  1635. bed_temp = round(temps.get("bed", 0))
  1636. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1637. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1638. # Auto-detect dual-nozzle printers from MQTT temperature data
  1639. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1640. _nozzle_count_updated.add(printer_id)
  1641. # Update nozzle_count in database
  1642. async with async_session() as db:
  1643. from backend.app.models.printer import Printer
  1644. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1645. printer = result.scalar_one_or_none()
  1646. if printer and printer.nozzle_count != 2:
  1647. printer.nozzle_count = 2
  1648. await db.commit()
  1649. logging.getLogger(__name__).info(
  1650. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1651. )
  1652. # Include target temps for heating phase detection
  1653. bed_target = round(temps.get("bed_target", 0))
  1654. nozzle_target = round(temps.get("nozzle_target", 0))
  1655. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1656. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1657. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1658. #
  1659. # dry_countdown_stalled rides along because it is the one drying signal the
  1660. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1661. # dry_time stopped moving, so on the frame that flips it every other member
  1662. # of this key is identical and the push would be deduplicated away. Mid-print
  1663. # a temperature would eventually break the tie, but a parked command on an
  1664. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1665. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1666. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1667. ams_dry_key = (
  1668. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1669. if state.raw_data
  1670. else ()
  1671. )
  1672. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1673. #
  1674. # The filament identity fields are here because Configure Slot writes
  1675. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1676. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1677. # matched, this function returned before broadcasting, and the card kept
  1678. # showing the old filament until the 30s fallback poll or a page reload —
  1679. # even though the configure route asks the printer for a fresh pushall and
  1680. # that push does carry the new values. Reset always worked, because it
  1681. # clears tray_type.
  1682. #
  1683. # These fields only change when someone configures a slot or swaps a spool,
  1684. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1685. ams_tray_key = (
  1686. tuple(
  1687. (
  1688. t.get("id"),
  1689. t.get("tray_type", ""),
  1690. t.get("state"),
  1691. t.get("tray_color", ""),
  1692. t.get("tray_info_idx", ""),
  1693. t.get("tray_sub_brands", ""),
  1694. t.get("cali_idx"),
  1695. )
  1696. for a in (state.raw_data.get("ams") or [])
  1697. for t in a.get("tray", [])
  1698. )
  1699. if state.raw_data
  1700. else ()
  1701. )
  1702. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1703. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1704. # in the AMS change-hash (tray fields only, and widening that would fire
  1705. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1706. # screen changed no key at all and the card's inlet badges sat stale until a
  1707. # reload. Like the filament-backup flag, these only move when someone
  1708. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1709. fts_key = (
  1710. state.fila_switch.installed if state.fila_switch else False,
  1711. tuple(sorted(state.ams_switch_inlet.items())),
  1712. # Which hotend holds which slot. Unlike the two above this does move
  1713. # mid-print, on every filament change — but only between discrete slots,
  1714. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1715. # it live: it decides which hotend the Load dialog may offer and whether
  1716. # Unload has anything to act on.
  1717. tuple(
  1718. sorted(
  1719. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1720. # Sort on the extruder id alone: the other members are nullable
  1721. # and comparing None with an int raises.
  1722. key=lambda entry: entry[0],
  1723. )
  1724. ),
  1725. )
  1726. status_key = (
  1727. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1728. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1729. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1730. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1731. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1732. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1733. )
  1734. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1735. if not is_active_print:
  1736. _unauthorized_print_kill_sent.discard(printer_id)
  1737. elif printer_id in _unauthorized_print_kill_sent:
  1738. # stop_print() was already sent for this print; avoid all further
  1739. # ownership and settings work until the printer leaves an active state.
  1740. pass
  1741. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1742. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1743. _unauthorized_print_kill_sent.discard(printer_id)
  1744. else:
  1745. kill_switch_enabled = False
  1746. authorization: bool | None = None
  1747. status_logger = logging.getLogger(__name__)
  1748. try:
  1749. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1750. if kill_switch_enabled:
  1751. async with async_session() as db:
  1752. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1753. except Exception as e:
  1754. # Fail safe: a database/reconciliation error must never turn into an
  1755. # irreversible stop of a print whose ownership is still unknown.
  1756. authorization = None
  1757. status_logger.warning(
  1758. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1759. )
  1760. if not kill_switch_enabled or authorization is True:
  1761. _unauthorized_print_kill_sent.discard(printer_id)
  1762. elif authorization is None:
  1763. _unauthorized_print_kill_sent.discard(printer_id)
  1764. status_logger.debug(
  1765. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1766. printer_id,
  1767. )
  1768. else:
  1769. try:
  1770. stopped = printer_manager.stop_print(printer_id)
  1771. if stopped:
  1772. _unauthorized_print_kill_sent.add(printer_id)
  1773. printer_info = printer_manager.get_printer(printer_id)
  1774. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1775. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1776. notification_data = {
  1777. "status": "stopped",
  1778. "filename": state.gcode_file or state.current_print or "",
  1779. "subtask_name": state.subtask_name or "",
  1780. "progress": state.progress,
  1781. "reason": "unauthorized_print",
  1782. }
  1783. status_logger.warning(
  1784. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1785. printer_id,
  1786. state.state,
  1787. )
  1788. try:
  1789. await ws_manager.broadcast(
  1790. {
  1791. "type": "kill_switch_triggered",
  1792. "printer_id": printer_id,
  1793. "printer_name": printer_name,
  1794. "filename": filename,
  1795. "reason": "unauthorized_print",
  1796. }
  1797. )
  1798. except Exception as e:
  1799. status_logger.warning(
  1800. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1801. )
  1802. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1803. if previous_task is not None and not previous_task.done():
  1804. previous_task.cancel()
  1805. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1806. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1807. name=f"kill-switch-notification-{printer_id}",
  1808. )
  1809. else:
  1810. status_logger.warning(
  1811. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1812. printer_id,
  1813. state.state,
  1814. )
  1815. except Exception as e:
  1816. status_logger.warning(
  1817. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1818. )
  1819. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1820. try:
  1821. printer_info = printer_manager.get_printer(printer_id)
  1822. if printer_info:
  1823. await mqtt_relay.on_printer_status(
  1824. printer_id,
  1825. state,
  1826. printer_info.name,
  1827. printer_info.serial_number,
  1828. printer_manager.is_awaiting_plate_clear(printer_id),
  1829. )
  1830. except Exception:
  1831. pass # Don't fail status callback if MQTT fails
  1832. if _last_status_broadcast.get(printer_id) == status_key:
  1833. return # No change, skip WebSocket broadcast
  1834. _last_status_broadcast[printer_id] = status_key
  1835. # Check for progress milestone notifications (25%, 50%, 75%)
  1836. progress = state.progress or 0
  1837. is_printing = state.state in ("RUNNING", "PRINTING")
  1838. if is_printing and progress > 0:
  1839. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1840. if current_milestone is not None:
  1841. try:
  1842. from backend.app.models.printer import Printer
  1843. # Read the printer in a short session and release the connection
  1844. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1845. # pinned a pooled connection per milestone, per printer (issue #2572).
  1846. async with async_session() as db:
  1847. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1848. printer = result.scalar_one_or_none()
  1849. printer_name = printer.name if printer else f"Printer {printer_id}"
  1850. filename = state.subtask_name or state.gcode_file or "Unknown"
  1851. # remaining_time is in minutes, convert to seconds for notification
  1852. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1853. # Capture camera snapshot for notification image attachment (no DB held).
  1854. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1855. # Notification send needs a session (provider/template lookups).
  1856. async with async_session() as db:
  1857. await notification_service.on_print_progress(
  1858. printer_id,
  1859. printer_name,
  1860. filename,
  1861. current_milestone,
  1862. db,
  1863. remaining_time_seconds,
  1864. image_data=image_data,
  1865. )
  1866. except Exception as e:
  1867. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1868. elif progress < 5:
  1869. # Reset milestone tracking when print restarts or new print begins
  1870. _last_progress_milestone[printer_id] = 0
  1871. _first_layer_notified[printer_id] = False
  1872. # HMS error codes that should not trigger notifications even though they
  1873. # have known descriptions (e.g. user-initiated actions, not real errors).
  1874. _HMS_NOTIFICATION_SUPPRESS = {
  1875. "0500_400E", # Printing was cancelled (user action, not an error)
  1876. }
  1877. # Check for new HMS errors and send notifications
  1878. current_hms_errors = getattr(state, "hms_errors", []) or []
  1879. if current_hms_errors:
  1880. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1881. if new_errors:
  1882. try:
  1883. from backend.app.models.printer import Printer
  1884. # Read the printer in a short session and release the connection
  1885. # BEFORE the ~15s camera snapshot below (issue #2572).
  1886. async with async_session() as db:
  1887. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1888. printer = result.scalar_one_or_none()
  1889. printer_name = printer.name if printer else f"Printer {printer_id}"
  1890. # Format error details for notification
  1891. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1892. module_names = {
  1893. 0x03: "Print/Task",
  1894. 0x05: "Nozzle/Extruder",
  1895. 0x07: "AMS/Filament",
  1896. 0x0C: "Motion Controller",
  1897. 0x12: "Chamber",
  1898. }
  1899. # Capture camera snapshot once for all error notifications (no DB held).
  1900. error_image_data = await _capture_snapshot_for_notification(
  1901. printer_id, printer, logging.getLogger(__name__)
  1902. )
  1903. # Notification sends need a session (provider/template lookups).
  1904. async with async_session() as db:
  1905. sent_count = 0
  1906. for error in new_errors:
  1907. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1908. # Build short code like "0700_8010"
  1909. # Mask to 16 bits to handle printers that send larger values
  1910. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1911. error_code_masked = error_code_int & 0xFFFF
  1912. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1913. # Only notify for errors Bambu publishes text for — printers
  1914. # send undocumented codes that aren't real errors, and Bambu
  1915. # lists some with empty text. Resolved at parse time (#2926);
  1916. # short_code is still needed for the suppression set below.
  1917. description = error.description
  1918. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1919. continue
  1920. error_type = f"{module_name} Error"
  1921. error_detail = description
  1922. await notification_service.on_printer_error(
  1923. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1924. )
  1925. sent_count += 1
  1926. if sent_count:
  1927. logging.getLogger(__name__).info(
  1928. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1929. )
  1930. # Also publish to MQTT relay (no DB): every new fault that
  1931. # counts, with or without text, the same set the UI counts.
  1932. printer_info = printer_manager.get_printer(printer_id)
  1933. if printer_info:
  1934. errors_data = [
  1935. {
  1936. "code": e.code,
  1937. "attr": e.attr,
  1938. "module": e.module,
  1939. "severity": e.severity,
  1940. }
  1941. for e in new_errors
  1942. ]
  1943. await mqtt_relay.on_printer_error(
  1944. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1945. )
  1946. except Exception as e:
  1947. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1948. else:
  1949. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1950. # across a print state change) are forgotten. Some codes, e.g. chamber
  1951. # temperature regulation during PETG prints, toggle every few seconds.
  1952. _take_new_hms_faults(printer_id, [], state.state)
  1953. await ws_manager.send_printer_status(
  1954. printer_id,
  1955. printer_state_to_dict(
  1956. state,
  1957. printer_id,
  1958. printer_manager.get_model(printer_id),
  1959. printer_manager.get_drying_targets(printer_id),
  1960. ),
  1961. )
  1962. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1963. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1964. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1965. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1966. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1967. K-profiles are per-nozzle and the printer's calibration table is numbered
  1968. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1969. switch's other inlet therefore silently invalidates every configured slot in
  1970. it: the index stays put and now resolves against the other nozzle's table.
  1971. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1972. and 0.020 on the right kept the left profile after the move, and a manual
  1973. RFID re-read only re-asserted the same wrong one.
  1974. Configuring a slot is a deliberate preparation step, so this re-selects
  1975. rather than re-configures: only the calibration binding moves, and only for
  1976. slots whose spool already has a stored profile for the new nozzle. A slot
  1977. Bambuddy knows nothing about is left exactly as the operator left it.
  1978. """
  1979. logger = logging.getLogger(__name__)
  1980. target_extruder = extruder_for_inlet(inlet)
  1981. if target_extruder is None:
  1982. return
  1983. client = printer_manager.get_client(printer_id)
  1984. state = printer_manager.get_status(printer_id)
  1985. if not client or not state or not state.raw_data:
  1986. return
  1987. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1988. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1989. # the nozzle width, which changes both the K profile to select and the
  1990. # preset the slot should carry.
  1991. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1992. ams_raw = state.raw_data.get("ams")
  1993. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1994. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1995. if not unit:
  1996. return
  1997. try:
  1998. async with async_session() as db:
  1999. for tray in unit.get("tray", []):
  2000. tray_id = int(tray.get("id", -1))
  2001. if tray_id < 0 or not tray.get("tray_type"):
  2002. continue
  2003. current_idx = tray.get("cali_idx")
  2004. profile = await find_slot_kprofile_for_extruder(
  2005. db,
  2006. printer_id,
  2007. ams_id,
  2008. tray_id,
  2009. target_extruder,
  2010. nozzle_diameter,
  2011. printer_manager.get_model(printer_id),
  2012. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2013. )
  2014. if profile is None or profile.cali_idx is None:
  2015. continue
  2016. if current_idx == profile.cali_idx:
  2017. continue # Already on the right one.
  2018. logger.info(
  2019. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2020. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2021. printer_id,
  2022. ams_id,
  2023. tray_id,
  2024. inlet,
  2025. target_extruder,
  2026. profile.name,
  2027. current_idx,
  2028. profile.cali_idx,
  2029. profile.k_value,
  2030. )
  2031. client.extrusion_cali_sel(
  2032. ams_id=ams_id,
  2033. tray_id=tray_id,
  2034. cali_idx=profile.cali_idx,
  2035. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2036. nozzle_diameter=nozzle_diameter,
  2037. )
  2038. except Exception as e:
  2039. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2040. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2041. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2042. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2043. from the delayed re-check -- which is why it takes the AMS data and print
  2044. state as arguments instead of reading them from the push (#3186).
  2045. """
  2046. logger = logging.getLogger(__name__)
  2047. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2048. # Auto-unlink spool assignments with stale fingerprints. Under the
  2049. # per-printer assignment lock since #3186: the held-removal re-check runs
  2050. # this outside any MQTT push, so it can now overlap one.
  2051. try:
  2052. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2053. from sqlalchemy.orm import selectinload
  2054. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2055. from backend.app.models.spool import Spool as _Spool
  2056. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2057. from backend.app.services.ams_slot_presence import spool_present
  2058. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2059. # Built-in assignments only. Since #2812 they survive a switch to
  2060. # Spoolman mode rather than being deleted by it, and this pass ends
  2061. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2062. # time as the AMS contents changed under the other mode, undoing the
  2063. # preservation more slowly but just as completely.
  2064. assignments = []
  2065. if not await spoolman_owns_assignments(db):
  2066. result = await db.execute(
  2067. select(SA)
  2068. .where(SA.printer_id == printer_id)
  2069. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2070. )
  2071. assignments = result.scalars().all()
  2072. # ``printing_now`` (top of this function) keeps a runout from
  2073. # unlinking the spool that fed the print — the next idle-time pass
  2074. # unlinks it if the user really did take it out.
  2075. stale = []
  2076. # Removals this pass is holding rather than unlinking (#3186).
  2077. held: set[tuple] = set()
  2078. for assignment in assignments:
  2079. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2080. if assignment.ams_id == 255:
  2081. ps = printer_manager.get_status(printer_id)
  2082. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2083. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2084. current_tray = None
  2085. for vt in vt_tray_raw:
  2086. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2087. current_tray = vt
  2088. break
  2089. if not current_tray:
  2090. # vt_tray data may not have arrived yet — keep assignment
  2091. continue
  2092. else:
  2093. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2094. if not current_tray:
  2095. if printing_now:
  2096. logger.info(
  2097. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2098. assignment.spool_id,
  2099. assignment.ams_id,
  2100. assignment.tray_id,
  2101. )
  2102. continue
  2103. # A whole AMS unit can drop out of one push and come back in
  2104. # the next; only a slot that stays gone is a removal (#3186).
  2105. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2106. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2107. held.add(hold_key)
  2108. logger.info(
  2109. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2110. "unlinking if it is still gone in %ds",
  2111. assignment.spool_id,
  2112. assignment.ams_id,
  2113. assignment.tray_id,
  2114. int(slot_unlink_grace.GRACE_SECONDS),
  2115. )
  2116. continue
  2117. logger.info(
  2118. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2119. assignment.spool_id,
  2120. assignment.ams_id,
  2121. assignment.tray_id,
  2122. )
  2123. stale.append(assignment) # Slot empty
  2124. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2125. # A Bambu Lab spool is in this slot — check if it's the same spool
  2126. # that's currently assigned. If yes, keep the assignment (avoids
  2127. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2128. # the printer's filament preset on every startup).
  2129. tray_uuid = current_tray.get("tray_uuid", "")
  2130. tag_uid = current_tray.get("tag_uid", "")
  2131. spool = assignment.spool
  2132. spool_matches = False
  2133. if spool:
  2134. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2135. spool.tag_uid
  2136. and tag_uid
  2137. and tag_uid != "0000000000000000"
  2138. and spool.tag_uid.upper() == tag_uid.upper()
  2139. ):
  2140. spool_matches = True
  2141. if spool_matches:
  2142. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2143. cur_color = current_tray.get("tray_color", "")
  2144. cur_type = current_tray.get("tray_type", "")
  2145. fp_color = assignment.fingerprint_color or ""
  2146. fp_type = assignment.fingerprint_type or ""
  2147. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2148. assignment.fingerprint_color = cur_color
  2149. assignment.fingerprint_type = cur_type
  2150. logger.debug(
  2151. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2152. assignment.spool_id,
  2153. assignment.ams_id,
  2154. assignment.tray_id,
  2155. )
  2156. continue
  2157. # Different BL spool or unrecognized — unlink so auto-assign can match
  2158. logger.info(
  2159. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2160. assignment.spool_id,
  2161. assignment.ams_id,
  2162. assignment.tray_id,
  2163. tray_uuid,
  2164. )
  2165. stale.append(assignment)
  2166. else:
  2167. cur_color = current_tray.get("tray_color", "")
  2168. cur_type = current_tray.get("tray_type", "")
  2169. cur_state = current_tray.get("state")
  2170. fp_color = assignment.fingerprint_color or ""
  2171. fp_type = assignment.fingerprint_type or ""
  2172. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2173. # the slot was empty when the user pre-assigned via SpoolBuddy
  2174. # (the firmware drops ams_filament_setting on empty slots, so
  2175. # MQTT was deferred). The moment any filament gets inserted
  2176. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2177. # reconfigured spool — fire the deferred configuration.
  2178. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2179. # extruder" code) OR, on firmwares that don't use the state
  2180. # enum meaningfully, a non-empty tray_type when state is
  2181. # NOT one of the firmware's explicit empty signals (9, 10).
  2182. # state-only was wrong for firmwares that never set 11 — A1
  2183. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2184. # always report state=3 — so the replay never fired for them
  2185. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2186. # explicit "empty" signals authoritative over any stale
  2187. # tray_type that might survive the relay's auto-clearing.
  2188. #
  2189. # tray_exist_bits comes first because that guard cannot tell
  2190. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2191. # writes state=9 when the bit is 0 and leaves it there when the
  2192. # bit returns. A non-RFID spool inserted into a pre-assigned
  2193. # slot brings no tray_type with it, so the stale 9 made this
  2194. # expression false forever and the deferred config never fired
  2195. # — the deadlock #1322 removed from the assign path, still in
  2196. # place here (#3084, #3100).
  2197. loaded = spool_present(current_tray) is True or (
  2198. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2199. )
  2200. if not fp_type.strip() and loaded and assignment.spool:
  2201. try:
  2202. from backend.app.api.routes.inventory import (
  2203. apply_spool_to_slot_via_mqtt,
  2204. )
  2205. await apply_spool_to_slot_via_mqtt(
  2206. db=db,
  2207. current_user=None,
  2208. spool=assignment.spool,
  2209. printer_id=printer_id,
  2210. ams_id=assignment.ams_id,
  2211. tray_id=assignment.tray_id,
  2212. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2213. current_tray_type=cur_type,
  2214. )
  2215. logger.info(
  2216. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2217. assignment.spool_id,
  2218. printer_id,
  2219. assignment.ams_id,
  2220. assignment.tray_id,
  2221. )
  2222. except Exception:
  2223. logger.exception(
  2224. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2225. assignment.spool_id,
  2226. printer_id,
  2227. assignment.ams_id,
  2228. assignment.tray_id,
  2229. )
  2230. assignment.fingerprint_color = cur_color
  2231. assignment.fingerprint_type = cur_type
  2232. continue
  2233. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2234. # Blank tray data mid-print is a runout, not a swap: the
  2235. # firmware clears colour and type when it unloads a spool
  2236. # it just emptied. Unlinking here would erase the record
  2237. # of which spool fed the print so far.
  2238. if printing_now and not cur_color.strip() and not cur_type.strip():
  2239. logger.info(
  2240. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2241. "(runout?)",
  2242. assignment.spool_id,
  2243. assignment.ams_id,
  2244. assignment.tray_id,
  2245. )
  2246. continue
  2247. # Same reasoning off the print, on firmware's own say-so:
  2248. # a blank tray report from a slot whose tray_exist_bits
  2249. # bit is set describes a spool the AMS cannot identify —
  2250. # a non-RFID one, or one whose slot was reset — not a
  2251. # spool that was taken out. Deleting the assignment there
  2252. # threw away the identity the user had supplied, which is
  2253. # the only place it existed (#3100). A slot the bit calls
  2254. # empty, or one that carries no bit at all, still unlinks.
  2255. #
  2256. # Unless the slot was reported empty first: a removal
  2257. # already held means a spool came out and another went
  2258. # in, so the blank report keeps the hold running below
  2259. # rather than cancelling it (#3186).
  2260. if (
  2261. spool_present(current_tray) is True
  2262. and not cur_color.strip()
  2263. and not cur_type.strip()
  2264. and not slot_unlink_grace.is_held(
  2265. printer_id,
  2266. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2267. )
  2268. ):
  2269. logger.info(
  2270. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2271. "tray reports no filament data yet",
  2272. assignment.spool_id,
  2273. assignment.ams_id,
  2274. assignment.tray_id,
  2275. )
  2276. continue
  2277. # A blank report the presence bit does not vouch for is
  2278. # still only one push. An idle X1C cleared a whole AMS
  2279. # unit's bits, colour and type for a moment and lost
  2280. # four saved assignments that way (#3186); unlink only
  2281. # if the slot is still blank after the grace period.
  2282. if not cur_color.strip() and not cur_type.strip():
  2283. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2284. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2285. held.add(hold_key)
  2286. logger.info(
  2287. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2288. "unlinking if it is still blank in %ds",
  2289. assignment.spool_id,
  2290. assignment.ams_id,
  2291. assignment.tray_id,
  2292. int(slot_unlink_grace.GRACE_SECONDS),
  2293. )
  2294. continue
  2295. # Fingerprint mismatch — but check if tray now matches the
  2296. # assigned spool (e.g. auto-configure changed the tray).
  2297. # Both sides are reduced to the type the slot can carry
  2298. # before comparing: the assign path writes that rather
  2299. # than the spool's raw material (#2902), so a spool whose
  2300. # material is a product line — "PLA+", "HTPLA" — reports
  2301. # back as "PLA" and would otherwise fail this check and
  2302. # be auto-unlinked from the slot it was just assigned to.
  2303. # Reducing the printer's side too keeps slots configured
  2304. # by an older Bambuddy, still reporting "PLA+", matching.
  2305. spool = assignment.spool
  2306. if spool:
  2307. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2308. # Two ways the assign path can have arrived at the
  2309. # slot's type, so both count as "we wrote this".
  2310. # The material column is one; the spool's preset is
  2311. # the other, and it outranks the material when the
  2312. # spool has one -- a spool whose material says PLA
  2313. # and whose preset is "Bambu PLA Aero" puts
  2314. # PLA-AERO in the slot (#2902). Read from the stored
  2315. # preset name rather than resolving the preset,
  2316. # because this runs on every AMS push and a cloud
  2317. # lookup here would be both slow and unavailable on
  2318. # the unauthenticated replay path.
  2319. spool_types = {printer_filament_type(spool.material).upper()}
  2320. if spool.slicer_filament_name:
  2321. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2322. # An imported local preset stores its type outright,
  2323. # which is what the assign path used -- and the name
  2324. # above may be unset. One keyed read, and only on a
  2325. # mismatch, which is rare.
  2326. #
  2327. # slicer_filament is free text up to fifty characters,
  2328. # so the digits have to be checked against the range
  2329. # of the integer primary key they are about to be
  2330. # compared with. Postgres raises on an out-of-range
  2331. # integer rather than simply not matching, and that
  2332. # would poison this session and abandon the rest of
  2333. # the cleanup pass.
  2334. lp_ref = (spool.slicer_filament or "").strip()
  2335. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2336. from backend.app.models.local_preset import LocalPreset as _LP
  2337. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2338. if lp_type:
  2339. spool_types.add(printer_filament_type(lp_type).upper())
  2340. if (
  2341. _colors_similar(cur_color, spool_color)
  2342. and printer_filament_type(cur_type).upper() in spool_types
  2343. ):
  2344. logger.info(
  2345. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2346. assignment.spool_id,
  2347. assignment.ams_id,
  2348. assignment.tray_id,
  2349. )
  2350. assignment.fingerprint_color = cur_color
  2351. assignment.fingerprint_type = cur_type
  2352. continue
  2353. logger.info(
  2354. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2355. assignment.spool_id,
  2356. assignment.ams_id,
  2357. assignment.tray_id,
  2358. cur_color,
  2359. cur_type,
  2360. fp_color,
  2361. fp_type,
  2362. spool.rgba if spool else "?",
  2363. spool.material if spool else "?",
  2364. )
  2365. stale.append(assignment) # Spool changed
  2366. slot_unlink_grace.settle(printer_id, "inventory", held)
  2367. # Snapshot slots before delete — ORM attribute access after the
  2368. # commit would refresh against a deleted row.
  2369. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2370. for a in stale:
  2371. await db.delete(a)
  2372. if stale:
  2373. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2374. # Commit any changes (stale deletions and/or fingerprint updates)
  2375. await db.commit()
  2376. # Tell open browsers the assignment is gone (#2575). Only the manual
  2377. # REST assign/unassign endpoints broadcast this event; without it the
  2378. # frontend's spool-assignments cache keeps rendering the unlinked
  2379. # spool on the slot until an unrelated refetch — which reads exactly
  2380. # like "the fix didn't work" (reporter verified: a browser refresh
  2381. # after the swap showed the correct state all along).
  2382. for ams_id, tray_id in unlinked_slots:
  2383. await ws_manager.broadcast(
  2384. {
  2385. "type": "spool_assignment_changed",
  2386. "printer_id": printer_id,
  2387. "ams_id": ams_id,
  2388. "tray_id": tray_id,
  2389. }
  2390. )
  2391. except Exception as e:
  2392. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2393. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2394. """Delete Spoolman slot rows whose held removal has run its grace period.
  2395. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2396. talks to Spoolman for every tray; this only needs the local rows, so it
  2397. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2398. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2399. not in a slot the presence bit calls occupied -- and nothing else.
  2400. """
  2401. logger = logging.getLogger(__name__)
  2402. try:
  2403. async with async_session() as db:
  2404. from backend.app.api.routes.settings import get_setting
  2405. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2406. from backend.app.services.ams_slot_presence import spool_present
  2407. enabled = await get_setting(db, "spoolman_enabled")
  2408. if not enabled or enabled.lower() != "true":
  2409. return
  2410. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2411. if sync_mode and sync_mode != "auto":
  2412. return
  2413. trays: dict[tuple[int, int], dict] = {}
  2414. for ams_unit in ams_data or []:
  2415. if not isinstance(ams_unit, dict):
  2416. continue
  2417. for tray in ams_unit.get("tray", []):
  2418. if isinstance(tray, dict):
  2419. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2420. rows = (
  2421. (
  2422. await db.execute(
  2423. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2424. )
  2425. )
  2426. .scalars()
  2427. .all()
  2428. )
  2429. held: set[tuple] = set()
  2430. expired: list[tuple[int, int]] = []
  2431. for row in rows:
  2432. tray = trays.get((row.ams_id, row.tray_id))
  2433. if tray is None or printing_now:
  2434. continue
  2435. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2436. continue
  2437. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2438. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2439. continue
  2440. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2441. expired.append((row.ams_id, row.tray_id))
  2442. else:
  2443. held.add(hold_key)
  2444. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2445. if not expired:
  2446. return
  2447. # A statement rather than ORM deletes, like the sync pass: the two
  2448. # can overlap, and a row the other already removed must not fail
  2449. # this commit.
  2450. for ams_id, tray_id in expired:
  2451. await db.execute(
  2452. delete(SpoolmanSlotAssignment).where(
  2453. SpoolmanSlotAssignment.printer_id == printer_id,
  2454. SpoolmanSlotAssignment.ams_id == ams_id,
  2455. SpoolmanSlotAssignment.tray_id == tray_id,
  2456. )
  2457. )
  2458. await db.commit()
  2459. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2460. for ams_id, tray_id in expired:
  2461. await ws_manager.broadcast(
  2462. {
  2463. "type": "spool_assignment_changed",
  2464. "printer_id": printer_id,
  2465. "ams_id": ams_id,
  2466. "tray_id": tray_id,
  2467. }
  2468. )
  2469. except Exception as e:
  2470. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2471. async def _recheck_held_unlinks(printer_id: int) -> None:
  2472. """Re-run just the slot cleanup against the printer's current AMS state.
  2473. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2474. passes otherwise run only when the AMS hash changes, and a slot that went
  2475. empty and stayed empty may never change it again.
  2476. """
  2477. status = printer_manager.get_status(printer_id)
  2478. # A disconnected printer's state is its last report, not a new one: acting
  2479. # on it would "confirm" a removal nobody has seen for the whole grace
  2480. # period. Leave the holds; the first push after reconnecting decides.
  2481. if status is None or not status.connected:
  2482. return
  2483. ams_raw = status.raw_data.get("ams")
  2484. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2485. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2486. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2487. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2488. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2489. async def on_ams_change(printer_id: int, ams_data: list):
  2490. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2491. logger = logging.getLogger(__name__)
  2492. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2493. # on_print_complete may pop _active_sessions during our awaits (#880).
  2494. from backend.app.services.usage_tracker import _active_sessions
  2495. _print_active = printer_id in _active_sessions
  2496. # A slot that reports empty while a print is running is a filament runout,
  2497. # not a spool swap: the spool is still physically in the AMS, just
  2498. # consumed. Dropping either inventory backend's slot link there loses the
  2499. # only record of which spool fed the print, so the completion path can't
  2500. # charge the runout segment to anything. Both cleanup passes below consult
  2501. # this; computed once, up front, so neither depends on the other having run.
  2502. _unlink_state = printer_manager.get_status(printer_id)
  2503. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2504. # The session alone is not enough: a restart that finds a stale persisted
  2505. # session registers none for the print that is running.
  2506. _print_active = _print_active or printing_now
  2507. # MQTT relay - publish AMS change
  2508. try:
  2509. printer_info = printer_manager.get_printer(printer_id)
  2510. if printer_info:
  2511. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2512. except Exception:
  2513. pass # Don't fail AMS callback if MQTT fails
  2514. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2515. # This ensures frontend gets immediate updates when AMS slots are configured
  2516. try:
  2517. state = printer_manager.get_status(printer_id)
  2518. if state:
  2519. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2520. await ws_manager.send_printer_status(
  2521. printer_id,
  2522. printer_state_to_dict(
  2523. state,
  2524. printer_id,
  2525. printer_manager.get_model(printer_id),
  2526. printer_manager.get_drying_targets(printer_id),
  2527. ),
  2528. )
  2529. except Exception as e:
  2530. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2531. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2532. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2533. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2534. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2535. # "no existing assignment" for the same (printer, ams, tray) and race to
  2536. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2537. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2538. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2539. try:
  2540. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2541. from sqlalchemy.orm import selectinload
  2542. from backend.app.api.routes.settings import get_setting
  2543. from backend.app.models.spool import Spool
  2544. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2545. from backend.app.services.spool_tag_matcher import (
  2546. auto_assign_spool,
  2547. create_spool_from_tray,
  2548. find_matching_untagged_spool,
  2549. get_spool_by_tag,
  2550. is_bambu_tag,
  2551. is_valid_tag,
  2552. link_tag_to_inventory_spool,
  2553. )
  2554. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2555. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2556. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2557. if not _spoolman_on or _spoolman_on.lower() != "true":
  2558. for ams_unit in ams_data:
  2559. if not isinstance(ams_unit, dict):
  2560. continue
  2561. ams_id = int(ams_unit.get("id", 0))
  2562. for tray in ams_unit.get("tray", []):
  2563. if not isinstance(tray, dict):
  2564. continue
  2565. tray_id = int(tray.get("id", 0))
  2566. tag_uid = tray.get("tag_uid", "")
  2567. tray_uuid = tray.get("tray_uuid", "")
  2568. tray_info_idx = tray.get("tray_info_idx", "")
  2569. if not tray.get("tray_type"):
  2570. # Slot reported empty — drop any cached unknown-tag
  2571. # broadcast so reinserting the same spool re-prompts.
  2572. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2573. continue # Empty slot
  2574. # Check if assignment already exists for this slot
  2575. existing = await db.execute(
  2576. select(SA)
  2577. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2578. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2579. )
  2580. existing_assignment = existing.scalar_one_or_none()
  2581. if existing_assignment:
  2582. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2583. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2584. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2585. # Skip during active prints: the usage tracker handles deduction
  2586. # precisely via 3MF data on print completion. Without this guard the
  2587. # AMS remain% SET and the usage tracker ADD both fire from the same
  2588. # MQTT message, doubling the deduction (#880).
  2589. if _print_active:
  2590. continue
  2591. remain_raw = tray.get("remain")
  2592. if (
  2593. remain_raw is not None
  2594. and existing_assignment.spool
  2595. and not existing_assignment.spool.weight_locked
  2596. ):
  2597. try:
  2598. remain_val = int(remain_raw)
  2599. except (TypeError, ValueError):
  2600. remain_val = -1
  2601. if 1 <= remain_val <= 100:
  2602. lw = existing_assignment.spool.label_weight or 1000
  2603. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2604. current_used = existing_assignment.spool.weight_used or 0
  2605. if new_used > current_used + 1:
  2606. logger.info(
  2607. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2608. existing_assignment.spool_id,
  2609. current_used,
  2610. new_used,
  2611. remain_val,
  2612. )
  2613. existing_assignment.spool.weight_used = new_used
  2614. await db.commit()
  2615. # Re-apply stored K-profile when the live tray's
  2616. # cali_idx drifted from the spool's stored profile.
  2617. # This catches "reset slot → re-read" and any other
  2618. # path where the firmware loses the user's K-profile
  2619. # selection while the SpoolAssignment row persists.
  2620. # Per the maintainer's rule: any time a spool tag is
  2621. # identified and matches inventory, the slot must be
  2622. # configured with the spool's stored settings. Without
  2623. # this block the existing-assignment branch only ran
  2624. # weight-sync and let the firmware-default cali_idx win.
  2625. try:
  2626. spool = existing_assignment.spool
  2627. if (
  2628. spool is not None
  2629. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2630. and spool.k_profiles
  2631. ):
  2632. state = printer_manager.get_status(printer_id)
  2633. slot_nozzle = resolve_slot_nozzle(
  2634. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2635. )
  2636. nozzle_diameter = slot_nozzle.diameter
  2637. slot_extruder = slot_nozzle.extruder
  2638. # Prefer exact extruder match, fall back to
  2639. # extruder-agnostic kp for the same printer +
  2640. # nozzle. Avoids hard-skipping when the AMS is
  2641. # mapped differently than at calibration time.
  2642. matching_kp = None
  2643. fallback_kp = None
  2644. for kp in spool.k_profiles:
  2645. if (
  2646. kp.printer_id != printer_id
  2647. or kp.nozzle_diameter != nozzle_diameter
  2648. or kp.cali_idx is None
  2649. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2650. ):
  2651. continue
  2652. if (
  2653. slot_extruder is not None
  2654. and kp.extruder is not None
  2655. and kp.extruder == slot_extruder
  2656. ):
  2657. matching_kp = kp
  2658. break
  2659. if fallback_kp is None:
  2660. fallback_kp = kp
  2661. chosen_kp = matching_kp or fallback_kp
  2662. if chosen_kp is not None:
  2663. live_cali_idx = tray.get("cali_idx")
  2664. # Only fire MQTT when the printer's live
  2665. # cali_idx differs from the stored value.
  2666. # Avoids spamming the broker on every
  2667. # MQTT push during steady-state operation.
  2668. if live_cali_idx != chosen_kp.cali_idx:
  2669. client = printer_manager.get_client(printer_id)
  2670. if client:
  2671. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2672. client.extrusion_cali_sel(
  2673. ams_id=ams_id,
  2674. tray_id=tray_id,
  2675. cali_idx=chosen_kp.cali_idx,
  2676. filament_id=cali_filament_id,
  2677. nozzle_diameter=nozzle_diameter,
  2678. )
  2679. logger.info(
  2680. "Re-applied K-profile cali_idx=%d for spool %d "
  2681. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2682. chosen_kp.cali_idx,
  2683. spool.id,
  2684. printer_id,
  2685. ams_id,
  2686. tray_id,
  2687. live_cali_idx,
  2688. )
  2689. except Exception:
  2690. logger.exception(
  2691. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2692. printer_id,
  2693. ams_id,
  2694. tray_id,
  2695. )
  2696. continue
  2697. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2698. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2699. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2700. if not spool:
  2701. # Try matching an untagged inventory spool (same material/color)
  2702. spool = await find_matching_untagged_spool(db, tray)
  2703. if spool:
  2704. await link_tag_to_inventory_spool(db, spool, tray)
  2705. elif _auto_add_unknown:
  2706. spool = await create_spool_from_tray(db, tray)
  2707. else:
  2708. # Auto-add disabled: surface the slot so the
  2709. # user can add it manually via the UI.
  2710. await _broadcast_unknown_tag(
  2711. printer_id=printer_id,
  2712. ams_id=ams_id,
  2713. tray_id=tray_id,
  2714. tag_uid=tag_uid,
  2715. tray_uuid=tray_uuid,
  2716. tray_type=tray.get("tray_type"),
  2717. tray_color=tray.get("tray_color"),
  2718. tray_sub_brands=tray.get("tray_sub_brands"),
  2719. tray_count=len(ams_unit.get("tray", [])),
  2720. )
  2721. continue
  2722. # Slot matched (existing tag, untagged inventory
  2723. # match, or freshly auto-created spool) — drop any
  2724. # stale dedup so a future tag swap re-prompts.
  2725. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2726. await auto_assign_spool(
  2727. printer_id,
  2728. ams_id,
  2729. tray_id,
  2730. spool,
  2731. printer_manager,
  2732. db,
  2733. tray_info_idx=tray_info_idx,
  2734. )
  2735. await db.commit()
  2736. await ws_manager.broadcast(
  2737. {
  2738. "type": "spool_auto_assigned",
  2739. "printer_id": printer_id,
  2740. "ams_id": ams_id,
  2741. "tray_id": tray_id,
  2742. "spool_id": spool.id,
  2743. }
  2744. )
  2745. logger.info(
  2746. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2747. spool.id,
  2748. printer_id,
  2749. ams_id,
  2750. tray_id,
  2751. )
  2752. elif is_valid_tag(tag_uid, tray_uuid):
  2753. # Non-BL spool with some tag — let user choose
  2754. await _broadcast_unknown_tag(
  2755. printer_id=printer_id,
  2756. ams_id=ams_id,
  2757. tray_id=tray_id,
  2758. tag_uid=tag_uid,
  2759. tray_uuid=tray_uuid,
  2760. tray_type=tray.get("tray_type"),
  2761. tray_color=tray.get("tray_color"),
  2762. tray_sub_brands=tray.get("tray_sub_brands"),
  2763. tray_count=len(ams_unit.get("tray", [])),
  2764. )
  2765. # No-tag slots (generic non-RFID filament) are left alone:
  2766. # nothing to identify, prompting "+ Add" would just create
  2767. # ghost spools with empty tags on every confirm.
  2768. except Exception as e:
  2769. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2770. try:
  2771. async with async_session() as db:
  2772. from backend.app.api.routes.settings import get_setting
  2773. from backend.app.models.printer import Printer
  2774. # Check if Spoolman is enabled
  2775. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2776. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2777. return
  2778. # Check sync mode
  2779. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2780. if sync_mode and sync_mode != "auto":
  2781. return # Only sync on auto mode
  2782. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2783. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2784. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2785. # always owned by per-print tracking, never by AMS auto-sync. The
  2786. # setting is still read by the settings UI for backwards compat but
  2787. # has no effect on the sync path here.
  2788. # Get Spoolman URL
  2789. spoolman_url = await get_setting(db, "spoolman_url")
  2790. if not spoolman_url:
  2791. return
  2792. # Get or create Spoolman client
  2793. client = await get_spoolman_client()
  2794. if not client:
  2795. try:
  2796. client = await init_spoolman_client(spoolman_url)
  2797. except ValueError as exc:
  2798. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2799. return
  2800. # Check if Spoolman is reachable
  2801. if not await client.health_check():
  2802. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2803. return
  2804. # Get printer name for location
  2805. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2806. printer = result.scalar_one_or_none()
  2807. printer_name = printer.name if printer else f"Printer {printer_id}"
  2808. # OPTIMIZATION: Fetch all spools once before processing trays
  2809. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2810. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2811. try:
  2812. cached_spools = await client.get_spools()
  2813. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2814. except Exception as e:
  2815. logger.error(
  2816. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2817. printer_id,
  2818. e,
  2819. )
  2820. return
  2821. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2822. from sqlalchemy.orm import selectinload
  2823. from backend.app.models.spool_assignment import SpoolAssignment
  2824. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2825. from backend.app.services.ams_slot_presence import spool_present
  2826. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2827. # Built-in remaining weight, used by sync_ams_tray only when the
  2828. # firmware reports an unusable remain%/tray_weight for a slot.
  2829. #
  2830. # Left empty since #2812. This block runs in Spoolman mode only,
  2831. # and until then the built-in table was emptied on the switch, so
  2832. # there was never anything here to read and the fallback was inert.
  2833. # Preserving those rows makes it live again, and it is keyed by slot
  2834. # rather than by spool: after a mode switch the tray may well hold
  2835. # different filament, and ``create_spool`` writes ``remaining_weight``
  2836. # unconditionally, so a stale figure would be seeded into a brand new
  2837. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2838. # intent survives for whoever revisits the cross-mode fallback.
  2839. inventory_weights: dict[tuple[int, int], float] = {}
  2840. if not await spoolman_owns_assignments(db):
  2841. try:
  2842. assign_result = await db.execute(
  2843. select(SpoolAssignment)
  2844. .options(selectinload(SpoolAssignment.spool))
  2845. .where(SpoolAssignment.printer_id == printer_id)
  2846. )
  2847. for assignment in assign_result.scalars().all():
  2848. spool = assignment.spool
  2849. if spool and spool.label_weight > 0:
  2850. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2851. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2852. except Exception as e:
  2853. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2854. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2855. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2856. try:
  2857. slot_result = await db.execute(
  2858. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2859. )
  2860. for slot in slot_result.scalars().all():
  2861. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2862. except Exception as e:
  2863. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2864. # Sync each AMS tray and collect slot changes for DB persistence
  2865. synced = 0
  2866. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2867. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2868. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2869. for ams_unit in ams_data:
  2870. if not isinstance(ams_unit, dict):
  2871. continue
  2872. ams_id = int(ams_unit.get("id", 0))
  2873. trays = ams_unit.get("tray", [])
  2874. for tray_data in trays:
  2875. if not isinstance(tray_data, dict):
  2876. continue
  2877. tray_id_raw = int(tray_data.get("id", 0))
  2878. tray = client.parse_ams_tray(ams_id, tray_data)
  2879. if not tray:
  2880. # Empty tray slot — record for local assignment cleanup
  2881. # and drop any cached unknown-tag broadcast so a
  2882. # reinserted spool re-prompts.
  2883. #
  2884. # Not during a running print: a slot that empties there
  2885. # is a filament runout, and the spool is still in the
  2886. # AMS. `spoolman_slot_assignments` is how a tag-less
  2887. # spool assigned through the Bambuddy UI is resolved at
  2888. # completion (#1459), so deleting the row mid-print
  2889. # loses the runout segment's usage — the same failure
  2890. # the internal inventory's auto-unlink had.
  2891. #
  2892. # Nor when firmware's presence bit says the slot is
  2893. # occupied. parse_ams_tray calls a tray with no type or
  2894. # no colour empty, and a spool the AMS cannot read has
  2895. # neither until something configures it — so a tag-less
  2896. # spool assigned through the UI had its row deleted by
  2897. # the first idle push after it was inserted. Same
  2898. # deletion as the internal inventory's in #3100, same
  2899. # answer, so the two modes stay in step.
  2900. #
  2901. # And only once the slot has stayed empty for the grace
  2902. # period -- the internal inventory's #3186 answer, for
  2903. # the same one-push blank.
  2904. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2905. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2906. if not printing_now and (
  2907. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2908. ):
  2909. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2910. empty_slots.append((ams_id, tray_id_raw))
  2911. else:
  2912. spoolman_held.add(hold_key)
  2913. logger.info(
  2914. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2915. "unlinking if it is still empty in %ds",
  2916. ams_id,
  2917. tray_id_raw,
  2918. linked_spool,
  2919. int(slot_unlink_grace.GRACE_SECONDS),
  2920. )
  2921. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2922. continue
  2923. spool_tag = (
  2924. tray.tray_uuid
  2925. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2926. else tray.tag_uid
  2927. )
  2928. # Provide the hint only when no RFID is available
  2929. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2930. try:
  2931. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2932. result = await client.sync_ams_tray(
  2933. tray,
  2934. printer_name,
  2935. db,
  2936. # Per-print tracking is the only weight writer (#1119).
  2937. # AMS auto-sync still maintains spool metadata / slot
  2938. # assignments but no longer touches remaining_weight.
  2939. disable_weight_sync=True,
  2940. cached_spools=cached_spools,
  2941. inventory_remaining=inv_remaining,
  2942. spoolman_spool_id_hint=hint,
  2943. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2944. )
  2945. if result is None and spool_tag and not auto_add_unknown_rfid:
  2946. # Spoolman skipped auto-create per user setting — surface
  2947. # the slot so the UI can offer "+ Add to inventory".
  2948. await _broadcast_unknown_tag(
  2949. printer_id=printer_id,
  2950. ams_id=ams_id,
  2951. tray_id=tray.tray_id,
  2952. tag_uid=tray.tag_uid or "",
  2953. tray_uuid=tray.tray_uuid or "",
  2954. tray_type=tray.tray_type,
  2955. tray_color=tray.tray_color,
  2956. tray_sub_brands=tray.tray_sub_brands,
  2957. tray_count=len(trays),
  2958. )
  2959. elif result:
  2960. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2961. if result:
  2962. synced += 1
  2963. if result.get("id"):
  2964. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2965. # If a new spool was created, add it to the cache
  2966. # so subsequent trays can find it if they reference the same tag
  2967. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2968. if not spool_exists:
  2969. cached_spools.append(result)
  2970. logger.debug(
  2971. "[Printer %s] Added newly created spool %s to cache",
  2972. printer_id,
  2973. result["id"],
  2974. )
  2975. # Reconcile slot_preset_mappings (the same row internal
  2976. # mode keeps in sync via inventory + spool_tag_matcher).
  2977. # Without this the slot card surfaces the previous spool's
  2978. # preset name — same bug shape, different inventory mode.
  2979. from backend.app.services.slot_preset_writer import (
  2980. upsert_slot_preset_for_spoolman_spool,
  2981. )
  2982. await upsert_slot_preset_for_spoolman_spool(
  2983. db=db,
  2984. spoolman_spool=result,
  2985. tray_info_idx=tray.tray_info_idx or "",
  2986. tray_sub_brands=tray.tray_sub_brands or "",
  2987. tray_type=tray.tray_type or "",
  2988. printer_id=printer_id,
  2989. ams_id=ams_id,
  2990. tray_id=tray.tray_id,
  2991. )
  2992. except Exception as e:
  2993. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2994. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2995. if synced > 0:
  2996. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2997. # Persist slot assignment changes to the local table
  2998. if slot_changes or empty_slots:
  2999. try:
  3000. for ams_id, tray_id, spool_id in slot_changes:
  3001. await db.execute(
  3002. text(
  3003. "INSERT INTO spoolman_slot_assignments"
  3004. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  3005. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  3006. " ON CONFLICT(printer_id, ams_id, tray_id)"
  3007. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  3008. ),
  3009. {
  3010. "printer_id": printer_id,
  3011. "ams_id": ams_id,
  3012. "tray_id": tray_id,
  3013. "spool_id": spool_id,
  3014. },
  3015. )
  3016. for ams_id, tray_id in empty_slots:
  3017. await db.execute(
  3018. delete(SpoolmanSlotAssignment).where(
  3019. SpoolmanSlotAssignment.printer_id == printer_id,
  3020. SpoolmanSlotAssignment.ams_id == ams_id,
  3021. SpoolmanSlotAssignment.tray_id == tray_id,
  3022. )
  3023. )
  3024. await db.commit()
  3025. except Exception as e:
  3026. await db.rollback()
  3027. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3028. else:
  3029. # Tell open browsers the slot changed. This loop rewrites
  3030. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  3031. # above, and the AMS slot card reads that row ahead of the
  3032. # live tray_info_idx -- so with no event the card keeps
  3033. # showing the previous spool's preset name. Internal mode
  3034. # raises spool_auto_assigned for the same reason; this loop
  3035. # broadcast nothing at all, which made Spoolman mode the
  3036. # worse half of the same bug. On the else branch so a
  3037. # failed commit stays silent and a broadcast failure cannot
  3038. # roll back rows that are already committed.
  3039. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  3040. await ws_manager.broadcast(
  3041. {
  3042. "type": "spool_assignment_changed",
  3043. "printer_id": printer_id,
  3044. "ams_id": ams_id,
  3045. "tray_id": tray_id,
  3046. }
  3047. )
  3048. except Exception as e:
  3049. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3050. # Largest finish photo attached to a notification; a bigger one is still linked.
  3051. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3052. async def _finish_photo_for_notification(
  3053. db, archive, archive_id: int, filename: str
  3054. ) -> tuple[str | None, bytes | None]:
  3055. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3056. With authentication off the link is the archive's own photo route, as it
  3057. always was: it opens without a login and doesn't expire. With
  3058. authentication on that route needs a media token, which nothing tapping a
  3059. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3060. link only ever answered 401. The photo is then saved as a notification
  3061. photo as well (utils/notification_photos.py) and the link points there: an
  3062. unguessable name that opens this one photo and nothing else, for 3 days.
  3063. The link is relative when no External URL is set. Bytes over
  3064. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3065. ``(None, None)`` when the photo can't be found.
  3066. """
  3067. from backend.app.api.routes.settings import get_setting
  3068. from backend.app.core.auth import is_auth_enabled
  3069. from backend.app.utils.archive_paths import find_archive_photo
  3070. from backend.app.utils.notification_photos import save_notification_photo
  3071. log = logging.getLogger(__name__)
  3072. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3073. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3074. photo_bytes: bytes | None = None
  3075. try:
  3076. photo_path = find_archive_photo(archive, filename)
  3077. if photo_path is not None:
  3078. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3079. except Exception as e:
  3080. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3081. try:
  3082. auth_on = await is_auth_enabled(db)
  3083. except Exception:
  3084. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3085. if auth_on:
  3086. url = None
  3087. if photo_bytes:
  3088. try:
  3089. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3090. url = f"{base}/api/v1/notifications/photos/{name}"
  3091. except Exception as e:
  3092. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3093. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3094. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3095. return url, None
  3096. if photo_bytes:
  3097. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3098. return url, photo_bytes
  3099. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3100. """Capture a camera snapshot for notification image attachment.
  3101. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3102. Uses: external camera > buffered frame > fresh capture.
  3103. Turns the chamber light on for the picture when the printer asks for it
  3104. (#1655). ``light=False`` is for callers that capture all through a print,
  3105. where the light would flash with every frame.
  3106. """
  3107. if not printer:
  3108. return None
  3109. async with camera_light(printer if light else None):
  3110. return await _capture_snapshot_frame(printer_id, printer, logger)
  3111. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3112. """The capture behind ``_capture_snapshot_for_notification``."""
  3113. try:
  3114. from backend.app.api.routes.settings import get_setting
  3115. async with async_session() as db:
  3116. capture_enabled = await get_setting(db, "capture_finish_photo")
  3117. if capture_enabled is not None and capture_enabled.lower() != "true":
  3118. return None
  3119. # Try external camera first
  3120. if printer.external_camera_enabled and printer.external_camera_url:
  3121. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3122. from backend.app.api.routes.camera import live_frame_for_capture
  3123. from backend.app.services.external_camera import capture_frame
  3124. # An external camera allows one reader, so capturing while a viewer
  3125. # is attached fails (#2707). A None here falls through to the paths
  3126. # below exactly as a failed capture did.
  3127. defer, buffered = live_frame_for_capture(printer_id)
  3128. if defer:
  3129. frame_data = buffered
  3130. else:
  3131. frame_data = await capture_frame(
  3132. printer.external_camera_url,
  3133. printer.external_camera_type or "mjpeg",
  3134. snapshot_url=printer.external_camera_snapshot_url,
  3135. )
  3136. if frame_data and len(frame_data) <= 2_500_000:
  3137. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3138. return _apply_camera_rotation(frame_data, printer, logger)
  3139. # Try buffered frame from active stream
  3140. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3141. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3142. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3143. buffered_frame = get_buffered_frame(printer_id)
  3144. if (active_for_printer or active_chamber) and buffered_frame:
  3145. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3146. if len(buffered_frame) <= 2_500_000:
  3147. return _apply_camera_rotation(buffered_frame, printer, logger)
  3148. # Fresh capture from printer camera
  3149. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3150. from backend.app.services.camera import capture_camera_frame_bytes
  3151. frame_data = await capture_camera_frame_bytes(
  3152. printer.ip_address, printer.access_code, printer.model, timeout=15
  3153. )
  3154. if frame_data and len(frame_data) <= 2_500_000:
  3155. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3156. return _apply_camera_rotation(frame_data, printer, logger)
  3157. except Exception as e:
  3158. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3159. return None
  3160. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3161. """#1867: bank a recent in-print camera frame for the finish photo.
  3162. Called on every layer change and (#2547) on every print-progress advance.
  3163. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3164. path has a pre-End-G-code image for prints that end with a plate swap.
  3165. Both drivers are print telemetry that stops the instant printing ends: no
  3166. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3167. plate swap) executes. So the last banked frame is always the finished print,
  3168. never the swapped plate — that property is what the #1867 path relies on and
  3169. it must survive any change to the throttle below.
  3170. Layer changes alone were not enough: they stop when the *final* layer
  3171. begins, which on a three-minute last layer left the bank stale by the whole
  3172. length of that layer (#2547). Progress keeps ticking through it.
  3173. Best-effort: any failure just leaves the previous banked frame.
  3174. """
  3175. logger = logging.getLogger(__name__)
  3176. client = printer_manager.get_client(printer_id)
  3177. state = client.state if client else None
  3178. if not state or state.state != "RUNNING":
  3179. return
  3180. # Only during actual extrusion — firmware ticks layer_num during the
  3181. # pre-print calibration sequence, whose sub-stages are non-zero.
  3182. if state.mc_print_sub_stage not in (None, 0):
  3183. return
  3184. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3185. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3186. # now that progress advances also drive banking, that exemption would fire a
  3187. # camera grab on every percent tick of the last layer. Bambu printers accept
  3188. # one RTSP client at a time, so each grab contends with the live view.
  3189. now = time.monotonic()
  3190. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3191. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3192. return
  3193. total = state.total_layers or 0
  3194. try:
  3195. async with async_session() as db:
  3196. from backend.app.models.printer import Printer
  3197. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3198. printer = result.scalar_one_or_none()
  3199. if not printer:
  3200. return
  3201. # Reuses the notification snapshot path, which honours the
  3202. # `capture_finish_photo` setting (returns None when disabled) so we
  3203. # don't bank frames the user never asked for. Without the chamber light
  3204. # (#1655): this runs every 25 seconds for the whole print.
  3205. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3206. if frame:
  3207. _inprint_frame_bank[printer_id] = frame
  3208. _inprint_frame_bank_ts[printer_id] = now
  3209. logger.debug(
  3210. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3211. printer_id,
  3212. layer_num,
  3213. total,
  3214. len(frame),
  3215. )
  3216. except Exception as e:
  3217. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3218. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3219. """Apply camera rotation to snapshot image if configured."""
  3220. from backend.app.services.camera import apply_camera_rotation
  3221. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3222. async def _send_print_start_notification(
  3223. printer_id: int,
  3224. data: dict,
  3225. archive_data: dict | None = None,
  3226. logger=None,
  3227. ):
  3228. """Helper to send print start notification with optional archive data."""
  3229. if logger is None:
  3230. logger = logging.getLogger(__name__)
  3231. try:
  3232. async with async_session() as db:
  3233. from backend.app.models.printer import Printer
  3234. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3235. printer = result.scalar_one_or_none()
  3236. printer_name = printer.name if printer else f"Printer {printer_id}"
  3237. # Capture camera snapshot for notification image attachment
  3238. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3239. if image_data:
  3240. if archive_data is None:
  3241. archive_data = {}
  3242. archive_data["image_data"] = image_data
  3243. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3244. # Send user-specific email notification for print start
  3245. if archive_data and archive_data.get("created_by_id"):
  3246. await notification_service.send_user_print_email(
  3247. event_type="user_print_start",
  3248. created_by_id=archive_data["created_by_id"],
  3249. printer_name=printer_name,
  3250. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3251. db=db,
  3252. )
  3253. except Exception as e:
  3254. logger.warning("Notification on_print_start failed: %s", e)
  3255. async def _dispatch_user_print_email(
  3256. status: str,
  3257. created_by_id: int | None,
  3258. printer_name: str,
  3259. filename: str,
  3260. db,
  3261. image_data: bytes | None = None,
  3262. finish_photo_url: str | None = None,
  3263. ) -> None:
  3264. """Send a user-specific print-completion email based on print status.
  3265. Maps the normalised print status to the correct event type and delegates
  3266. to :meth:`NotificationService.send_user_print_email`. A single helper
  3267. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3268. "stopped"`` dispatch block at every call site.
  3269. Does nothing if *created_by_id* is ``None``.
  3270. """
  3271. if created_by_id is None:
  3272. return
  3273. if status == "completed":
  3274. event_type = "user_print_complete"
  3275. elif status == "failed":
  3276. event_type = "user_print_failed"
  3277. elif status in ("stopped", "aborted", "cancelled"):
  3278. event_type = "user_print_stopped"
  3279. else:
  3280. return
  3281. await notification_service.send_user_print_email(
  3282. event_type=event_type,
  3283. created_by_id=created_by_id,
  3284. printer_name=printer_name,
  3285. filename=filename,
  3286. db=db,
  3287. image_data=image_data,
  3288. finish_photo_url=finish_photo_url,
  3289. )
  3290. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3291. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3292. try:
  3293. from backend.app.services.archive import extract_printable_objects_from_archive
  3294. client = printer_manager.get_client(printer_id)
  3295. if not client:
  3296. return
  3297. # Extract with positions for UI overlay, scoped to the plate that
  3298. # is printing — resolve_plate_id is the same resolver /cover uses,
  3299. # so the object list can't disagree with the thumbnail it is drawn
  3300. # over (#2522).
  3301. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3302. app_settings.base_dir / archive.file_path,
  3303. plate_number=resolve_plate_id(client.state),
  3304. )
  3305. if printable_objects:
  3306. client.state.printable_objects = printable_objects
  3307. client.state.printable_objects_bbox_all = bbox_all
  3308. client.state.skipped_objects = []
  3309. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3310. except Exception as e:
  3311. logger.debug("Failed to extract printable objects from archive: %s", e)
  3312. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3313. """Put the skip-objects list back after a restart mid-print.
  3314. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3315. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3316. which the #1304 guard suppresses on the first RUNNING push after startup.
  3317. Everything else this hook restores (the archive, the usage-tracking session,
  3318. the timelapse baseline) was already handled; the object list was not, so a
  3319. restart mid-print took skip-objects away for the rest of that print.
  3320. Nothing recovered it either: the printer card gates its Skip button on the
  3321. object count, and the one endpoint that can rebuild the list is reachable
  3322. only from the modal that button opens.
  3323. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3324. leftover ``status="printing"`` row from a completion we never saw cannot
  3325. hand this print someone else's objects. Without one, nothing is loaded
  3326. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3327. case on demand.
  3328. """
  3329. client = printer_manager.get_client(printer_id)
  3330. if client is None or client.state.printable_objects:
  3331. return
  3332. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3333. if subtask_id in ("", "0"):
  3334. return
  3335. from backend.app.models.archive import PrintArchive
  3336. archive = await db.scalar(
  3337. select(PrintArchive)
  3338. .where(
  3339. PrintArchive.printer_id == printer_id,
  3340. PrintArchive.status == "printing",
  3341. PrintArchive.subtask_id == subtask_id,
  3342. )
  3343. .order_by(PrintArchive.created_at.desc())
  3344. .limit(1)
  3345. )
  3346. if archive is not None:
  3347. _load_objects_from_archive(archive, printer_id, logger)
  3348. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3349. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3350. # past it; the second covers a handshake that failed again on the way back and
  3351. # armed a fresh one. Module-level so tests can shrink them.
  3352. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3353. # Retry ladder for the other temporary give-up: the file service answered and
  3354. # the transfer still did not finish, which at print start is usually the printer
  3355. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3356. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3357. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3358. # two cover a printer that stays busy well into the print.
  3359. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3360. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3361. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3362. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3363. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3364. # by view, so two views race), the cool-off retry task, and print completion.
  3365. # Without this they each read file_path == "" and each run a full copy, so the row
  3366. # ends up pointing at one timestamped directory while the others sit orphaned.
  3367. #
  3368. # Keyed by printer rather than archive because a printer runs one print at a time,
  3369. # which makes the two equally strong here — and it bounds the dict by printer
  3370. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3371. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3372. # resuming, so "no waiters" is not a question this API can answer.
  3373. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3374. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3375. """Fill in a no-3MF archive from a 3MF that turned up later.
  3376. Returns True when the row was upgraded. Safe to call speculatively: it
  3377. verifies the archive still exists, is still a fallback, and that the file
  3378. is a readable 3MF before touching anything.
  3379. Serialised per printer — see ``_fallback_recovery_locks``.
  3380. """
  3381. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3382. async with lock:
  3383. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3384. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3385. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3386. import zipfile
  3387. from backend.app.models.archive import PrintArchive
  3388. from backend.app.services.archive import ArchiveService
  3389. logger = logging.getLogger(__name__)
  3390. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3391. return False
  3392. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3393. # A truncated or half-written download is worse than no download: it
  3394. # would replace an honest empty archive with wrong metadata.
  3395. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3396. return False
  3397. async with async_session() as db:
  3398. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3399. if archive is None or archive.deleted_at is not None:
  3400. return False
  3401. if archive.file_path:
  3402. # Already recovered, or never was a fallback. Either way there is a
  3403. # real 3MF attached and overwriting it is not this function's job.
  3404. return False
  3405. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3406. service = ArchiveService(db)
  3407. recovered = await service.archive_print(
  3408. printer_id=printer_id,
  3409. source_file=source_3mf,
  3410. print_data={**print_data, "status": archive.status or "printing"},
  3411. subtask_id=archive.subtask_id,
  3412. update_archive_id=archive.id,
  3413. )
  3414. if recovered is None:
  3415. return False
  3416. logger.info(
  3417. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3418. archive_id,
  3419. source_3mf,
  3420. recovered.file_size,
  3421. )
  3422. # `archive_updated`, not `archive_created` — the row was already on the
  3423. # Archives page as an empty card and is now filled in, not new.
  3424. await ws_manager.send_archive_updated(
  3425. {
  3426. "id": recovered.id,
  3427. "printer_id": recovered.printer_id,
  3428. "filename": recovered.filename,
  3429. "print_name": recovered.print_name,
  3430. "status": recovered.status,
  3431. }
  3432. )
  3433. return True
  3434. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3435. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3436. Called from the paths that pull a 3MF for a print that is already under way
  3437. — chiefly the cover endpoint, which downloads the very file the archive flow
  3438. could not get and, before #2957, used it for a thumbnail and nothing else.
  3439. The bytes are already local, so this costs a parse and a row update.
  3440. No-op when the running print has a real archive, which is the common case.
  3441. """
  3442. from backend.app.models.archive import PrintArchive
  3443. logger = logging.getLogger(__name__)
  3444. # `_active_prints` is keyed on the raw names seen at print start — the
  3445. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3446. # Callers here arrive with whichever variant their own path produced, so
  3447. # match on the same normalization the download cache uses rather than on an
  3448. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3449. # endpoint find an archive registered under "Desktop_Goose".
  3450. wanted = normalize_3mf_name(name)
  3451. archive_id = None
  3452. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3453. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3454. archive_id = value
  3455. break
  3456. if archive_id is None:
  3457. return False
  3458. async with async_session() as db:
  3459. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3460. # Cheap pre-check so the common case (a normal archive) does no work.
  3461. if archive is None or archive.file_path or archive.deleted_at is not None:
  3462. return False
  3463. try:
  3464. return await _recover_fallback_archive(archive_id, path, printer_id)
  3465. except Exception as e:
  3466. # Recovery is opportunistic. A failure here must never take down the
  3467. # caller, which is usually just trying to render a thumbnail.
  3468. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3469. return False
  3470. def _schedule_fallback_3mf_retry(
  3471. printer_id: int,
  3472. archive_id: int,
  3473. filenames: list[str],
  3474. delays: tuple[float, ...] | None = None,
  3475. reason: str = REASON_FTPS_COOLOFF,
  3476. ) -> None:
  3477. """Re-attempt the 3MF download after a temporary give-up.
  3478. ``reason`` says which give-up this is, and picks the default ladder: an
  3479. FTPS cool-off has to be waited out, while a transfer that timed out under
  3480. contention is worth asking about again straight away (#3063). It is only
  3481. read for the ladder and the log line -- the retry itself is identical, since
  3482. in both cases the file is on the printer and the last attempt at it failed
  3483. for a reason that does not last.
  3484. """
  3485. logger = logging.getLogger(__name__)
  3486. if delays is None:
  3487. delays = (
  3488. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3489. if reason == REASON_FTP_TRANSFER_FAILED
  3490. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3491. )
  3492. async def _retry() -> None:
  3493. from backend.app.models.archive import PrintArchive
  3494. from backend.app.models.printer import Printer
  3495. for delay in delays:
  3496. await asyncio.sleep(delay)
  3497. async with async_session() as db:
  3498. archive = (
  3499. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3500. ).scalar_one_or_none()
  3501. if archive is None or archive.deleted_at is not None or archive.file_path:
  3502. return
  3503. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3504. if printer is None:
  3505. return
  3506. # Read the fields while the session is open rather than touching
  3507. # a detached instance minutes later, mid-download.
  3508. printer_ip = printer.ip_address
  3509. printer_code = printer.access_code
  3510. printer_model = printer.model
  3511. # Someone else may have fetched it in the meantime — the cover
  3512. # endpoint routinely does, and its copy is the same bytes.
  3513. for name in filenames:
  3514. cached = get_cached_3mf(printer_id, name)
  3515. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3516. return
  3517. if ftps_handshake_blocked(printer_ip):
  3518. logger.info(
  3519. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3520. printer_id,
  3521. archive_id,
  3522. )
  3523. continue
  3524. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3525. for candidate in filenames:
  3526. # Bare name only. These come from the print-start flow, which
  3527. # already strips the path, but the local temp write must not
  3528. # depend on that holding for every future caller — a name that
  3529. # is absolute or contains ".." would otherwise escape the data
  3530. # volume via the `/` operator.
  3531. name = Path(candidate).name
  3532. if not name or name in (".", ".."):
  3533. continue
  3534. if not name.endswith(".3mf"):
  3535. name = f"{name}.3mf"
  3536. temp_path = app_settings.archive_dir / "temp" / name
  3537. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3538. try:
  3539. hit = await download_file_try_paths_async(
  3540. printer_ip,
  3541. printer_code,
  3542. ftp_probe_paths(name),
  3543. temp_path,
  3544. socket_timeout=ftp_timeout,
  3545. printer_model=printer_model,
  3546. )
  3547. except Exception as e:
  3548. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3549. continue
  3550. if not hit:
  3551. continue
  3552. cache_3mf_download(printer_id, name, temp_path)
  3553. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3554. return
  3555. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3556. async def _guarded() -> None:
  3557. try:
  3558. await _retry()
  3559. except asyncio.CancelledError:
  3560. raise
  3561. except Exception as e:
  3562. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3563. finally:
  3564. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3565. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3566. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3567. if existing and not existing.done():
  3568. existing.cancel()
  3569. task = asyncio.create_task(_guarded())
  3570. _fallback_3mf_retry_tasks[printer_id] = task
  3571. logger.info(
  3572. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3573. archive_id,
  3574. reason,
  3575. printer_id,
  3576. ", ".join(f"{d:g}s" for d in delays),
  3577. )
  3578. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3579. """Whether an archive created here should ask for the print's outcome (#1898).
  3580. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3581. branches below: a queued job already has its archive and takes the
  3582. expected-print branch, where the queue item's own ``confirm_outcome``
  3583. decides. The queue is still consulted, because a restart mid-print empties
  3584. ``_expected_prints`` — without the check the setting could override a queue
  3585. item that deliberately has the flag off. Any failure answers "don't ask":
  3586. an unwanted prompt is worse than a missing one, and this must never be the
  3587. reason a print goes unarchived.
  3588. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3589. leaves one behind when a completion cannot be matched to it
  3590. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3591. only takes it back once the printer has sat connected and terminal for
  3592. minutes. Until then every screen-started print on that printer would
  3593. silently lose its prompt, so the row is held against ``observed_name`` by
  3594. the same comparison a completion uses: a positive disagreement means the row
  3595. is about some other run and this print is external after all.
  3596. """
  3597. logger = logging.getLogger(__name__)
  3598. try:
  3599. # A savepoint rather than a rollback of the caller's transaction on
  3600. # failure: a failed statement leaves the transaction unusable, but a
  3601. # full rollback also expires every object the caller has loaded (the
  3602. # printer, the archive it just created), and on an async session the
  3603. # next attribute read then raises instead of reloading. Everything here
  3604. # is a read, so undoing the savepoint loses nothing.
  3605. async with db.begin_nested():
  3606. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3607. except Exception as e:
  3608. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3609. return False
  3610. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3611. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3612. from backend.app.api.routes.settings import get_setting, setting_is_true
  3613. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3614. return False
  3615. from backend.app.models.print_queue import PrintQueueItem
  3616. dispatched_here = await db.scalar(
  3617. select(PrintQueueItem)
  3618. .where(
  3619. PrintQueueItem.printer_id == printer_id,
  3620. PrintQueueItem.status == "printing",
  3621. )
  3622. .limit(1)
  3623. )
  3624. if dispatched_here is None:
  3625. return True
  3626. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3627. observed = (observed_name or "").strip()
  3628. if not expected or not observed or _subtask_names_match(expected, observed):
  3629. logger.info(
  3630. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3631. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3632. printer_id,
  3633. dispatched_here.id,
  3634. )
  3635. return False
  3636. logger.info(
  3637. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3638. "%r; treating this as an externally started print.",
  3639. dispatched_here.id,
  3640. printer_id,
  3641. expected,
  3642. observed,
  3643. )
  3644. return True
  3645. async def _dispatch_outcome_confirmation_safely(
  3646. db,
  3647. printer_id: int,
  3648. printer_name: str,
  3649. data: dict,
  3650. archive_id: int,
  3651. archive_data: dict | None = None,
  3652. ) -> None:
  3653. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3654. The completion task sends the per-user print email on the same session
  3655. right after the prompt. A failed statement in the prompt leaves that
  3656. session needing a rollback, and without one the email step fails with
  3657. PendingRollbackError; the prompt is the optional part, so it must not be
  3658. the reason the email never goes out.
  3659. """
  3660. try:
  3661. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3662. except Exception as e:
  3663. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3664. try:
  3665. await db.rollback()
  3666. except Exception:
  3667. pass
  3668. async def dispatch_outcome_confirmation(
  3669. db,
  3670. printer_id: int,
  3671. printer_name: str,
  3672. data: dict,
  3673. archive_id: int,
  3674. archive_data: dict | None = None,
  3675. ) -> bool:
  3676. """Emit the post-print outcome prompt for a completed archive (#1898).
  3677. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3678. queue item, or from ``confirm_outcome_external_prints`` for a print
  3679. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3680. question still open. Mints the per-archive capability token the one-tap
  3681. verdict links carry.
  3682. Lives here rather than inline in ``on_print_complete``'s notification task
  3683. because that task swallows every exception: extracted, the gate and the two
  3684. emissions can be driven by a test, which is the only thing standing between
  3685. a regression here and a farm that quietly stops asking.
  3686. Returns whether a prompt was sent.
  3687. """
  3688. logger = logging.getLogger(__name__)
  3689. from backend.app.models.archive import PrintArchive
  3690. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3691. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3692. return False
  3693. import secrets as _secrets
  3694. # A spent token stays on the row so the one-tap route can recognise it, so
  3695. # "has a token" no longer means "answerable". A prompt going out now needs a
  3696. # live one: mint a new token whenever the stored one is already spent, or
  3697. # every button in the new message would land on the already-answered page.
  3698. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3699. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3700. confirm_archive.confirm_token_used_at = None
  3701. await db.commit()
  3702. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3703. base = await get_external_base_url(db)
  3704. if not await get_setting(db, "external_url"):
  3705. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3706. # absolute URL, so an unconfigured install used to get a message body
  3707. # with two unusable relative paths and no buttons at all. The shared
  3708. # fallback at least produces tappable links; say which setting makes
  3709. # them resolve from a phone.
  3710. logger.warning(
  3711. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3712. "Set Settings → External URL so they resolve away from this host.",
  3713. base,
  3714. )
  3715. token = confirm_archive.confirm_token
  3716. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3717. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3718. confirm_url = f"{base}/archives?confirm={archive_id}"
  3719. await ws_manager.send_print_confirm_request(
  3720. printer_id,
  3721. {
  3722. "archive_id": archive_id,
  3723. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3724. },
  3725. )
  3726. await notification_service.on_print_confirm_request(
  3727. printer_id,
  3728. printer_name,
  3729. data,
  3730. db,
  3731. archive_data=archive_data,
  3732. good_url=good_url,
  3733. reject_url=reject_url,
  3734. confirm_url=confirm_url,
  3735. archive_id=archive_id,
  3736. )
  3737. return True
  3738. async def _printer_gone(db, printer_id: int) -> bool:
  3739. """Whether the printer was deleted. A column read: the session's loaded
  3740. Printer would otherwise answer for the database."""
  3741. from backend.app.models.printer import Printer
  3742. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3743. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3744. """Remove the archive just written if its printer was deleted meanwhile.
  3745. The delete route sweeps the printer's archives before it commits, so a row
  3746. committed after that sweep (the check before writing passed while the
  3747. delete was still uncommitted) is left for a printer that will never report
  3748. the print's end. A row the sweep reached is the route's: deleted with the
  3749. printer's archives, or detached (printer_id NULL) when the user kept them,
  3750. and then left as it is. Either way nothing is registered for it. Run after
  3751. the archive's commit, before anything is registered for it.
  3752. """
  3753. from backend.app.models.archive import PrintArchive
  3754. if not await _printer_gone(db, printer_id):
  3755. return False
  3756. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3757. if owner == printer_id:
  3758. logging.getLogger(__name__).info(
  3759. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3760. )
  3761. await ArchiveService(db).delete_archive(archive_id)
  3762. await forget_printer(printer_id)
  3763. return True
  3764. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3765. """After an IntegrityError on a print start's archive write: whether it was
  3766. the printer being deleted, forgotten then (the caller returns).
  3767. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3768. commit, so an archive written or adopted for it meanwhile (one that sets
  3769. printer_id) waits and the printer's foreign key then refuses it. That is
  3770. the printer being deleted, not an error; anything else is re-raised by the
  3771. caller.
  3772. """
  3773. await db.rollback()
  3774. if not await _printer_gone(db, printer_id):
  3775. return False
  3776. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3777. await forget_printer(printer_id)
  3778. return True
  3779. async def _forget_if_printer_gone(printer_id: int) -> None:
  3780. """At the end of a print start: the slow steps after the last check (smart
  3781. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3782. printer's delete and its forget_printer, and then wrote state back.
  3783. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3784. SQLite; PostgreSQL refuses it.)
  3785. Its own session: those steps can leave the handler's needing a rollback (a
  3786. write to the archive the delete removed). Never raises: it runs inside the
  3787. fallback branch's try, whose except reports the archive as failed.
  3788. """
  3789. try:
  3790. async with async_session() as db:
  3791. gone = await _printer_gone(db, printer_id)
  3792. if gone:
  3793. await forget_printer(printer_id)
  3794. except Exception:
  3795. logging.getLogger(__name__).warning(
  3796. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3797. )
  3798. async def on_print_start(printer_id: int, data: dict):
  3799. """Handle print start - archive the 3MF file immediately."""
  3800. logger = logging.getLogger(__name__)
  3801. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3802. try:
  3803. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3804. except Exception:
  3805. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3806. # Clear any stale user-stopped flag from previous print cycles
  3807. _user_stopped_printers.discard(printer_id)
  3808. # A new print starts its milestones from zero (#3211). The status path only
  3809. # resets on progress below 5 while not printing, which a printer that goes
  3810. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3811. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3812. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3813. _last_progress_milestone[printer_id] = 0
  3814. _kill_switch_notification_tasks.pop(printer_id, None)
  3815. # #1721: drop any leftover pre-captured finish frame from a prior print
  3816. # so a never-consumed cache entry can't bleed into the new print's photo.
  3817. _stage22_finish_frames.pop(printer_id, None)
  3818. # #1867: same for the in-print frame bank — a queued print must not reuse
  3819. # the previous job's banked frame.
  3820. _inprint_frame_bank.pop(printer_id, None)
  3821. _inprint_frame_bank_ts.pop(printer_id, None)
  3822. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3823. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3824. # print's flag instead of inheriting it.
  3825. print_dispatch_context.adopt(printer_id)
  3826. # Cancel any active bed cooldown waiter for this printer
  3827. if _bed_cool_waiters.pop(printer_id, None):
  3828. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3829. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3830. from backend.app.api.routes.printers import clear_cover_cache
  3831. clear_cover_cache(printer_id)
  3832. await ws_manager.send_print_start(printer_id, data)
  3833. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3834. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3835. # MQTT relay - publish print start
  3836. try:
  3837. printer_info = printer_manager.get_printer(printer_id)
  3838. if printer_info:
  3839. await mqtt_relay.on_print_start(
  3840. printer_id,
  3841. printer_info.name,
  3842. printer_info.serial_number,
  3843. data.get("filename", ""),
  3844. data.get("subtask_name", ""),
  3845. )
  3846. except Exception:
  3847. pass # Don't fail print start callback if MQTT fails
  3848. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3849. # and mapping, and the seeded tray-change log.
  3850. #
  3851. # Unconditional, for both inventory backends. This only *captures* — the
  3852. # writing is still split, with the internal tracker skipped at completion
  3853. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3854. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3855. # tray-change log, and that log is the only record of which spool fed
  3856. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3857. # it on one side only would leave Spoolman users with the mid-print
  3858. # restart bug this fixes for everyone else.
  3859. try:
  3860. async with async_session() as db:
  3861. from backend.app.api.routes.settings import get_setting
  3862. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3863. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3864. await usage_on_print_start(
  3865. printer_id,
  3866. data,
  3867. printer_manager,
  3868. db=db,
  3869. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3870. )
  3871. except Exception as e:
  3872. logger.warning("Usage tracker on_print_start failed: %s", e)
  3873. # Track if notification was sent (to avoid sending twice)
  3874. notification_sent = False
  3875. # Smart plug automation: turn on plug when print starts
  3876. try:
  3877. async with async_session() as db:
  3878. await smart_plug_manager.on_print_start(printer_id, db)
  3879. except Exception as e:
  3880. logger.warning("Smart plug on_print_start failed: %s", e)
  3881. async with async_session() as db:
  3882. from backend.app.models.printer import Printer
  3883. from backend.app.services.bambu_ftp import list_files_async
  3884. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3885. printer = result.scalar_one_or_none()
  3886. # Plate detection check - pause if objects detected on build plate
  3887. logger.info(
  3888. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3889. )
  3890. if printer and printer.plate_detection_enabled:
  3891. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3892. # Release the pooled DB connection before the plate-detection camera
  3893. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3894. # printer SELECT has run so far — nothing to persist — so this commit
  3895. # is a data-noop that ends the read transaction and returns the
  3896. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3897. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3898. # archive lookups below re-acquire a fresh connection on next execute.
  3899. await db.commit()
  3900. try:
  3901. from backend.app.services.plate_detection import check_plate_empty
  3902. # Build ROI tuple from printer settings if available
  3903. roi = None
  3904. if all(
  3905. [
  3906. printer.plate_detection_roi_x is not None,
  3907. printer.plate_detection_roi_y is not None,
  3908. printer.plate_detection_roi_w is not None,
  3909. printer.plate_detection_roi_h is not None,
  3910. ]
  3911. ):
  3912. roi = (
  3913. printer.plate_detection_roi_x,
  3914. printer.plate_detection_roi_y,
  3915. printer.plate_detection_roi_w,
  3916. printer.plate_detection_roi_h,
  3917. )
  3918. # Auto-turn on chamber light if it's off for better detection
  3919. light_was_off = False
  3920. client = printer_manager.get_client(printer_id)
  3921. if client and client.state:
  3922. light_was_off = not client.state.chamber_light
  3923. if light_was_off:
  3924. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3925. client.set_chamber_light(True)
  3926. # Wait for light to physically turn on and camera to adjust exposure
  3927. await asyncio.sleep(2.5)
  3928. plate_photo_data = None
  3929. objects_detected = False
  3930. try:
  3931. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3932. plate_result = await check_plate_empty(
  3933. printer_id=printer_id,
  3934. ip_address=printer.ip_address,
  3935. access_code=printer.access_code,
  3936. model=printer.model,
  3937. include_debug_image=False,
  3938. external_camera_url=printer.external_camera_url,
  3939. external_camera_type=printer.external_camera_type,
  3940. use_external=printer.external_camera_enabled,
  3941. roi=roi,
  3942. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3943. )
  3944. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3945. if objects_detected:
  3946. # Objects detected - pause the print!
  3947. logger.warning(
  3948. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3949. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3950. )
  3951. pause_client = printer_manager.get_client(printer_id)
  3952. if pause_client:
  3953. pause_client.pause_print()
  3954. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3955. # Snapshot while the light's still on — restoring it first
  3956. # would leave the notification with a dark photo.
  3957. try:
  3958. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3959. except Exception as snap_err:
  3960. logger.warning(
  3961. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3962. )
  3963. finally:
  3964. # Restore chamber light to original state as soon as the
  3965. # camera is done with it, whatever happened above.
  3966. if light_was_off and client:
  3967. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3968. try:
  3969. client.set_chamber_light(False)
  3970. except Exception as light_err:
  3971. logger.warning(
  3972. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3973. printer_id,
  3974. light_err,
  3975. )
  3976. if objects_detected:
  3977. # Send notification about plate not empty
  3978. await ws_manager.broadcast(
  3979. {
  3980. "type": "plate_not_empty",
  3981. "printer_id": printer_id,
  3982. "printer_name": printer.name,
  3983. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3984. }
  3985. )
  3986. # Also send push notification
  3987. try:
  3988. await notification_service.on_plate_not_empty(
  3989. printer_id=printer_id,
  3990. printer_name=printer.name,
  3991. db=db,
  3992. difference_percent=plate_result.difference_percent,
  3993. image_data=plate_photo_data,
  3994. )
  3995. except Exception as notif_err:
  3996. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3997. else:
  3998. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3999. except Exception as plate_err:
  4000. # Don't block print on plate detection errors
  4001. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  4002. if not printer:
  4003. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4004. if not notification_sent:
  4005. await _send_print_start_notification(printer_id, data, logger=logger)
  4006. return
  4007. if not printer.auto_archive:
  4008. # auto-archive disabled — check if there's an expected print (dispatched
  4009. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4010. # If so, fall through to the expected-print handling below so the archive
  4011. # is tracked in _active_prints and usage tracking works at completion.
  4012. _fn = data.get("filename", "")
  4013. _sn = data.get("subtask_name", "")
  4014. _check_keys: list[tuple[int, str]] = []
  4015. if _sn:
  4016. _check_keys += [
  4017. (printer_id, _sn),
  4018. (printer_id, f"{_sn}.3mf"),
  4019. (printer_id, f"{_sn}.gcode.3mf"),
  4020. ]
  4021. if _fn:
  4022. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4023. _check_keys.append((printer_id, _base_fn))
  4024. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4025. _check_keys += [
  4026. (printer_id, _no_archive_base),
  4027. (printer_id, f"{_no_archive_base}.3mf"),
  4028. ]
  4029. _has_expected = any(k in _expected_prints for k in _check_keys)
  4030. if not _has_expected:
  4031. # No expected print — truly external print (started from slicer/touchscreen)
  4032. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4033. if not notification_sent:
  4034. _no_archive_creator: int | None = None
  4035. for _key in _check_keys:
  4036. _expected_prints.pop(_key, None)
  4037. _expected_print_registered_at.pop(_key, None)
  4038. popped_creator = _expected_print_creators.pop(_key, None)
  4039. if _no_archive_creator is None:
  4040. _no_archive_creator = popped_creator
  4041. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4042. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4043. return
  4044. else:
  4045. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4046. # Get the filename and subtask_name
  4047. filename = data.get("filename", "")
  4048. subtask_name = data.get("subtask_name", "")
  4049. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4050. # present, it lets us match an archive across a backend restart (#972):
  4051. # same id → same print → resume the existing row instead of cancelling
  4052. # it and recreating from scratch (which loses started_at). Treat "0"
  4053. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4054. raw_mqtt = data.get("raw_data") or {}
  4055. subtask_id = raw_mqtt.get("subtask_id")
  4056. if subtask_id is not None:
  4057. subtask_id = str(subtask_id).strip()
  4058. if subtask_id in ("", "0"):
  4059. subtask_id = None
  4060. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4061. # Skip the printer's own jobs — a calibration run is not a user's print.
  4062. # See is_internal_printer_job for what counts and why both fields are
  4063. # tested; the pressure-advance line reports as a subtask name with no
  4064. # /usr/ path, which the old prefix-only test here missed entirely.
  4065. #
  4066. # No notification either. The event describes the printer calibrating
  4067. # itself, so "Print started" is as wrong as the archive was, and the
  4068. # matching completion is suppressed in on_print_complete for the same
  4069. # reason.
  4070. if is_internal_printer_job(filename, subtask_name):
  4071. logger.info(
  4072. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4073. filename,
  4074. subtask_name,
  4075. )
  4076. return
  4077. if not filename and not subtask_name:
  4078. # Send notification without archive data (no filename)
  4079. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4080. if not notification_sent:
  4081. await _send_print_start_notification(printer_id, data, logger=logger)
  4082. return
  4083. # Check if this is an expected print from reprint/scheduled
  4084. # Build list of possible keys to check
  4085. expected_keys = []
  4086. if subtask_name:
  4087. expected_keys.append((printer_id, subtask_name))
  4088. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  4089. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4090. if filename:
  4091. fname = filename.split("/")[-1] if "/" in filename else filename
  4092. expected_keys.append((printer_id, fname))
  4093. # Strip extensions to match
  4094. base = fname.replace(".gcode", "").replace(".3mf", "")
  4095. expected_keys.append((printer_id, base))
  4096. expected_keys.append((printer_id, f"{base}.3mf"))
  4097. expected_archive_id = None
  4098. for key in expected_keys:
  4099. expected_archive_id = _expected_prints.pop(key, None)
  4100. _expected_print_registered_at.pop(key, None)
  4101. if expected_archive_id:
  4102. # Clean up other possible keys for this print
  4103. for other_key in expected_keys:
  4104. _expected_prints.pop(other_key, None)
  4105. _expected_print_registered_at.pop(other_key, None)
  4106. break
  4107. if expected_archive_id:
  4108. # This is a reprint/scheduled print - use existing archive, don't create new one
  4109. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4110. from backend.app.models.archive import PrintArchive
  4111. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4112. archive = result.scalar_one_or_none()
  4113. # Deleted after this handler loaded it (the plate check waits
  4114. # seconds) but before the route forgot the expected print: the
  4115. # archive the route kept or deleted is left as the route left it.
  4116. if archive and await _printer_gone(db, printer_id):
  4117. logger.info(
  4118. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4119. )
  4120. await forget_printer(printer_id)
  4121. return
  4122. if archive:
  4123. # As it was before this adoption: put back if the printer turns
  4124. # out to have been deleted while it was adopted (below).
  4125. before_adoption = {
  4126. attr.columns[0].name: getattr(archive, attr.key)
  4127. for attr in sa_inspect(PrintArchive).column_attrs
  4128. if attr.key != "id"
  4129. }
  4130. # Update archive status to printing
  4131. archive.status = "printing"
  4132. archive.started_at = datetime.now(timezone.utc)
  4133. # The previous run's outcome is not this one's: a reprint that
  4134. # completes must not keep showing why the last one failed.
  4135. archive.failure_reason = None
  4136. archive.completed_at = None
  4137. # The previous run's answer is still on this row and the
  4138. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4139. # so without a reset the second run inherits the first run's
  4140. # verdict: no prompt at all, and a green "good" badge on a run
  4141. # nobody ever judged.
  4142. if archive.confirm_requested:
  4143. archive.user_verdict = None
  4144. archive.user_verdict_source = None
  4145. archive.user_verdict_at = None
  4146. archive.confirm_token = None
  4147. archive.confirm_token_used_at = None
  4148. # Reprint of an archive reuses the source row. Without resetting
  4149. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4150. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4151. # extracts the *original* print's last frame, which then ships in
  4152. # the completion notification (#1707). Clear the path so the
  4153. # scanner runs fresh; also unlink the old video file so reprints
  4154. # don't accumulate orphans in the archive directory. Photos list
  4155. # is left alone — accumulating one finish photo per run is fine.
  4156. # The print-start baseline (#2704) is stale for the same reason:
  4157. # it describes the printer before the previous run. The capture
  4158. # below overwrites it, but clear it here too so an early failure
  4159. # can't leave the scan diffing against the wrong snapshot.
  4160. #
  4161. # Unlinked only when it is the same plate printing again. Every
  4162. # plate of a Send All shares this archive, and the video on it
  4163. # can be the only copy of another plate's run -- the printer's
  4164. # was deleted once it attached (#3275). That one is left in the
  4165. # archive directory, which goes with the archive. A video whose
  4166. # plate is not on record (attached by hand, or before the
  4167. # column existed) is kept too: nothing tells it apart from
  4168. # another plate's, and keeping costs one file where deleting
  4169. # can cost the only copy.
  4170. archive.timelapse_baseline = None
  4171. stale_timelapse_relpath = archive.timelapse_path
  4172. stale_timelapse_plate_id = archive.timelapse_plate_id
  4173. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4174. if stale_timelapse_relpath:
  4175. archive.timelapse_path = None
  4176. archive.timelapse_plate_id = None
  4177. if stale_timelapse_relpath and stale_timelapse_plate_id != starting_plate_id:
  4178. logger.info(
  4179. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4180. stale_timelapse_relpath,
  4181. stale_timelapse_plate_id,
  4182. expected_archive_id,
  4183. starting_plate_id,
  4184. )
  4185. # The video is deleted once the adoption stands (below).
  4186. delete_stale_video = bool(stale_timelapse_relpath) and stale_timelapse_plate_id == starting_plate_id
  4187. # Persist a restart-stable id so a later restart resumes this
  4188. # archive by subtask_id instead of name-matching + duplicating
  4189. # it (#1485). The printer often hasn't echoed subtask_id back
  4190. # this soon after dispatch, so fall back to the id Bambuddy
  4191. # minted when it sent the print command. Scoped to this
  4192. # expected-print branch on purpose: an expected match means
  4193. # Bambuddy dispatched this exact print in this process, so the
  4194. # client's last-dispatch id genuinely belongs to it — using it
  4195. # for an externally-started print could mis-tag the archive.
  4196. effective_subtask_id = subtask_id
  4197. if not effective_subtask_id:
  4198. _client = printer_manager.get_client(printer_id)
  4199. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4200. if _dispatched:
  4201. effective_subtask_id = str(_dispatched).strip() or None
  4202. # Update on first-set OR on reprint (the queue dispatcher mints
  4203. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4204. # the rewrite for reprints leaves the archive holding the FIRST
  4205. # run's id; if MQTT then reconnects mid-print, the reconciler
  4206. # (#1542) compares the stale stored id against the printer's
  4207. # live id, sees a mismatch, and synthesises a bogus PRINT
  4208. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4209. # in #1807. Inequality check preserves the noop-on-stable-push
  4210. # behaviour the earlier `not archive.subtask_id` guard provided.
  4211. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4212. archive.subtask_id = effective_subtask_id
  4213. # #1403 follow-up: VP-queue archives are created with
  4214. # printer_id=None at queue-add time (we don't know which
  4215. # printer will run the job yet). When the print actually
  4216. # starts on a specific printer the expected-archive lookup
  4217. # used to skip this assignment, leaving printer_id=None
  4218. # forever — which then disables the "Scan for timelapse"
  4219. # button in ArchivesPage (gated on !archive.printer_id).
  4220. if archive.printer_id != printer_id:
  4221. archive.printer_id = printer_id
  4222. adopting_id = archive.id # a rollback expires the object
  4223. try:
  4224. await db.commit()
  4225. except (IntegrityError, StaleDataError):
  4226. # The archive stays unchanged, or is gone: "delete archives"
  4227. # removed the row under the adoption, which then matched no
  4228. # row (StaleDataError) rather than being refused.
  4229. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4230. return
  4231. raise
  4232. # The printer can be deleted between the check above and this
  4233. # commit (the route's transaction lasts seconds), and the commit
  4234. # then adopted the archive anyway: status, verdict and timelapse
  4235. # changed, and the deleted printer's id written on a row the
  4236. # route had detached or never touched. Undo the adoption.
  4237. if await _printer_gone(db, printer_id):
  4238. logger.info(
  4239. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4240. printer_id,
  4241. archive.id,
  4242. )
  4243. # Everything as before this adoption. The printer it had
  4244. # then stays, unless it was the deleted one: the route
  4245. # detached that row (kept) or deleted it (no row matches).
  4246. previous_printer = before_adoption["printer_id"]
  4247. await db.execute(
  4248. update(PrintArchive)
  4249. .where(PrintArchive.id == archive.id)
  4250. .values(
  4251. {
  4252. **before_adoption,
  4253. "printer_id": None if previous_printer == printer_id else previous_printer,
  4254. }
  4255. )
  4256. )
  4257. await db.commit()
  4258. await forget_printer(printer_id)
  4259. return
  4260. if delete_stale_video and stale_timelapse_relpath:
  4261. try:
  4262. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4263. if stale_path.is_file():
  4264. stale_path.unlink()
  4265. logger.info(
  4266. "Deleted stale timelapse %s on reprint of archive %s",
  4267. stale_timelapse_relpath,
  4268. expected_archive_id,
  4269. )
  4270. except OSError as e:
  4271. logger.warning(
  4272. "Failed to delete stale timelapse %s on reprint: %s",
  4273. stale_timelapse_relpath,
  4274. e,
  4275. )
  4276. # Track as active print
  4277. _active_prints[(printer_id, archive.filename)] = archive.id
  4278. if subtask_name:
  4279. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4280. # Start timelapse session if external camera is enabled (#1353).
  4281. # Queue / VP-dispatched prints land here in the expected-archive
  4282. # branch and used to skip start_session entirely — frames were
  4283. # never captured and the post-print stitch silently returned None.
  4284. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4285. # Inject ams_mapping into usage tracker session — the session was created
  4286. # before expected-print promotion, so it may have ams_mapping=None when
  4287. # the MQTT request topic subscription failed (common on P1S/A1).
  4288. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4289. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4290. if _stored_map or _stored_plate_id is not None:
  4291. try:
  4292. from backend.app.services.usage_tracker import _active_sessions
  4293. _ut_session = _active_sessions.get(printer_id)
  4294. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4295. _ut_session.ams_mapping = _stored_map
  4296. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4297. # plate_id injection covers direct-Print of plate N of a multi-plate
  4298. # 3MF — queue prints already capture it via the on_print_start queue
  4299. # lookup, but direct-Print never goes through the queue (#1697).
  4300. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4301. _ut_session.plate_id = _stored_plate_id
  4302. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4303. except Exception:
  4304. pass
  4305. # Set up energy tracking (#941: persist start on archive row)
  4306. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4307. await ws_manager.send_archive_updated(
  4308. {
  4309. "id": archive.id,
  4310. "status": "printing",
  4311. }
  4312. )
  4313. # Send notification with archive data (reprint/scheduled)
  4314. if not notification_sent:
  4315. # Use archive's created_by_id; fall back to the creator registered via
  4316. # register_expected_print (handles library-file-based queue items where
  4317. # the freshly-created archive has no created_by_id yet).
  4318. # Pop ALL matching keys so no stale entries remain in the dict.
  4319. fallback_creator = None
  4320. for key in expected_keys:
  4321. popped = _expected_print_creators.pop(key, None)
  4322. if fallback_creator is None:
  4323. fallback_creator = popped
  4324. archive_data = {
  4325. "print_time_seconds": archive.print_time_seconds,
  4326. "created_by_id": archive.created_by_id or fallback_creator,
  4327. }
  4328. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4329. # Extract printable objects from the archived 3MF file
  4330. _load_objects_from_archive(archive, printer_id, logger)
  4331. # Store Spoolman tracking data for per-filament usage reporting
  4332. try:
  4333. await _store_spoolman_print_data(
  4334. printer_id,
  4335. archive.id,
  4336. archive.file_path,
  4337. db,
  4338. printer_manager,
  4339. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4340. plate_id=_get_start_plate_id(archive.id),
  4341. )
  4342. except Exception as e:
  4343. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4344. # Price the print from its spools now rather than only at completion (#3261)
  4345. _schedule_archive_cost_estimate(
  4346. printer_id,
  4347. archive.id,
  4348. printer_manager,
  4349. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4350. plate_id=_get_start_plate_id(archive.id),
  4351. session_factory=async_session,
  4352. )
  4353. # Capture timelapse file baseline for snapshot-diff on completion
  4354. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4355. # hit this branch — without the baseline the completion-time scan
  4356. # falls into its "take baseline now" fallback, which snapshots
  4357. # AFTER the new MP4 already exists and never matches a diff
  4358. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4359. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4360. await _forget_if_printer_gone(printer_id)
  4361. return # Skip creating a new archive
  4362. # The archive was deleted after the job was queued.
  4363. if not printer.auto_archive:
  4364. # Only the expected print brought a printer that does not
  4365. # archive this far; with it gone, nothing is archived.
  4366. return
  4367. # Otherwise archive the print anew rather than drop it, so it still
  4368. # gets its notification, usage tracking and history.
  4369. logger.warning(
  4370. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4371. expected_archive_id,
  4372. printer_id,
  4373. )
  4374. # Check if there's already a "printing" archive for this printer/file
  4375. # This prevents duplicates when backend restarts during an active print
  4376. from backend.app.models.archive import PrintArchive
  4377. existing_archive: PrintArchive | None = None
  4378. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4379. # across a backend restart for the same print, so this is the most
  4380. # reliable way to reattach. We also accept a previously stale-cancelled
  4381. # archive here so users upgrading mid-print get revived when the row
  4382. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4383. if subtask_id:
  4384. by_id = await db.execute(
  4385. select(PrintArchive)
  4386. .where(PrintArchive.printer_id == printer_id)
  4387. .where(PrintArchive.subtask_id == subtask_id)
  4388. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4389. .order_by(PrintArchive.created_at.desc())
  4390. .limit(1)
  4391. )
  4392. candidate = by_id.scalar_one_or_none()
  4393. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4394. existing_archive = candidate
  4395. # Fallback match: name-based lookup. Kept as-is for prints whose
  4396. # subtask_id is missing ("0" / local / non-cloud prints).
  4397. if existing_archive is None:
  4398. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4399. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4400. # A print started from the printer's screen names its file in full,
  4401. # so the forms above double its extension. The file itself is the
  4402. # one exact match, and nothing looser is added (#3009).
  4403. if _subtask_is_the_file(subtask_name, filename):
  4404. archive_filenames.append(subtask_name)
  4405. existing = await db.execute(
  4406. select(PrintArchive)
  4407. .where(PrintArchive.printer_id == printer_id)
  4408. .where(PrintArchive.status == "printing")
  4409. .where(
  4410. or_(
  4411. PrintArchive.print_name == check_name,
  4412. PrintArchive.filename.in_(archive_filenames),
  4413. )
  4414. )
  4415. .order_by(PrintArchive.created_at.desc())
  4416. .limit(1)
  4417. )
  4418. existing_archive = existing.scalar_one_or_none()
  4419. if existing_archive:
  4420. # subtask_id match → always resume, regardless of age. Same print,
  4421. # just a backend restart. Revive if it was previously stale-cancelled.
  4422. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4423. if subtask_match:
  4424. if existing_archive.status == "cancelled":
  4425. logger.warning(
  4426. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4427. existing_archive.id,
  4428. subtask_id,
  4429. )
  4430. existing_archive.status = "printing"
  4431. existing_archive.failure_reason = None
  4432. await db.commit()
  4433. else:
  4434. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4435. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4436. if existing_archive.energy_start_kwh is None:
  4437. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4438. if not notification_sent:
  4439. archive_data = {
  4440. "print_time_seconds": existing_archive.print_time_seconds,
  4441. "created_by_id": existing_archive.created_by_id,
  4442. }
  4443. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4444. _load_objects_from_archive(existing_archive, printer_id, logger)
  4445. return
  4446. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4447. # stale from the printer's *current* progress, not wall-clock age.
  4448. # A genuinely long print used to trip a blind 4h cutoff and have its
  4449. # live archive cancelled + duplicated on every backend restart
  4450. # (#1485). If the printer reports real progress, this name-matched
  4451. # 'printing' archive IS that ongoing print — resume it whatever its
  4452. # age. Only treat it as a stale leftover when the printer clearly
  4453. # shows a different, freshly-started print: near-0% progress on an
  4454. # archive far too old to still be at 0%. Unknown progress (printer
  4455. # not connected) never cancels — resuming is the safe default.
  4456. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4457. live_status = printer_manager.get_status(printer_id)
  4458. live_progress = getattr(live_status, "progress", None) if live_status else None
  4459. looks_stale = (
  4460. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4461. )
  4462. if looks_stale:
  4463. logger.warning(
  4464. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4465. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4466. )
  4467. existing_archive.status = "cancelled"
  4468. # Canonical key, not a sentence (issue #2974). "No status update
  4469. # received" is what both stale paths actually observed; which of
  4470. # the two it was is already carried by ``status`` -- cancelled
  4471. # here, the reconciled outcome at the reconnect site -- so one
  4472. # key loses no information and gives the Statistics breakdown a
  4473. # single bucket instead of two untranslatable prose strings.
  4474. existing_archive.failure_reason = "noStatusUpdate"
  4475. await db.commit()
  4476. # Fall through to create new archive (don't return)
  4477. else:
  4478. logger.info(
  4479. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4480. )
  4481. # Track this as the active print
  4482. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4483. # Attach subtask_id retroactively so future restarts can resume.
  4484. # Compare for inequality (not "is empty") to also pick up reprint
  4485. # dispatches that mint a fresh id — see #1807 for the bogus
  4486. # "Print Stopped" the strict-empty guard caused on reconnect.
  4487. if subtask_id and existing_archive.subtask_id != subtask_id:
  4488. existing_archive.subtask_id = subtask_id
  4489. await db.commit()
  4490. # Also set up energy tracking if not already tracked (#941: persisted column)
  4491. if existing_archive.energy_start_kwh is None:
  4492. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4493. # Send notification with archive data (existing archive)
  4494. if not notification_sent:
  4495. archive_data = {
  4496. "print_time_seconds": existing_archive.print_time_seconds,
  4497. "created_by_id": existing_archive.created_by_id,
  4498. }
  4499. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4500. # Extract printable objects from the archived 3MF file
  4501. _load_objects_from_archive(existing_archive, printer_id, logger)
  4502. return
  4503. # Build list of possible 3MF filenames to try
  4504. possible_names = []
  4505. # Bambu printers typically store files as "Name.gcode.3mf"
  4506. # The subtask_name is usually the best source for the filename
  4507. if subtask_name:
  4508. if _subtask_is_the_file(subtask_name, filename):
  4509. # A print started from the printer's own screen reports the
  4510. # file's full name, extension included. That is the file, so
  4511. # no extension is appended to it (#3009).
  4512. possible_names.append(subtask_name)
  4513. else:
  4514. # Try common Bambu naming patterns
  4515. possible_names.append(f"{subtask_name}.gcode.3mf")
  4516. possible_names.append(f"{subtask_name}.3mf")
  4517. # Try original filename with .3mf extension
  4518. if filename:
  4519. # Extract just the filename part, not the full path
  4520. fname = filename.split("/")[-1] if "/" in filename else filename
  4521. if fname.endswith(".3mf"):
  4522. possible_names.append(fname)
  4523. elif fname.endswith(".gcode"):
  4524. base = fname.rsplit(".", 1)[0]
  4525. possible_names.append(f"{base}.gcode.3mf")
  4526. possible_names.append(f"{base}.3mf")
  4527. else:
  4528. possible_names.append(f"{fname}.gcode.3mf")
  4529. possible_names.append(f"{fname}.3mf")
  4530. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4531. space_variants = []
  4532. for name in possible_names:
  4533. if " " in name:
  4534. space_variants.append(name.replace(" ", "_"))
  4535. possible_names.extend(space_variants)
  4536. # Remove duplicates while preserving order
  4537. seen = set()
  4538. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4539. logger.info("Trying filenames: %s", possible_names)
  4540. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4541. # here means none of the expected-/existing-archive write branches ran
  4542. # (they all return earlier) — only SELECTs have executed on this path, so
  4543. # this commit persists nothing; it ends the read transaction so the
  4544. # connection returns to the pool during the download. That download tries
  4545. # up to five remote paths per candidate filename with retry/backoff and
  4546. # can run for minutes under FTP contention; holding the session across it
  4547. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4548. # work runs during the download — the new-archive writes below re-acquire
  4549. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4550. await db.commit()
  4551. # Try to find and download the 3MF file
  4552. temp_path = None
  4553. downloaded_filename = None
  4554. # Cache check: cover endpoint may have already pulled this 3MF during
  4555. # the print (frontend opens the card and shows the thumbnail) — reuse
  4556. # that file instead of re-downloading 36MB over the same FTP link that
  4557. # just served it (#972). The cache keys on a normalized filename so
  4558. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4559. for try_filename in possible_names:
  4560. if not try_filename.endswith(".3mf"):
  4561. continue
  4562. cached = get_cached_3mf(printer_id, try_filename)
  4563. if cached:
  4564. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4565. temp_path = cached
  4566. downloaded_filename = try_filename
  4567. break
  4568. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4569. # H2-series and P2S the answer is routinely no — the file stays on
  4570. # internal eMMC and port 990 only ever serves external storage — and
  4571. # then the whole sweep below (six filenames x five directories x four
  4572. # retries, then the directory walk) is ~110 connections that cannot
  4573. # succeed. Skip it and say why (#2780).
  4574. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4575. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4576. # running rather than because the file is somewhere unreachable. The
  4577. # distinction is the whole of #2957: one is permanent, the other clears
  4578. # in minutes with the file still sitting on the printer.
  4579. blocked_by_ftps_cooloff = False
  4580. # Set when a probe reached the printer and still came back without the
  4581. # file -- a timeout mid-transfer, a refused connection, anything that is
  4582. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4583. # caught by name below, so a file that genuinely is not on the card
  4584. # leaves this False and schedules nothing. Anything else means the
  4585. # transfer, not the file, is what failed, and that does not last (#3063).
  4586. ftp_transfer_failed = False
  4587. # The print's name, for a fallback archive whose `subtask_name` the
  4588. # plate guard below had to disown. Display only, and deliberately kept
  4589. # apart from `subtask_name`: that variable is what every file lookup
  4590. # here is built from, and once a name has been shown to fetch another
  4591. # plate's 3MF it must not key `_active_prints` either, or the cover
  4592. # endpoint hands the same contradicted file to
  4593. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4594. display_name_after_plate_reject: str | None = None
  4595. # Get FTP retry settings
  4596. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4597. # ...but "the printer put it on eMMC" is where it went, not whether we
  4598. # can read it. An H2D with a card in mirrors the job to /cache and
  4599. # serves it happily, and skipping on the URL alone cost that reporter
  4600. # every archive for two days (#2856). So ask the printer instead of
  4601. # guessing: the dispatch named the exact file, which is one connection
  4602. # walking five paths rather than the sweep's ~110. Only when the probe
  4603. # comes back empty does the verdict's reason stand.
  4604. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4605. if ftps_handshake_blocked(printer.ip_address):
  4606. # Deliberately NOT recorded as a cool-off give-up. This branch
  4607. # only runs on an unreachable verdict, and that verdict is the
  4608. # honest, permanent reason the archive is empty — the probe was
  4609. # a long shot on top of it. Blaming the cool-off here would
  4610. # schedule a retry for a file sitting on internal eMMC, which is
  4611. # the sweep #2780 removed (#2957).
  4612. logger.debug(
  4613. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4614. storage.probe_filename,
  4615. printer_id,
  4616. )
  4617. else:
  4618. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4619. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4620. try:
  4621. probe_hit = await download_file_try_paths_async(
  4622. printer.ip_address,
  4623. printer.access_code,
  4624. ftp_probe_paths(storage.probe_filename),
  4625. probe_path,
  4626. socket_timeout=ftp_timeout,
  4627. printer_model=printer.model,
  4628. )
  4629. except Exception as e:
  4630. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4631. probe_hit = False
  4632. if probe_hit:
  4633. downloaded_filename = storage.probe_filename
  4634. temp_path = probe_path
  4635. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4636. # Naming the path, not just the file: a printer that keeps
  4637. # uploads around for weeks can serve a same-named copy of an
  4638. # earlier slice, and without the directory in the log that
  4639. # mismatch is invisible rather than merely rare (#1820).
  4640. logger.info(
  4641. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4642. downloaded_filename,
  4643. probe_hit,
  4644. printer_id,
  4645. storage.reason,
  4646. )
  4647. if not storage.reachable and not downloaded_filename:
  4648. # Same opening words whether or not a probe ran, because that is
  4649. # the phrase support asks people to grep for — only the tail says
  4650. # which of the two happened.
  4651. logger.info(
  4652. "Skipping the 3MF lookup for printer %s: %s — %s",
  4653. printer_id,
  4654. storage.reason,
  4655. "no copy of it on external storage either"
  4656. if storage.probe_filename
  4657. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4658. )
  4659. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4660. if not try_filename.endswith(".3mf"):
  4661. continue
  4662. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4663. # printers, so try it first — deferring it to last cost #972's reporter
  4664. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4665. # landing on the path that actually had the file.
  4666. remote_paths = [
  4667. f"/{try_filename}",
  4668. f"/cache/{try_filename}",
  4669. f"/model/{try_filename}",
  4670. f"/data/{try_filename}",
  4671. f"/data/Metadata/{try_filename}",
  4672. ]
  4673. temp_path = app_settings.archive_dir / "temp" / try_filename
  4674. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4675. for remote_path in remote_paths:
  4676. if ftps_handshake_blocked(printer.ip_address):
  4677. # The printer's FTPS service is not completing a TLS
  4678. # handshake, so it has no path we could reach — walking the
  4679. # remaining candidates only re-runs the same failure
  4680. # (#2780). Fall through to the no-3MF archive now.
  4681. #
  4682. # Remember *why*, though. This is the one give-up that is
  4683. # temporary: the cool-off clears in minutes and the file was
  4684. # on the printer the whole time. The fallback archive is
  4685. # stamped with it so a retry can be scheduled, and so the
  4686. # Archives banner stops blaming storage (#2957).
  4687. blocked_by_ftps_cooloff = True
  4688. logger.warning(
  4689. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4690. printer_id,
  4691. )
  4692. break
  4693. logger.debug("Trying FTP download: %s", remote_path)
  4694. try:
  4695. if ftp_retry_enabled:
  4696. downloaded = await with_ftp_retry(
  4697. download_file_async,
  4698. printer.ip_address,
  4699. printer.access_code,
  4700. remote_path,
  4701. temp_path,
  4702. timeout=ftp_timeout,
  4703. socket_timeout=ftp_timeout,
  4704. printer_model=printer.model,
  4705. max_retries=ftp_retry_count,
  4706. retry_delay=ftp_retry_delay,
  4707. operation_name=f"Download 3MF from {remote_path}",
  4708. cooloff_ip=printer.ip_address,
  4709. non_retry_exceptions=(FileNotOnPrinterError,),
  4710. )
  4711. else:
  4712. downloaded = await download_file_async(
  4713. printer.ip_address,
  4714. printer.access_code,
  4715. remote_path,
  4716. temp_path,
  4717. timeout=ftp_timeout,
  4718. socket_timeout=ftp_timeout,
  4719. printer_model=printer.model,
  4720. )
  4721. if downloaded:
  4722. downloaded_filename = try_filename
  4723. logger.info("Downloaded: %s", remote_path)
  4724. # Populate shared cache so the cover endpoint (if it
  4725. # runs next) doesn't refetch the same 36MB over FTP.
  4726. cache_3mf_download(printer_id, try_filename, temp_path)
  4727. break
  4728. # with_ftp_retry returns None once it has spent its budget,
  4729. # and download_file_async returns False on a timeout, so an
  4730. # exhausted transfer arrives here rather than as an
  4731. # exception (#3063).
  4732. ftp_transfer_failed = True
  4733. except FileNotOnPrinterError:
  4734. # 550 — file isn't at this path. Advance to next candidate
  4735. # without burning the retry budget.
  4736. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4737. except Exception as e:
  4738. ftp_transfer_failed = True
  4739. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4740. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4741. break
  4742. # If still not found, try listing directories to find matching file
  4743. # Different printer models use different directory structures. Skipped
  4744. # when the printer's FTPS handshake is failing — the directory walk is
  4745. # five more connections that cannot get further than the download did.
  4746. if (
  4747. not downloaded_filename
  4748. and storage.reachable
  4749. and (filename or subtask_name)
  4750. and not ftps_handshake_blocked(printer.ip_address)
  4751. ):
  4752. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4753. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4754. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4755. for search_dir in search_dirs:
  4756. if downloaded_filename:
  4757. break
  4758. try:
  4759. dir_files = await list_files_async(
  4760. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4761. )
  4762. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4763. if threemf_files:
  4764. logger.info(
  4765. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4766. )
  4767. for f in dir_files:
  4768. if f.get("is_directory"):
  4769. continue
  4770. fname = f.get("name", "")
  4771. # Normalize both for comparison (spaces and underscores are equivalent)
  4772. fname_normalized = fname.lower().replace(" ", "_")
  4773. search_normalized = search_term.replace(" ", "_")
  4774. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4775. logger.info("Found matching file in %s: %s", search_dir, fname)
  4776. temp_path = app_settings.archive_dir / "temp" / fname
  4777. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4778. remote_full_path = posixpath.join(search_dir, fname)
  4779. if ftp_retry_enabled:
  4780. downloaded = await with_ftp_retry(
  4781. download_file_async,
  4782. printer.ip_address,
  4783. printer.access_code,
  4784. remote_full_path,
  4785. temp_path,
  4786. timeout=ftp_timeout,
  4787. socket_timeout=ftp_timeout,
  4788. printer_model=printer.model,
  4789. max_retries=ftp_retry_count,
  4790. retry_delay=ftp_retry_delay,
  4791. operation_name=f"Download 3MF from {remote_full_path}",
  4792. cooloff_ip=printer.ip_address,
  4793. )
  4794. else:
  4795. downloaded = await download_file_async(
  4796. printer.ip_address,
  4797. printer.access_code,
  4798. remote_full_path,
  4799. temp_path,
  4800. timeout=ftp_timeout,
  4801. socket_timeout=ftp_timeout,
  4802. printer_model=printer.model,
  4803. )
  4804. if downloaded:
  4805. downloaded_filename = fname
  4806. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4807. cache_3mf_download(printer_id, fname, temp_path)
  4808. break
  4809. # The listing named the file, so it is on the card;
  4810. # only the transfer failed (#3063).
  4811. ftp_transfer_failed = True
  4812. except Exception as e:
  4813. logger.debug("Failed to list %s: %s", search_dir, e)
  4814. # Validate the downloaded 3MF actually matches the plate that's running
  4815. # (#1204): subtask_name lags across consecutive plates of the same model,
  4816. # so the first FTP candidate (built from subtask_name) can land on the
  4817. # previous plate's still-resident upload. Cross-check the slice_info
  4818. # plate index against the plate parsed from gcode_file (always fresh —
  4819. # it's the field whose change triggered this callback).
  4820. if downloaded_filename and temp_path:
  4821. expected_plate = parse_plate_id(filename)
  4822. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4823. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4824. logger.warning(
  4825. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4826. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4827. downloaded_filename,
  4828. actual_plate,
  4829. expected_plate,
  4830. subtask_name,
  4831. )
  4832. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4833. retry_succeeded = False
  4834. if corrected_subtask and corrected_subtask != subtask_name:
  4835. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4836. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4837. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4838. for remote_path in (
  4839. f"/{try_filename}",
  4840. f"/cache/{try_filename}",
  4841. f"/model/{try_filename}",
  4842. f"/data/{try_filename}",
  4843. f"/data/Metadata/{try_filename}",
  4844. ):
  4845. try:
  4846. if ftp_retry_enabled:
  4847. downloaded = await with_ftp_retry(
  4848. download_file_async,
  4849. printer.ip_address,
  4850. printer.access_code,
  4851. remote_path,
  4852. retry_temp_path,
  4853. timeout=ftp_timeout,
  4854. socket_timeout=ftp_timeout,
  4855. printer_model=printer.model,
  4856. max_retries=ftp_retry_count,
  4857. retry_delay=ftp_retry_delay,
  4858. operation_name=f"Re-download 3MF from {remote_path}",
  4859. cooloff_ip=printer.ip_address,
  4860. non_retry_exceptions=(FileNotOnPrinterError,),
  4861. )
  4862. else:
  4863. downloaded = await download_file_async(
  4864. printer.ip_address,
  4865. printer.access_code,
  4866. remote_path,
  4867. retry_temp_path,
  4868. timeout=ftp_timeout,
  4869. socket_timeout=ftp_timeout,
  4870. printer_model=printer.model,
  4871. )
  4872. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4873. logger.info(
  4874. "[CALLBACK] Re-download succeeded with corrected name %s "
  4875. "(plate %s) — replacing wrong file",
  4876. try_filename,
  4877. expected_plate,
  4878. )
  4879. try:
  4880. temp_path.unlink(missing_ok=True)
  4881. except OSError:
  4882. pass
  4883. temp_path = retry_temp_path
  4884. downloaded_filename = try_filename
  4885. subtask_name = corrected_subtask
  4886. cache_3mf_download(printer_id, try_filename, temp_path)
  4887. retry_succeeded = True
  4888. break
  4889. elif downloaded:
  4890. # Wrong plate again — discard and keep trying
  4891. try:
  4892. retry_temp_path.unlink(missing_ok=True)
  4893. except OSError:
  4894. pass
  4895. except FileNotOnPrinterError:
  4896. continue
  4897. except Exception as e:
  4898. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4899. if retry_succeeded:
  4900. break
  4901. # If the retry didn't find a matching file, drop the wrong 3MF
  4902. # so the no-3MF fallback below creates an archive whose name
  4903. # at least reflects the right plate.
  4904. if not retry_succeeded:
  4905. logger.warning(
  4906. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4907. expected_plate,
  4908. )
  4909. try:
  4910. temp_path.unlink(missing_ok=True)
  4911. except OSError:
  4912. pass
  4913. temp_path = None
  4914. downloaded_filename = None
  4915. # Whatever the sweep's transport did earlier, it is not why
  4916. # this archive ends up empty: a 3MF downloaded fine, it was
  4917. # just the wrong plate. Retrying would re-fetch that same
  4918. # contradicted file under the same stale names and hand it
  4919. # to _recover_fallback_archive, which checks that a
  4920. # candidate is a readable 3MF but not which plate it is --
  4921. # so the row would be filled in with another plate's
  4922. # filament and cost, the exact swap #2957 removed (#3063).
  4923. ftp_transfer_failed = False
  4924. # Disown the name for *lookups*: it has just been shown to
  4925. # fetch another plate's 3MF, and it keys `_active_prints`
  4926. # below, where the cover endpoint's own download of that
  4927. # same name would find this archive and fill it in with the
  4928. # file we are discarding here.
  4929. #
  4930. # Keep it for the *title*, which is a separate question.
  4931. # ``swap_plate_suffix`` returns None both for a name that
  4932. # carries no "- Plate N" / "_plate_N" suffix and for no
  4933. # name at all, and those are not the same situation: a name
  4934. # without a suffix holds no stale plate number to be wrong
  4935. # about. Blanking both uses at once dropped the project
  4936. # name too, and the row fell through to the gcode_file path
  4937. # titled "plate_1" though the real name was in hand.
  4938. # #1204's own premise is consecutive plates *of the same
  4939. # model*, so the project part is right either way (#3126).
  4940. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4941. subtask_name = corrected_subtask or ""
  4942. # Deleted while the 3MF was being fetched (that can take minutes): no
  4943. # archive, timelapse or tracking for a printer that will never report
  4944. # the print's end. forget_printer again: the download registered its
  4945. # 3MF cache entry after the delete cleared the id. (A delete committing
  4946. # while the archive is written is caught after its commit.)
  4947. if await _printer_gone(db, printer_id):
  4948. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  4949. await forget_printer(printer_id)
  4950. return
  4951. if not downloaded_filename or not temp_path:
  4952. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4953. # Create a fallback archive without 3MF data so the print is still tracked
  4954. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4955. try:
  4956. from backend.app.models.archive import PrintArchive
  4957. # Why the card is empty. The two temporary causes outrank the
  4958. # storage verdict because they say the sweep never got a fair
  4959. # answer: a cool-off skipped it at the transport, and a failed
  4960. # transfer reached the printer but never finished. Either way
  4961. # the file is still on the card, so reporting where the printer
  4962. # files its jobs would describe a setting that is not the
  4963. # problem (#2957, #3063).
  4964. if blocked_by_ftps_cooloff:
  4965. no_3mf_reason = REASON_FTPS_COOLOFF
  4966. elif storage.reachable and ftp_transfer_failed:
  4967. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4968. else:
  4969. no_3mf_reason = storage.reason
  4970. # Derive print name from subtask_name or filename. The
  4971. # plate guard's disowned name comes second: it is a real name
  4972. # for a real print, and only the gcode_file path is left
  4973. # otherwise -- which titles the row "plate_1" (#3126).
  4974. print_name = subtask_name or display_name_after_plate_reject or filename
  4975. if print_name:
  4976. # Clean up the name (remove extensions, path parts)
  4977. print_name = print_name.split("/")[-1]
  4978. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4979. else:
  4980. print_name = "Unknown Print"
  4981. # Recover estimated print time from MQTT (best-effort for notifications)
  4982. fallback_print_time = None
  4983. mqtt_remaining = data.get("remaining_time")
  4984. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4985. fallback_print_time = int(mqtt_remaining)
  4986. if fallback_print_time is None:
  4987. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4988. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4989. fallback_print_time = int(mc_remaining * 60)
  4990. # Best-effort filament metadata from MQTT — see
  4991. # _extract_filament_data_from_mqtt. Without this the fallback
  4992. # archive's filament fields stayed NULL even though the AMS
  4993. # state at print start was sitting right there in `data`.
  4994. # The slicer's ams_mapping (when present) narrows the result
  4995. # to slots actually used by the print (#1533).
  4996. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4997. # Create minimal archive entry
  4998. fallback_archive = PrintArchive(
  4999. printer_id=printer_id,
  5000. filename=filename or f"{print_name}.3mf",
  5001. file_path="", # Empty - no 3MF file available
  5002. file_size=0,
  5003. print_name=print_name,
  5004. print_time_seconds=fallback_print_time,
  5005. status="printing",
  5006. started_at=datetime.now(timezone.utc),
  5007. subtask_id=subtask_id,
  5008. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5009. filament_type=mqtt_filament_meta.get("filament_type"),
  5010. filament_color=mqtt_filament_meta.get("filament_color"),
  5011. extra_data={
  5012. "no_3mf_available": True,
  5013. # Why the card is empty, when we know -- see above. The
  5014. # banner reads this to stop telling H2/P2 owners to
  5015. # switch on a setting that is already on and would not
  5016. # have helped (#2780).
  5017. "no_3mf_reason": no_3mf_reason,
  5018. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5019. "_print_data": data,
  5020. },
  5021. )
  5022. db.add(fallback_archive)
  5023. try:
  5024. await db.commit()
  5025. except IntegrityError:
  5026. # Not "Failed to create fallback archive" below, and no
  5027. # start notification for a printer that is gone.
  5028. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5029. return
  5030. raise
  5031. await db.refresh(fallback_archive)
  5032. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5033. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5034. return
  5035. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5036. # Track as active print
  5037. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  5038. if filename:
  5039. _active_prints[(printer_id, filename)] = fallback_archive.id
  5040. if subtask_name:
  5041. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  5042. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  5043. # Record starting energy if smart plug available (#941: persisted column)
  5044. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5045. # Send WebSocket notification
  5046. await ws_manager.send_archive_created(
  5047. {
  5048. "id": fallback_archive.id,
  5049. "printer_id": fallback_archive.printer_id,
  5050. "filename": fallback_archive.filename,
  5051. "print_name": fallback_archive.print_name,
  5052. "status": fallback_archive.status,
  5053. }
  5054. )
  5055. # MQTT relay - publish archive created
  5056. try:
  5057. await mqtt_relay.on_archive_created(
  5058. archive_id=fallback_archive.id,
  5059. print_name=fallback_archive.print_name,
  5060. printer_name=printer.name,
  5061. status=fallback_archive.status,
  5062. )
  5063. except Exception:
  5064. pass # Don't fail if MQTT fails
  5065. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5066. try:
  5067. await _store_spoolman_print_data(
  5068. printer_id,
  5069. fallback_archive.id,
  5070. fallback_archive.file_path,
  5071. db,
  5072. printer_manager,
  5073. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5074. plate_id=_get_start_plate_id(fallback_archive.id),
  5075. )
  5076. except Exception as e:
  5077. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5078. # Both temporary give-ups are worth coming back for, and for
  5079. # the same reason: the file is on the printer and the last look
  5080. # failed at the transport rather than finding nothing. One waits
  5081. # out the handshake block (#2957), the other waits for the
  5082. # printer to stop being busy (#3063). Deliberately not scheduled
  5083. # for a storage verdict: a file on internal eMMC will not appear
  5084. # at any FTPS path however long we wait, and retrying it is
  5085. # exactly the sweep #2780 removed.
  5086. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5087. # `possible_names`, not the raw MQTT strings: it is the exact
  5088. # list this flow just tried, already stripped of any path
  5089. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5090. # some firmware) and deduped.
  5091. _schedule_fallback_3mf_retry(
  5092. printer_id=printer_id,
  5093. archive_id=fallback_archive.id,
  5094. filenames=list(possible_names),
  5095. reason=no_3mf_reason,
  5096. )
  5097. # Send notification without archive data (file not found)
  5098. if not notification_sent:
  5099. await _send_print_start_notification(printer_id, data, logger=logger)
  5100. # The same baseline the other two on_print_start branches take
  5101. # (#2704), and last for the same reason they are: it lists the
  5102. # printer's timelapse directory, so a slow card must not delay
  5103. # the _active_prints registration, the energy reading, the
  5104. # archive-created event or the start notification above it.
  5105. #
  5106. # This branch never took one, so every no-3MF archive reached
  5107. # completion with no baseline in memory and none on the row, and
  5108. # the completion scan fell into its "snapshot now" fallback --
  5109. # which runs after the printer has written the video, so the new
  5110. # file landed inside the baseline and no diff ever matched
  5111. # (#2957 follow-up).
  5112. #
  5113. # Skipped when the FTPS cool-off is what produced this fallback:
  5114. # the listing needs the same connection that just failed, so it
  5115. # could only record that the card was unreadable. The scan
  5116. # handles that case by refusing to choose between candidates.
  5117. if not blocked_by_ftps_cooloff:
  5118. await _capture_timelapse_baseline_at_start(
  5119. printer, printer_id, logger, archive_id=fallback_archive.id
  5120. )
  5121. await _forget_if_printer_gone(printer_id)
  5122. return
  5123. except Exception as e:
  5124. logger.error("Failed to create fallback archive: %s", e)
  5125. # Send notification without archive data (file not found)
  5126. if not notification_sent:
  5127. await _send_print_start_notification(printer_id, data, logger=logger)
  5128. return
  5129. try:
  5130. # Archive the file with status "printing"
  5131. service = ArchiveService(db)
  5132. try:
  5133. archive = await service.archive_print(
  5134. printer_id=printer_id,
  5135. source_file=temp_path,
  5136. print_data={**data, "status": "printing"},
  5137. subtask_id=subtask_id,
  5138. )
  5139. except IntegrityError:
  5140. # archive_print removed the folder it had copied the 3MF into.
  5141. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5142. return
  5143. raise
  5144. if archive:
  5145. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5146. # Set on the row rather than passed to archive_print, which also
  5147. # serves the queue dispatcher — there the queue item decides.
  5148. # Guarded because this branch has no ``except``: an unhandled
  5149. # write error would take the _active_prints registration, the
  5150. # start notification, the energy reading and the timelapse
  5151. # baseline below it with it, and a missing prompt is by far the
  5152. # cheaper failure.
  5153. archive_id = archive.id
  5154. try:
  5155. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5156. archive.confirm_requested = True
  5157. await db.commit()
  5158. except Exception as e:
  5159. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5160. # The rollback expires every loaded object, and on an async
  5161. # session reading one afterwards raises instead of
  5162. # reloading, so the two this branch goes on to use are
  5163. # fetched again. The archive itself was committed by
  5164. # archive_print; only the flag is lost.
  5165. try:
  5166. await db.rollback()
  5167. archive = await db.get(PrintArchive, archive_id)
  5168. printer = await db.get(Printer, printer_id)
  5169. except Exception as reload_error:
  5170. logger.warning(
  5171. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5172. )
  5173. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5174. return
  5175. # Track this active print (use both original filename and downloaded filename)
  5176. _active_prints[(printer_id, downloaded_filename)] = archive.id
  5177. if filename and filename != downloaded_filename:
  5178. _active_prints[(printer_id, filename)] = archive.id
  5179. if subtask_name:
  5180. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  5181. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5182. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5183. # Record starting energy from smart plug if available (#941: persisted column)
  5184. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5185. await ws_manager.send_archive_created(
  5186. {
  5187. "id": archive.id,
  5188. "printer_id": archive.printer_id,
  5189. "filename": archive.filename,
  5190. "print_name": archive.print_name,
  5191. "status": archive.status,
  5192. }
  5193. )
  5194. # MQTT relay - publish archive created
  5195. try:
  5196. await mqtt_relay.on_archive_created(
  5197. archive_id=archive.id,
  5198. print_name=archive.print_name,
  5199. printer_name=printer.name,
  5200. status=archive.status,
  5201. )
  5202. except Exception:
  5203. pass # Don't fail if MQTT fails
  5204. # Send notification with archive data (new archive created)
  5205. if not notification_sent:
  5206. archive_data = {
  5207. "print_time_seconds": archive.print_time_seconds,
  5208. "created_by_id": archive.created_by_id,
  5209. }
  5210. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5211. # Extract printable objects for skip object functionality
  5212. try:
  5213. from backend.app.services.archive import extract_printable_objects_from_3mf
  5214. client = printer_manager.get_client(printer_id)
  5215. if client:
  5216. with open(temp_path, "rb") as f:
  5217. threemf_data = f.read()
  5218. # Extract with positions for UI overlay, scoped to the
  5219. # plate that is printing — an all-plates 3MF carries
  5220. # every plate's objects (#2522).
  5221. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5222. threemf_data,
  5223. plate_number=resolve_plate_id(client.state),
  5224. include_positions=True,
  5225. )
  5226. if printable_objects:
  5227. # Store objects in printer state
  5228. client.state.printable_objects = printable_objects
  5229. client.state.printable_objects_bbox_all = bbox_all
  5230. client.state.skipped_objects = [] # Reset skipped objects for new print
  5231. logger.info(
  5232. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5233. )
  5234. except Exception as e:
  5235. logger.debug("Failed to extract printable objects: %s", e)
  5236. # Store Spoolman tracking data for per-filament usage reporting
  5237. try:
  5238. await _store_spoolman_print_data(
  5239. printer_id,
  5240. archive.id,
  5241. archive.file_path,
  5242. db,
  5243. printer_manager,
  5244. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5245. plate_id=_get_start_plate_id(archive.id),
  5246. )
  5247. except Exception as e:
  5248. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5249. # Price the print from its spools now rather than only at completion (#3261)
  5250. _schedule_archive_cost_estimate(
  5251. printer_id,
  5252. archive.id,
  5253. printer_manager,
  5254. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5255. plate_id=_get_start_plate_id(archive.id),
  5256. session_factory=async_session,
  5257. )
  5258. # Capture timelapse file baseline for snapshot-diff on completion
  5259. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5260. await _forget_if_printer_gone(printer_id)
  5261. finally:
  5262. # Keep temp_path around until print completes so the cover endpoint
  5263. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5264. # the file. If the cache entry was evicted early (file vanished),
  5265. # clean up any stragglers here to avoid leaking disk on retries.
  5266. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5267. if temp_path and temp_path.exists() and cached_now != temp_path:
  5268. temp_path.unlink()
  5269. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5270. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5271. # tests can shrink them without waiting out real delays.
  5272. #
  5273. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5274. # looking. Across 247 support bundles the attempt that found the video was #1
  5275. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5276. # decaying one, which is the signature of a budget that expires while files are
  5277. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5278. # prints make big videos and the printer writes them after the print ends, so
  5279. # the poll now runs for minutes and costs one FTP LIST per round.
  5280. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5281. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5282. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5283. def _timelapse_scan_max_attempts() -> int:
  5284. """Round cap for the poll, derived from the wall-clock budget.
  5285. The deadline alone is not a sufficient bound: it assumes each round really
  5286. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5287. and an FTP list that fails immediately would otherwise spin against the
  5288. printer at full speed for the whole window. Whichever bound is reached
  5289. first ends the poll.
  5290. """
  5291. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5292. # A zero interval makes the wall-clock budget meaningless; fall back to
  5293. # the round count the production interval would have given.
  5294. return 32
  5295. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5296. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5297. """Video filenames already attached to some other archive of this printer.
  5298. Used to disambiguate when more than one file is new since the baseline —
  5299. which happens when a previous print's video landed after this print's
  5300. baseline was taken. Ordering the candidates would be the obvious fix and is
  5301. the wrong one: it can only be done on mtime or on the filename timestamp,
  5302. both of which come from the printer's own clock, and a LAN-only printer
  5303. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5304. ``attach_timelapse`` saves the video into the archive directory under the
  5305. printer's original filename, and the later MP4 conversion keeps the stem,
  5306. so the stem of ``timelapse_path`` recovers what was claimed.
  5307. """
  5308. from backend.app.models.archive import PrintArchive
  5309. rows = await db.execute(
  5310. select(PrintArchive.timelapse_path).where(
  5311. PrintArchive.printer_id == printer_id,
  5312. PrintArchive.id != exclude_archive_id,
  5313. PrintArchive.timelapse_path.is_not(None),
  5314. )
  5315. )
  5316. return {Path(p).stem for p in rows.scalars().all() if p}
  5317. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5318. """Whether an *empty* timelapse listing for *printer* can be believed.
  5319. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5320. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5321. from one holding no videos. Everywhere that only wants to know "is there a
  5322. video yet" the difference does not matter — both mean "not yet, retry".
  5323. It matters where an empty listing is recorded as a *baseline*. Recording
  5324. "the card held nothing" for a card that was never read means every video on
  5325. it counts as new once the cool-off expires, and the completion scan then
  5326. attaches a stale video to this print and deletes it from the printer
  5327. (#2957 follow-up). Those two callers ask this first.
  5328. """
  5329. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5330. ip_address = getattr(printer, "ip_address", None)
  5331. if not ip_address:
  5332. return True
  5333. return not ftps_handshake_blocked(ip_address)
  5334. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5335. """List video files from printer's timelapse directory.
  5336. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5337. Returns (video_files, found_path) where video_files is a list of file dicts
  5338. and found_path is the directory where they were found, or ([], None).
  5339. An empty return does not distinguish "no videos" from "could not read the
  5340. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5341. baseline callers consult before believing one.
  5342. """
  5343. from backend.app.services.bambu_ftp import list_files_async
  5344. logger = logging.getLogger(__name__)
  5345. # No card in the slot means no /timelapse to walk — four connections that
  5346. # can only fail, on a path whose failures are swallowed and so would go on
  5347. # costing time silently forever (#2780).
  5348. #
  5349. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5350. # inside the loop's own try/except, so a caller that passed something
  5351. # unexpected used to get an empty listing rather than an exception. Keep
  5352. # that, instead of making this gate the first thing that can raise here.
  5353. printer_id = getattr(printer, "id", None)
  5354. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5355. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5356. return [], None
  5357. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5358. try:
  5359. found_files = await list_files_async(
  5360. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5361. )
  5362. if found_files:
  5363. video_files = [
  5364. f
  5365. for f in found_files
  5366. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5367. ]
  5368. if video_files:
  5369. return video_files, timelapse_path
  5370. except Exception as e:
  5371. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5372. continue
  5373. return [], None
  5374. async def _capture_timelapse_baseline_at_start(
  5375. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5376. ) -> None:
  5377. """Snapshot the printer's timelapse directory at print start so the
  5378. completion-time scan can pick the new file by set-difference.
  5379. Must be called from every on_print_start path that proceeds to a real
  5380. print — both the new-archive branch and the expected-archive branch (which
  5381. queue / VP-dispatched prints take). Without a baseline,
  5382. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5383. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5384. so the new file ends up in the "baseline" set and no diff ever matches.
  5385. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5386. unreliable — the snapshot-diff approach sidesteps that entirely.
  5387. When ``archive_id`` is known the baseline is also written to the archive
  5388. row, so it survives a restart and the manual "Scan for Timelapse" button
  5389. can run the same diff instead of falling back to clock-based matching
  5390. (#2704). Only baselines taken at print start are persisted — one taken at
  5391. completion already contains the new video and would poison a later scan.
  5392. """
  5393. names: set[str] | None = None
  5394. try:
  5395. if not _timelapse_listing_is_trustworthy(printer):
  5396. # Recorded anyway, deliberately. An empty baseline taken off a card
  5397. # we could not read is not authoritative, but it is still the right
  5398. # *default*: Bambuddy deletes each video from the printer once it is
  5399. # attached, so the usual card holds exactly one video at completion
  5400. # and an empty baseline resolves it correctly. Persisting NULL
  5401. # instead would send completion to take its own snapshot, by which
  5402. # point this print's video is on the card and would be swallowed by
  5403. # it. The ambiguity is handled where it actually bites — see
  5404. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5405. logger.warning(
  5406. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5407. "handshake cool-off, so the card could not be read — treating it as empty",
  5408. printer_id,
  5409. )
  5410. baseline_files, _ = await _list_timelapse_videos(printer)
  5411. names = {f.get("name", "") for f in baseline_files}
  5412. _timelapse_baselines[printer_id] = names
  5413. logger.info(
  5414. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5415. len(names),
  5416. printer_id,
  5417. )
  5418. except Exception as e:
  5419. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5420. if archive_id is None:
  5421. return
  5422. try:
  5423. async with async_session() as db:
  5424. from backend.app.models.archive import PrintArchive
  5425. archive = await db.get(PrintArchive, archive_id)
  5426. if archive is not None:
  5427. # Written even when the listing failed, and then as NULL. A
  5428. # reprint reuses the archive row, so leaving the previous run's
  5429. # baseline in place would have the scan diff this print against
  5430. # the state of the printer before the *last* one — and a stale
  5431. # baseline reads as authoritative, where NULL correctly falls
  5432. # back to a fresh snapshot.
  5433. archive.timelapse_baseline = sorted(names) if names is not None else None
  5434. await db.commit()
  5435. except Exception as e:
  5436. # In-memory baseline still covers the normal completion path.
  5437. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5438. async def _scan_for_timelapse_with_retries(
  5439. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5440. ):
  5441. """Poll the printer for this print's timelapse and attach it.
  5442. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5443. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5444. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5445. (#2704). Comparing the current listing against the set of filenames that
  5446. existed when the print started needs no clock at all, because the printer
  5447. writes the video only once the print has ended.
  5448. Baseline precedence: the caller's in-memory set, then the one persisted on
  5449. the archive at print start, then a snapshot taken now. The last of those is
  5450. a poor substitute — by completion the new video may already be on the card,
  5451. in which case it lands in the "baseline" and no diff can ever match — but it
  5452. is all that is available for a print that began before Bambuddy started.
  5453. On success the video is deleted from the printer, which keeps ``/timelapse``
  5454. down to the unclaimed files and makes the next diff unambiguous.
  5455. """
  5456. logger = logging.getLogger(__name__)
  5457. # Cleared when the baseline had to be taken off a card we could not read, so
  5458. # the attach step refuses to choose between several candidates (#2957).
  5459. baseline_trusted = True
  5460. # --- Phase 1: establish the baseline -------------------------------------
  5461. try:
  5462. async with async_session() as db:
  5463. from backend.app.models.printer import Printer
  5464. service = ArchiveService(db)
  5465. archive = await service.get_archive(archive_id)
  5466. if not archive:
  5467. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5468. return
  5469. if archive.timelapse_path:
  5470. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5471. return
  5472. if not archive.printer_id:
  5473. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5474. return
  5475. if baseline_names is not None:
  5476. logger.info(
  5477. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5478. len(baseline_names),
  5479. archive_id,
  5480. )
  5481. elif archive.timelapse_baseline is not None:
  5482. # Persisted at print start — survives a restart mid-print.
  5483. baseline_names = set(archive.timelapse_baseline)
  5484. logger.info(
  5485. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5486. len(baseline_names),
  5487. archive_id,
  5488. )
  5489. else:
  5490. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5491. printer = result.scalar_one_or_none()
  5492. if not printer:
  5493. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5494. return
  5495. if not _timelapse_listing_is_trustworthy(printer):
  5496. # The card is unreadable at the one moment a baseline has to
  5497. # be taken, so the empty listing below means "we never
  5498. # looked", not "these are all new". Carry on with it anyway
  5499. # — the usual card holds exactly one video, which resolves
  5500. # correctly — but stop the poll from *choosing* between
  5501. # several, which is how a stale video got attached to this
  5502. # print and then deleted off the printer (#2957 follow-up).
  5503. baseline_trusted = False
  5504. logger.warning(
  5505. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5506. "handshake cool-off. A single new video still resolves; several will not be "
  5507. "guessed between — use Scan for Timelapse to pick one by hand",
  5508. archive_id,
  5509. archive.printer_id,
  5510. )
  5511. baseline_files, _ = await _list_timelapse_videos(printer)
  5512. baseline_names = {f.get("name", "") for f in baseline_files}
  5513. logger.info(
  5514. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5515. len(baseline_names),
  5516. archive_id,
  5517. )
  5518. except Exception as e:
  5519. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5520. return
  5521. # --- Phase 2: poll for a file that was not there when the print began -----
  5522. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5523. max_attempts = _timelapse_scan_max_attempts()
  5524. seen_names: set[str] = set()
  5525. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5526. attempt = 0
  5527. while True:
  5528. await asyncio.sleep(delay)
  5529. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5530. attempt += 1
  5531. try:
  5532. from backend.app.models.printer import Printer
  5533. # Read phase: fetch archive + printer in a short session and release
  5534. # the pooled connection BEFORE the FTP list/download below. Holding it
  5535. # across the FTP round-trips left one connection idle-in-transaction per
  5536. # in-flight scan (issue #2572).
  5537. async with async_session() as db:
  5538. service = ArchiveService(db)
  5539. archive = await service.get_archive(archive_id)
  5540. if not archive:
  5541. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5542. return
  5543. if archive.timelapse_path:
  5544. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5545. return
  5546. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5547. printer = result.scalar_one_or_none()
  5548. if not printer:
  5549. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5550. return
  5551. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5552. # I/O phase (no DB connection held): FTP list + download.
  5553. video_files, found_path = await _list_timelapse_videos(printer)
  5554. # The poll can run for dozens of rounds, so only narrate a round
  5555. # that saw something change. Repeating the whole listing every 30 s
  5556. # would bury the one interesting line in the support bundle.
  5557. names_now = {f.get("name", "") for f in video_files}
  5558. changed = attempt == 1 or names_now != seen_names
  5559. seen_names = names_now
  5560. speak = logger.info if changed else logger.debug
  5561. if video_files:
  5562. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5563. if changed:
  5564. for f in video_files[:5]:
  5565. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5566. attached = await _attach_first_unclaimed_timelapse(
  5567. archive_id,
  5568. printer,
  5569. video_files,
  5570. baseline_names,
  5571. claimed,
  5572. attempt,
  5573. logger,
  5574. quiet=not changed,
  5575. require_unambiguous=not baseline_trusted,
  5576. plate_id=plate_id,
  5577. )
  5578. if attached:
  5579. return
  5580. else:
  5581. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5582. except Exception as e:
  5583. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5584. if attempt >= max_attempts or time.monotonic() >= deadline:
  5585. break
  5586. # No name-match fallback: it compared the print name against the filename,
  5587. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5588. # bundles it fired 159 times and matched zero times, so all it added was a
  5589. # misleading log line before giving up.
  5590. logger.warning(
  5591. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5592. archive_id,
  5593. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5594. )
  5595. async def _attach_first_unclaimed_timelapse(
  5596. archive_id: int,
  5597. printer,
  5598. video_files: list[dict],
  5599. baseline_names: set[str],
  5600. claimed: set[str],
  5601. attempt: int,
  5602. logger: logging.Logger,
  5603. *,
  5604. quiet: bool = False,
  5605. require_unambiguous: bool = False,
  5606. plate_id: int | None = None,
  5607. ) -> bool:
  5608. """Download and attach the one video that belongs to this print.
  5609. A candidate is any file absent from the print-start baseline. More than one
  5610. can qualify when a previous print's video landed late, after this print's
  5611. baseline was taken — those are filtered out by name, because they are
  5612. already attached to another archive. Sorting the candidates instead would
  5613. mean sorting on mtime or on the filename timestamp, both of which come from
  5614. the printer's unsynced clock.
  5615. Returns True once a video is attached. The printer's copy is deleted only
  5616. after the attach succeeds on bytes whose length matched the listing.
  5617. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5618. already seen this exact listing — the poll runs for many rounds and only the
  5619. rounds where something changed are worth an INFO line.
  5620. """
  5621. from backend.app.services.bambu_ftp import (
  5622. delete_archived_timelapse,
  5623. download_file_bytes_async,
  5624. remote_file_settled,
  5625. )
  5626. speak = logger.debug if quiet else logger.info
  5627. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5628. if not new_files:
  5629. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5630. return False
  5631. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5632. if not candidates:
  5633. speak(
  5634. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5635. attempt,
  5636. len(new_files),
  5637. )
  5638. return False
  5639. if len(candidates) > 1:
  5640. if require_unambiguous:
  5641. # The baseline is not evidence -- it was taken off a card that could
  5642. # not be read -- so "new since the baseline" does not narrow these
  5643. # down at all. Taking the first would attach an arbitrary video to
  5644. # this print and then delete it from the printer.
  5645. logger.warning(
  5646. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5647. "leaving all of them on the printer for manual selection",
  5648. attempt,
  5649. len(candidates),
  5650. ", ".join(str(f.get("name")) for f in candidates),
  5651. )
  5652. return False
  5653. logger.warning(
  5654. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5655. "the rest stay on the printer for manual selection",
  5656. attempt,
  5657. len(candidates),
  5658. ", ".join(str(f.get("name")) for f in candidates),
  5659. )
  5660. target = candidates[0]
  5661. file_name = target.get("name")
  5662. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5663. logger.info(
  5664. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5665. attempt,
  5666. file_name,
  5667. archive_id,
  5668. )
  5669. # The listing always carries a size (`list_files` skips entries it can't
  5670. # parse), but read it explicitly: the delete below is destructive and must
  5671. # depend on a size we actually had, not on one we hoped was there.
  5672. expected_size = target.get("size")
  5673. timelapse_data = await download_file_bytes_async(
  5674. printer.ip_address,
  5675. printer.access_code,
  5676. remote_path,
  5677. printer_model=printer.model,
  5678. expected_size=expected_size,
  5679. )
  5680. if not timelapse_data:
  5681. # Short or failed transfer. The printer keeps its copy, so the next
  5682. # round can try again — which is exactly why the delete below is
  5683. # gated on a verified download.
  5684. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5685. return False
  5686. # The length check above proves we got what the listing said, not that the
  5687. # printer had finished writing. A video still being written can be listed
  5688. # short, served short, and pass — so confirm it has stopped growing before
  5689. # committing to it and deleting the original (#2704).
  5690. if not await remote_file_settled(
  5691. printer.ip_address,
  5692. printer.access_code,
  5693. remote_path,
  5694. len(timelapse_data),
  5695. printer_model=printer.model,
  5696. ):
  5697. return False
  5698. # Write phase: attach in a fresh short-lived session.
  5699. async with async_session() as db:
  5700. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5701. if not success:
  5702. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5703. return False
  5704. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5705. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5706. await delete_archived_timelapse(
  5707. printer.ip_address,
  5708. printer.access_code,
  5709. remote_path,
  5710. verified=expected_size is not None,
  5711. printer_model=printer.model,
  5712. printer_name=printer.name,
  5713. )
  5714. return True
  5715. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5716. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5717. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5718. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5719. # How long the *background* upgrade keeps waiting after the notification has
  5720. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5721. # printer can't hold up the print-complete notification; this one exists so the
  5722. # archive still ends up with the better frame afterwards.
  5723. #
  5724. # Measured across 261 attaches in the support bundles, the video lands a median
  5725. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5726. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5727. # was 546s. Every other model was inside 26s. The long budget is therefore
  5728. # almost entirely for P1-series users; on everything else the short wait already
  5729. # wins and this task never runs.
  5730. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5731. async def _capture_finish_photo_from_timelapse(
  5732. archive_id: int,
  5733. archive_dir: Path,
  5734. timeout: float | None = None,
  5735. rotation: int = 0,
  5736. ) -> tuple[str | None, bool]:
  5737. """Wait for the per-print timelapse to land on the archive and extract its
  5738. last frame as the finish photo (#1397).
  5739. Bambu firmware stops timelapse recording after the toolhead parks but
  5740. before the bed-drop end-gcode runs, so the last frame frames the finished
  5741. print correctly. A live camera grab at gcode_state=FINISH captures the
  5742. bed already lowered.
  5743. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5744. ``archive.timelapse_path`` when the file lands. This function polls for
  5745. that field.
  5746. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5747. the wait ran out with no video on the archive yet — i.e. the video may
  5748. still be coming and a later attempt could succeed. It is False when the
  5749. video landed (whether or not extraction worked), because in that case
  5750. waiting longer changes nothing. The caller uses that to decide between
  5751. falling back permanently and scheduling a background upgrade.
  5752. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5753. still (#2708) so this source agrees with every other finish-photo source.
  5754. The archived video itself is the printer's own file and is left alone —
  5755. rotating it would mean re-encoding it.
  5756. """
  5757. import uuid
  5758. from backend.app.models.archive import PrintArchive
  5759. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5760. logger = logging.getLogger(__name__)
  5761. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5762. deadline = asyncio.get_event_loop().time() + budget
  5763. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5764. while True:
  5765. async with async_session() as db:
  5766. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5767. archive = result.scalar_one_or_none()
  5768. timelapse_relpath = archive.timelapse_path if archive else None
  5769. if timelapse_relpath:
  5770. video_path = app_settings.base_dir / timelapse_relpath
  5771. if video_path.exists() and video_path.stat().st_size > 0:
  5772. photos_dir = archive_dir / "photos"
  5773. photos_dir.mkdir(parents=True, exist_ok=True)
  5774. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5775. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5776. output_path = photos_dir / filename
  5777. if await extract_video_last_frame(video_path, output_path):
  5778. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5779. logger.info(
  5780. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5781. video_path.name,
  5782. archive_id,
  5783. )
  5784. return filename, False
  5785. logger.warning(
  5786. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5787. video_path.name,
  5788. archive_id,
  5789. )
  5790. return None, False
  5791. if asyncio.get_event_loop().time() >= deadline:
  5792. logger.info(
  5793. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5794. archive_id,
  5795. budget,
  5796. )
  5797. return None, True
  5798. await asyncio.sleep(poll_interval)
  5799. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5800. """Add the timelapse's last frame to an archive after the fact (#2704).
  5801. The print-complete notification waits only ~60s for the video, because
  5802. holding a notification for minutes is worse than sending it with a live
  5803. camera grab. On a P1-series printer the video often lands well after that,
  5804. so the archive used to be stuck with the live grab — which is taken at
  5805. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5806. the worse photo of the two.
  5807. This keeps waiting in the background and, when the video arrives, extracts
  5808. the frame and puts it *first* in the archive's photo list, so opening the
  5809. gallery shows it. The live grab is deliberately kept: the notification that
  5810. already went out links to that exact file, and deleting it would leave a
  5811. broken image in Discord or Telegram.
  5812. """
  5813. logger = logging.getLogger(__name__)
  5814. filename, _ = await _capture_finish_photo_from_timelapse(
  5815. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5816. )
  5817. if not filename:
  5818. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5819. return
  5820. try:
  5821. async with async_session() as db:
  5822. from backend.app.models.archive import PrintArchive
  5823. archive = await db.get(PrintArchive, archive_id)
  5824. if archive is None:
  5825. return
  5826. photos = list(archive.photos or [])
  5827. if filename in photos:
  5828. return
  5829. # Front of the list: PhotoGalleryModal opens at index 0.
  5830. archive.photos = [filename, *photos]
  5831. await db.commit()
  5832. except Exception as e:
  5833. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5834. return
  5835. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5836. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5837. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5838. """Put the filament-attribution context back after a restart mid-print.
  5839. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5840. both die with the process. The print keeps running, so at completion the
  5841. tracker would fall back to whatever the printer reports *now* — and AMS
  5842. filament backup makes "now" the substitute tray, charging the whole print
  5843. to the spool that only finished it.
  5844. The persisted row is only trusted when its print name still matches what
  5845. the printer says it is running: a row left behind by a completion we never
  5846. saw must not attach itself to the next print.
  5847. """
  5848. try:
  5849. from backend.app.api.routes.settings import get_setting
  5850. from backend.app.services.usage_tracker import (
  5851. clear_persisted_session,
  5852. get_persisted_print_name,
  5853. restore_session,
  5854. )
  5855. persisted_name = await get_persisted_print_name(db, printer_id)
  5856. current_name = (state.subtask_name or "").strip()
  5857. if persisted_name and current_name and persisted_name.strip() != current_name:
  5858. logger.info(
  5859. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5860. printer_id,
  5861. persisted_name,
  5862. current_name,
  5863. )
  5864. await clear_persisted_session(db, printer_id)
  5865. # Fall through to seeding: the print on the printer is real, it just
  5866. # isn't the one the row described.
  5867. persisted_log = None
  5868. else:
  5869. # Spoolman users get the tray-change log back but no in-memory
  5870. # session — see ``on_print_start`` on why that dict is load-bearing
  5871. # for the remain%-sync guard.
  5872. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5873. persisted_log = await restore_session(
  5874. db,
  5875. printer_id,
  5876. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5877. )
  5878. if persisted_log:
  5879. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5880. # Anything this process already observed goes after the persisted
  5881. # history — the log is ordered by layer, and a fresh process can
  5882. # only have seen changes from later in the print.
  5883. for entry in state.tray_change_log or []:
  5884. if tuple(entry) not in restored:
  5885. restored.append(tuple(entry))
  5886. state.tray_change_log = restored
  5887. tray_now = state.tray_now
  5888. if 0 <= tray_now <= 254:
  5889. if not state.tray_change_log:
  5890. # No persisted history — a print that started before this build,
  5891. # or before the row existed. Seed with the tray feeding right
  5892. # now so the remainder of the print is at least attributable to
  5893. # the right spool.
  5894. state.tray_change_log = [(tray_now, state.layer_num)]
  5895. logger.info(
  5896. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5897. printer_id,
  5898. tray_now,
  5899. state.layer_num,
  5900. )
  5901. # The tray handler updates ``last_loaded_tray`` on every push
  5902. # regardless of whether it logged a change, so re-align it to avoid
  5903. # a duplicate entry on the next push. Only ever with a real tray:
  5904. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5905. # 255" fallback, and writing 255 into it would defeat that.
  5906. state.last_loaded_tray = tray_now
  5907. except Exception:
  5908. # Never let attribution recovery cost the caller its timelapse
  5909. # baseline — that capture has to happen before the printer uploads
  5910. # the in-flight MP4 and there is no second chance at it.
  5911. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5912. async def on_print_running_observed(printer_id: int, data: dict):
  5913. """Restart-recovery for a print that started before Bambuddy came up.
  5914. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5915. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5916. creation). This hook restores the persisted archive into ``_active_prints``
  5917. and captures the timelapse baseline that normally hangs off print start.
  5918. Fires once per session, in lieu of on_print_start when restart-recovery
  5919. kicks in. The printer doesn't upload the timelapse until after PRINT
  5920. COMPLETE, so a baseline captured any time during the print is still
  5921. pre-upload.
  5922. """
  5923. logger = logging.getLogger(__name__)
  5924. async with async_session() as db:
  5925. from backend.app.models.printer import Printer
  5926. state = printer_manager.get_status(printer_id)
  5927. if state is not None:
  5928. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5929. if authorization is True:
  5930. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5931. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5932. await _restore_printable_objects(printer_id, state, db, logger)
  5933. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5934. printer = result.scalar_one_or_none()
  5935. if not printer:
  5936. logger.warning(
  5937. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5938. printer_id,
  5939. )
  5940. return
  5941. # Avoid double-capture: ownership reconciliation above must still run when
  5942. # a baseline already exists, but the camera work itself is one-shot.
  5943. if printer_id in _timelapse_baselines:
  5944. logger.debug(
  5945. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5946. printer_id,
  5947. )
  5948. return
  5949. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5950. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5951. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5952. against the printer's current MQTT state.
  5953. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5954. COMPLETE events, typically a print finishing during an MQTT disconnect
  5955. window followed by a smart-plug power cycle):
  5956. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5957. provably not running anymore — only branch that should fire under
  5958. normal disconnect-then-reconnect timing.
  5959. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5960. firmware mints a fresh ``subtask_id`` for each print, including the
  5961. ghost replay it runs after a power cycle from a leftover SD file —
  5962. so a mismatch unambiguously means the in-DB archive is no longer
  5963. the print on the printer.
  5964. 3. Printer is running but ``subtask_name`` is empty. The printer
  5965. doesn't know what it's running; the archive's reference to it is
  5966. already broken.
  5967. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5968. with matching subtask_id+subtask_name is left alone. The cost of a false
  5969. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5970. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5971. clears on synthesis, so the real completion creates a fresh row instead
  5972. of overwriting the synthesised one (#1679). The cost of a false negative
  5973. is the ghost-print loop in #1542.
  5974. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5975. MQTT has connected but the first ``push_status`` response hasn't been
  5976. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5977. The reconcile caller in ``on_printer_status_change`` is already gated
  5978. on a real ``state.state``, so in normal operation this branch is
  5979. unreachable; it's kept as belt-and-braces for future callers and for
  5980. the narrow window where a partial state update could arrive
  5981. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5982. ``not stale`` on degenerate input is strictly conservative: a real
  5983. stale archive will still be caught by the next push_status arriving
  5984. with terminal state.
  5985. """
  5986. current_state = (state.state or "").upper()
  5987. if current_state in ("", "UNKNOWN"):
  5988. # No real push_status yet — PrinterState defaults are not evidence.
  5989. return False, ""
  5990. if current_state in ("IDLE", "FINISH", "FAILED"):
  5991. return True, f"printer state {current_state}"
  5992. # Below here the printer is in a running / pre-running state (RUNNING /
  5993. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5994. current_subtask_id = (state.subtask_id or "").strip()
  5995. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5996. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5997. current_subtask_name = (state.subtask_name or "").strip()
  5998. if not current_subtask_name:
  5999. return True, "printer subtask_name empty"
  6000. return False, ""
  6001. async def prime_kprofile_table(printer_id: int) -> int:
  6002. """Read the printer's calibration table once per connection.
  6003. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6004. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6005. report ``cali_idx`` and nothing else -- that number can only come from
  6006. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6007. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6008. backup, or the printer answering a query BambuStudio made on the report
  6009. topic we share. A Bambuddy that nobody visited showed a card with no K
  6010. values at all.
  6011. Only the diameters actually fitted are asked for, which is one request on a
  6012. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6013. what the backup does, and it is both wasteful and the thing that used to
  6014. blank the table.
  6015. Returns the number of nozzles whose table was read.
  6016. """
  6017. client = printer_manager.get_client(printer_id)
  6018. state = printer_manager.get_status(printer_id)
  6019. if client is None or state is None or not state.connected:
  6020. return 0
  6021. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6022. # ask once, and both entries are empty until the first push_status lands.
  6023. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6024. if not diameters:
  6025. logging.getLogger(__name__).debug(
  6026. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6027. printer_id,
  6028. )
  6029. return 0
  6030. primed = 0
  6031. for diameter in diameters:
  6032. try:
  6033. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6034. except Exception as exc: # noqa: BLE001
  6035. # A printer that won't answer costs the card its K values, nothing
  6036. # more — never the connection this runs on the back of.
  6037. logging.getLogger(__name__).warning(
  6038. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6039. )
  6040. continue
  6041. primed += 1
  6042. logging.getLogger(__name__).info(
  6043. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6044. )
  6045. return primed
  6046. def _sd_files_in_use(state) -> set[str]:
  6047. """Names of the SD-card files the printer may be printing right now (#3009).
  6048. The post-print cleanup works out what to delete from the finished archive,
  6049. not from the printer. When reconciliation closes an old archive because the
  6050. printer has moved on to a new job, and that job is the same file reprinted
  6051. from the printer's screen, the cleanup would delete the file mid-print.
  6052. Empty unless the printer is busy: on an ordinary completion the state is
  6053. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6054. name, a path or a URL depending on firmware, and some report only the
  6055. plate's G-code, so the job name is matched as well, in the same spellings
  6056. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6057. ignores case.
  6058. """
  6059. def _text(value) -> str:
  6060. return value.strip() if isinstance(value, str) else ""
  6061. if state is None:
  6062. return set()
  6063. current_state = _text(getattr(state, "state", None)).upper()
  6064. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6065. return set()
  6066. in_use: set[str] = set()
  6067. gcode_file = _text(getattr(state, "gcode_file", None))
  6068. if gcode_file:
  6069. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6070. # both legal in a file name, and raises on some inputs.
  6071. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6072. if name:
  6073. in_use.add(name.lower())
  6074. subtask_name = _text(getattr(state, "subtask_name", None))
  6075. if subtask_name:
  6076. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6077. for ext in (".3mf", ".gcode"):
  6078. in_use.add(f"{name}{ext}".lower())
  6079. return in_use
  6080. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6081. """Synthesise ``on_print_complete`` for archives whose print can't be
  6082. running on the printer anymore.
  6083. Called once per MQTT (re)connection (from on_printer_status_change when
  6084. the connected edge flips False → True) and at Bambuddy startup (from
  6085. the FastAPI lifespan). Without this, a print that completes during a
  6086. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6087. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6088. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6089. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6090. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6091. closes the loop by faking the missed PRINT COMPLETE — the existing
  6092. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6093. and notifications.
  6094. Synthesised ``status="aborted"`` is the conservative label: we have no
  6095. proof the print finished successfully (and no progress evidence to
  6096. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6097. fires later, overwrites the status with the correct value.
  6098. Returns the number of archives reconciled.
  6099. """
  6100. state = printer_manager.get_status(printer_id)
  6101. if not state:
  6102. return 0
  6103. # Don't reconcile while disconnected — we'd be making a decision against
  6104. # stale cached state. The connected → reconcile edge handles this.
  6105. if not state.connected:
  6106. return 0
  6107. from backend.app.models.archive import PrintArchive
  6108. reconciled = 0
  6109. async with async_session() as db:
  6110. result = await db.execute(
  6111. select(PrintArchive).where(
  6112. PrintArchive.printer_id == printer_id,
  6113. PrintArchive.status == "printing",
  6114. )
  6115. )
  6116. active = list(result.scalars().all())
  6117. if not active:
  6118. return 0
  6119. logger = logging.getLogger(__name__)
  6120. for archive in active:
  6121. is_stale, reason = _is_active_archive_stale(archive, state)
  6122. if not is_stale:
  6123. continue
  6124. logger.info(
  6125. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6126. printer_id,
  6127. archive.id,
  6128. archive.filename,
  6129. reason,
  6130. )
  6131. # Synthesised payload: minimal fields the on_print_complete chain
  6132. # needs. `_reconciled` marker lets downstream code distinguish this
  6133. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6134. # metrics / debug logging). raw_data is the live printer state so
  6135. # the usage tracker can compare end-of-print remain% against the
  6136. # captured start values.
  6137. try:
  6138. await on_print_complete(
  6139. printer_id,
  6140. {
  6141. "status": "aborted",
  6142. "filename": archive.filename,
  6143. "subtask_name": archive.print_name or "",
  6144. "subtask_id": archive.subtask_id or "",
  6145. "raw_data": state.raw_data or {},
  6146. "_reconciled": True,
  6147. },
  6148. )
  6149. reconciled += 1
  6150. except Exception as e:
  6151. # Catch-all: a reconciliation failure must not block the
  6152. # printer's normal status flow. The archive stays in
  6153. # ``status="printing"`` and the next reconnect retries.
  6154. logger.warning(
  6155. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6156. archive.id,
  6157. e,
  6158. )
  6159. return reconciled
  6160. # #2547: clearance left between the nozzle and the top of the print when the
  6161. # plate is commanded back into camera framing. The nozzle is parked away from
  6162. # the part by then, so this is belt-and-braces against a max_z_height that
  6163. # under-reports (e.g. a slicer that excludes a final Z hop).
  6164. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6165. # How far below the restored position to drop the plate again afterwards, so
  6166. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6167. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6168. # on machines with less headroom.
  6169. _PLATE_PARK_DROP_MM = 100.0
  6170. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6171. # this axis, so it is a proven-safe speed for the full travel.
  6172. _PLATE_RESTORE_FEEDRATE = 600
  6173. # Time allowed for the plate to reach the restored position before the camera
  6174. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6175. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6176. # How long `_background_finish_photo` waits for this producer. Must cover the
  6177. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6178. # notification path's own photo wait so a slow producer degrades to a
  6179. # photo-less notification rather than a missed one. The chamber light's
  6180. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6181. # camera_light.MAX_DELAY_SECONDS stays below it.
  6182. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6183. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6184. """The ``_active_prints`` keys a finished print may be registered under.
  6185. Matching how they were registered in on_print_start. Shared by
  6186. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6187. to find the same binding.
  6188. """
  6189. possible_keys = []
  6190. # Try subtask_name variations first (most reliable for matching)
  6191. if subtask_name:
  6192. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6193. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6194. possible_keys.append((printer_id, subtask_name))
  6195. # Try filename variations
  6196. if filename:
  6197. # Extract just the filename if it's a path
  6198. fname = filename.split("/")[-1] if "/" in filename else filename
  6199. if fname.endswith(".3mf"):
  6200. possible_keys.append((printer_id, fname))
  6201. elif fname.endswith(".gcode"):
  6202. base_name = fname.rsplit(".", 1)[0]
  6203. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6204. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6205. possible_keys.append((printer_id, fname))
  6206. else:
  6207. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6208. possible_keys.append((printer_id, f"{fname}.3mf"))
  6209. possible_keys.append((printer_id, fname))
  6210. # Also try full path versions
  6211. if filename.endswith(".3mf"):
  6212. possible_keys.append((printer_id, filename))
  6213. elif filename.endswith(".gcode"):
  6214. base_name = filename.rsplit(".", 1)[0]
  6215. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6216. possible_keys.append((printer_id, filename))
  6217. else:
  6218. possible_keys.append((printer_id, f"{filename}.3mf"))
  6219. possible_keys.append((printer_id, filename))
  6220. return possible_keys
  6221. def _archive_name_forms(archive) -> set[str]:
  6222. """The names an archive could be echoed back as, in normalised form (#3240).
  6223. Its print name, and its filename with and without the 3MF extension.
  6224. """
  6225. forms = set()
  6226. if archive.print_name:
  6227. forms.add(_normalise_subtask_name(archive.print_name))
  6228. if archive.filename:
  6229. forms.add(_normalise_subtask_name(archive.filename))
  6230. for suffix in (".gcode.3mf", ".3mf"):
  6231. if archive.filename.lower().endswith(suffix):
  6232. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6233. forms.discard("")
  6234. return forms
  6235. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6236. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6237. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6238. from the plate recorded when the job was dispatched. Neither is touched:
  6239. ``on_print_complete`` pops both, which is why the finish-photo producer
  6240. calls this before its first await, while they are still there.
  6241. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6242. archive, or that it only knows by a name -- and on any error: the producer
  6243. calls this before the ``try`` that always releases the photo consumer, so
  6244. it must not raise.
  6245. """
  6246. try:
  6247. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6248. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6249. if archive_id is None:
  6250. return None, None
  6251. return archive_id, _print_plate_ids.get(archive_id)
  6252. except Exception:
  6253. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6254. return None, None
  6255. async def _max_z_for_current_print(
  6256. printer_id: int,
  6257. data: dict,
  6258. logger,
  6259. archive_id: int | None,
  6260. plate_id: int | None = None,
  6261. ) -> float | None:
  6262. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6263. This number becomes the target of a real Z move, so every step here refuses
  6264. rather than guesses. A height belonging to some *other* print is the one
  6265. failure that could drive the nozzle into the model: 20 mm carried onto a
  6266. 200 mm print would command the plate up through the part.
  6267. Three independent things therefore have to agree before a height is
  6268. returned:
  6269. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6270. when it started (see ``_bound_print``), never one found by name. A name
  6271. is not an identity: every plate of a multi-plate file shares one, and a
  6272. reprint reuses its archive row, so the newest archive with the right
  6273. name can be another plate of the same file. Support bundles show the
  6274. old name lookup doing exactly that (archive 288 for a print bound to
  6275. 169, 313 layers against 125), stopped only by the layer check below.
  6276. No binding, no move.
  6277. 2. **Identity.** The bound archive's name still has to be the finished
  6278. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6279. because the printer echoes spaces as underscores (#3240). Exact: not a
  6280. substring, and not the completion check's tolerance for a truncated
  6281. echo.
  6282. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6283. match the layer count the printer itself reported over MQTT for the print
  6284. that just ended. These come from genuinely different sources, so a
  6285. mismatch means the row is not this print, whatever its name says.
  6286. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6287. plate of a multi-plate file reuses the archive row without updating its
  6288. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6289. ``on_print_complete`` may already have flipped the status by the time we
  6290. run.
  6291. """
  6292. subtask_name = (data.get("subtask_name") or "").strip()
  6293. if not subtask_name:
  6294. # Nothing to identify the print by — refuse rather than fall back to
  6295. # "whatever ran last on this printer".
  6296. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6297. return None
  6298. if archive_id is None:
  6299. logger.info(
  6300. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6301. printer_id,
  6302. subtask_name,
  6303. )
  6304. return None
  6305. try:
  6306. from backend.app.models.archive import PrintArchive
  6307. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6308. async with async_session() as db:
  6309. result = await db.execute(
  6310. select(PrintArchive).where(
  6311. PrintArchive.id == archive_id,
  6312. PrintArchive.printer_id == printer_id,
  6313. PrintArchive.status.in_(("printing", "completed")),
  6314. PrintArchive.deleted_at.is_(None),
  6315. )
  6316. )
  6317. archive = result.scalar_one_or_none()
  6318. if archive is None or not archive.file_path:
  6319. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6320. return None
  6321. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6322. logger.warning(
  6323. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6324. printer_id,
  6325. archive_id,
  6326. subtask_name,
  6327. )
  6328. return None
  6329. client = printer_manager.get_client(printer_id)
  6330. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6331. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6332. logger.warning(
  6333. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6334. "— refusing to move the plate on a height that may not be this print's",
  6335. printer_id,
  6336. archive.id,
  6337. archive.total_layers,
  6338. reported_layers,
  6339. )
  6340. return None
  6341. # Stored relative to the data directory, like every other archive path
  6342. # (#3240: this read a `data_dir` setting that does not exist).
  6343. path = app_settings.base_dir / archive.file_path
  6344. plate = plate_id or archive.plate_id or 1
  6345. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6346. except Exception as e:
  6347. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6348. return None
  6349. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6350. """Raise the plate back into camera framing before the finish photo (#2547).
  6351. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6352. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6353. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6354. This commands an absolute ``G1 Z`` back to just above the last printed
  6355. layer.
  6356. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6357. clearance`` is a height the toolhead was physically at seconds earlier, so
  6358. it is inside the travel limits by construction and leaves the nozzle above
  6359. the part. It is also unambiguous across model families: Z is the
  6360. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6361. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6362. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6363. (#2579).
  6364. Returns True if the move was sent and waited out, False if it was skipped.
  6365. """
  6366. client = printer_manager.get_client(printer_id)
  6367. if client is None:
  6368. return False
  6369. # Re-read state immediately before commanding motion. If the queue has
  6370. # already started the next print, the printer is no longer ours to move.
  6371. state = getattr(client, "state", None)
  6372. if state is None or state.state != "FINISH":
  6373. logger.info(
  6374. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6375. printer_id,
  6376. getattr(state, "state", "unknown"),
  6377. )
  6378. return False
  6379. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6380. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6381. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6382. return False
  6383. logger.info(
  6384. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6385. printer_id,
  6386. target_z,
  6387. max_z_height,
  6388. _PLATE_RESTORE_CLEARANCE_MM,
  6389. _PLATE_RESTORE_SETTLE_SECONDS,
  6390. )
  6391. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6392. return True
  6393. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6394. """Drop the plate again after the finish photo (#2547).
  6395. Without this the user walks up to a finished print sitting just under the
  6396. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6397. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6398. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6399. print homes anyway.
  6400. """
  6401. client = printer_manager.get_client(printer_id)
  6402. state = getattr(client, "state", None) if client else None
  6403. if client is None or state is None or state.state != "FINISH":
  6404. return
  6405. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6406. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6407. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6408. """True if a queue item is about to take this printer (#2547).
  6409. The scheduler dispatches the next job the moment a print completes, and a
  6410. plate move interleaved with a print start is not a race worth having. The
  6411. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6412. this window; this closes the head of it.
  6413. """
  6414. try:
  6415. from backend.app.models.print_queue import PrintQueueItem
  6416. async with async_session() as db:
  6417. result = await db.execute(
  6418. select(PrintQueueItem.id)
  6419. .where(
  6420. PrintQueueItem.printer_id == printer_id,
  6421. PrintQueueItem.status.in_(("pending", "printing")),
  6422. )
  6423. .limit(1)
  6424. )
  6425. return result.scalar_one_or_none() is not None
  6426. except Exception as e:
  6427. # Fail closed: if we can't tell, don't move the plate.
  6428. logging.getLogger(__name__).debug(
  6429. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6430. )
  6431. return True
  6432. async def on_finish_photo_moment(printer_id: int, data: dict):
  6433. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6434. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6435. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6436. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6437. HMS halt, firmware variants). Grabs one frame via the same
  6438. external-camera / RTSP path the post-completion fallback uses, stores
  6439. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6440. ``_background_finish_photo`` consume the cached bytes when it runs.
  6441. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6442. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6443. set to Smooth (#1721). No force-on now means the user's explicit
  6444. timelapse=off in the slicer send dialog is respected.
  6445. """
  6446. logger = logging.getLogger(__name__)
  6447. trigger = data.get("trigger", "unknown")
  6448. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6449. logger.info(
  6450. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6451. printer_id,
  6452. trigger,
  6453. timelapse_was_active,
  6454. )
  6455. # If a timelapse is actively recording, skip the pre-capture — the
  6456. # post-completion path will extract the last frame from the recorded
  6457. # video, which still provides the best framing (toolhead parked,
  6458. # before bed drop) without the per-layer parking side effects.
  6459. if timelapse_was_active:
  6460. logger.info(
  6461. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6462. printer_id,
  6463. )
  6464. return
  6465. # #1790: register the producer-done event BEFORE the first await so the
  6466. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6467. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6468. # The `finally` below guarantees `set()` runs on every exit, including
  6469. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6470. producer_done = asyncio.Event()
  6471. _stage22_finish_in_flight[printer_id] = producer_done
  6472. # #3240: also before the first await. On the FINISH-state path
  6473. # `on_print_complete` is dispatched right behind us and pops both the
  6474. # print's archive binding and its plate; read here, they are still there.
  6475. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6476. # #2547: set once the plate has actually been raised, and read by the
  6477. # `finally` below. Declared out here so a failure anywhere after the move —
  6478. # a camera timeout, a DB error — still lowers the plate again.
  6479. restore_max_z: float | None = None
  6480. try:
  6481. async with async_session() as db:
  6482. from backend.app.api.routes.settings import get_setting
  6483. from backend.app.models.printer import Printer
  6484. capture_setting = await get_setting(db, "capture_finish_photo")
  6485. if capture_setting is not None and capture_setting.lower() != "true":
  6486. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6487. return
  6488. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6489. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6490. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6491. printer = result.scalar_one_or_none()
  6492. if printer is None:
  6493. logger.warning(
  6494. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6495. printer_id,
  6496. )
  6497. return
  6498. frame_bytes: bytes | None = None
  6499. # #2708: the banked frame arrives already rotated — it comes from
  6500. # `_capture_snapshot_for_notification`, which rotates before returning.
  6501. # Every other source below is a raw grab. Tracking which lets us store
  6502. # exactly one rotation in `_stage22_finish_frames` either way.
  6503. frame_already_rotated = False
  6504. # On the FINISH-state path the End G-code has already run, and two very
  6505. # different situations arrive here needing opposite answers.
  6506. #
  6507. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6508. # snippet may have ejected the plate — the scene in front of the camera
  6509. # is no longer the finished print, and no amount of moving the plate
  6510. # brings it back. Use the banked in-print frame instead.
  6511. #
  6512. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6513. # than the camera frames well, and the toolhead is parked out of the
  6514. # way. That is the *best* moment available on firmware that never emits
  6515. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6516. # back. Preferring the bank here unconditionally, as this code used to,
  6517. # is what shipped a mid-print photo with the toolhead over the part.
  6518. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6519. banked = _inprint_frame_bank.get(printer_id)
  6520. if banked:
  6521. frame_bytes = banked
  6522. frame_already_rotated = True
  6523. logger.info(
  6524. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6525. "frame (%d bytes) instead of a post-swap live grab",
  6526. len(banked),
  6527. )
  6528. else:
  6529. logger.warning(
  6530. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6531. "in-print bank is empty — falling back to a live grab, which may show a "
  6532. "swapped or empty plate",
  6533. printer_id,
  6534. )
  6535. # `restore_max_z` is set only once the plate is actually up, because the
  6536. # `finally` reads it to decide whether it owes a move back down.
  6537. #
  6538. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6539. # came up empty above: that machine may have just ejected its plate, and
  6540. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6541. # taking for a photo of a bed we already know may be bare.
  6542. if (
  6543. frame_bytes is None
  6544. and trigger == "finish_state"
  6545. and restore_plate_enabled
  6546. and not print_dispatch_context.end_gcode_injected(printer_id)
  6547. ):
  6548. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6549. if wants_restore is None:
  6550. logger.info(
  6551. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6552. printer_id,
  6553. )
  6554. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6555. logger.info(
  6556. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6557. printer_id,
  6558. )
  6559. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6560. restore_max_z = wants_restore
  6561. # Chamber light for the live capture below (#1655). The banked frame
  6562. # above was taken without it, like every in-print bank.
  6563. async with camera_light(printer if frame_bytes is None else None):
  6564. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6565. from backend.app.api.routes.camera import live_frame_for_capture
  6566. from backend.app.services.external_camera import capture_frame
  6567. # #2707: this used to collide with the live view and fail, which is
  6568. # how finish-photo notifications went out with no image attached.
  6569. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6570. defer, buffered = live_frame_for_capture(printer_id)
  6571. if defer:
  6572. frame_bytes = buffered
  6573. else:
  6574. frame_bytes = await capture_frame(
  6575. printer.external_camera_url,
  6576. printer.external_camera_type or "mjpeg",
  6577. snapshot_url=printer.external_camera_snapshot_url,
  6578. )
  6579. if frame_bytes:
  6580. logger.info(
  6581. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6582. len(frame_bytes),
  6583. )
  6584. elif frame_bytes is None:
  6585. from backend.app.api.routes.camera import get_buffered_frame
  6586. buffered = get_buffered_frame(printer_id)
  6587. if buffered:
  6588. frame_bytes = buffered
  6589. logger.info(
  6590. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6591. len(frame_bytes),
  6592. )
  6593. else:
  6594. from backend.app.services.camera import capture_camera_frame_bytes
  6595. frame_bytes = await capture_camera_frame_bytes(
  6596. ip_address=printer.ip_address,
  6597. access_code=printer.access_code,
  6598. model=printer.model,
  6599. timeout=15,
  6600. )
  6601. if frame_bytes:
  6602. logger.info(
  6603. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6604. len(frame_bytes),
  6605. )
  6606. if frame_bytes:
  6607. if not frame_already_rotated:
  6608. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6609. _stage22_finish_frames[printer_id] = frame_bytes
  6610. else:
  6611. logger.warning(
  6612. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6613. printer_id,
  6614. )
  6615. except Exception as e:
  6616. logger.warning(
  6617. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6618. printer_id,
  6619. e,
  6620. )
  6621. finally:
  6622. # #2547: we raised the plate, so we own lowering it — including when the
  6623. # capture above failed or threw partway through.
  6624. if restore_max_z is not None:
  6625. try:
  6626. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6627. except Exception as e:
  6628. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6629. # #1790: always unblock the consumer's bounded wait — whether we stored
  6630. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6631. # dict entry by the consumer doesn't affect signalling.
  6632. producer_done.set()
  6633. def _subtask_name_from_filename(filename: str) -> str:
  6634. """Recover the subtask name a print command would have carried for *filename*.
  6635. The dispatcher derives the printer-facing subtask name from the archive's
  6636. file name, so stripping the extensions back off gives the value MQTT echoes
  6637. on completion. Only the two extensions Bambuddy actually stores are removed,
  6638. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6639. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6640. """
  6641. name = PurePosixPath(filename).name
  6642. for suffix in (".3mf", ".gcode"):
  6643. if name.lower().endswith(suffix):
  6644. name = name[: -len(suffix)]
  6645. return name
  6646. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6647. """Whether the subtask name is the printed 3MF's own file name.
  6648. A print started from the printer's screen reports the same full name, with
  6649. its extension, as both subtask and file (#3009). A dispatched print reports
  6650. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6651. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6652. """
  6653. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6654. return False
  6655. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6656. # How the printer marks a subtask name it had to cut short. Observed on real
  6657. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6658. # (a name with multibyte characters came back at 98), so match the marker
  6659. # rather than a length.
  6660. _SUBTASK_TRUNCATION_MARKER = "..."
  6661. def _normalise_subtask_name(name: str) -> str:
  6662. """Canonical form for comparing a dispatched name against MQTT's echo.
  6663. The printer does not echo the name back verbatim: it substitutes
  6664. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6665. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6666. The 3MF lookup in this module has always known that -- it builds
  6667. space-to-underscore variants of every candidate filename, and its
  6668. directory search normalises both sides before comparing. This exists so
  6669. the completion check reads the same rule from the same place instead of
  6670. growing its own, which is exactly how it came to disagree (#2829).
  6671. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6672. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6673. are dropped after the substitution so both sides agree (#3241).
  6674. """
  6675. return name.strip().replace(" ", "_").strip("_").casefold()
  6676. def _subtask_names_match(expected: str, observed: str) -> bool:
  6677. """Whether two subtask names describe the same print.
  6678. Beyond the space/underscore substitution, the printer truncates long names
  6679. and marks the cut with ``...``. A truncated echo has to count as a match or
  6680. every print with a long name strands its queue item the same way.
  6681. """
  6682. expected_n = _normalise_subtask_name(expected)
  6683. observed_n = _normalise_subtask_name(observed)
  6684. if expected_n == observed_n:
  6685. return True
  6686. # Either side can be the truncated one: the printer truncates what it
  6687. # echoes, and an archive whose own filename was recorded from a previous
  6688. # truncated echo carries the marker too.
  6689. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6690. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6691. continue
  6692. # The full side has lost its edge underscores; a cut that lands right
  6693. # after one keeps it, so drop it here too (#3241). Nothing left before
  6694. # the marker is no evidence of anything, and must not match every name.
  6695. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6696. if kept and full.startswith(kept):
  6697. return True
  6698. return False
  6699. async def _queue_item_dispatched_name(db, item) -> str:
  6700. """The subtask name *item* was dispatched under, or "" when unknowable.
  6701. A row with no archive, or an archive with no file name, is unverifiable
  6702. rather than wrong; every caller answers that with its permissive branch.
  6703. """
  6704. if item.archive_id is None:
  6705. return ""
  6706. from backend.app.models.archive import PrintArchive
  6707. archive = await db.get(PrintArchive, item.archive_id)
  6708. if archive is None or not archive.filename:
  6709. return ""
  6710. return _subtask_name_from_filename(archive.filename)
  6711. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6712. """Whether this completion event is plausibly about *item*'s print.
  6713. The caller finds its queue row by printer and ``status='printing'`` alone,
  6714. which is all a completion event gives it -- there is no run identifier in
  6715. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6716. completion delivered for this printer closes whichever row happens to be
  6717. printing, however unrelated. Comparing the subtask name against the archive
  6718. the row was dispatched with costs one primary-key load and rules that out.
  6719. Deliberately permissive: it answers False only on a positive disagreement
  6720. between two names we actually have. A row with no archive, an archive with
  6721. no file name, or an event with no subtask name is unverifiable rather than
  6722. wrong, and refusing those would strand the item in ``printing`` and wedge
  6723. the printer's queue -- a worse failure than the one being prevented.
  6724. """
  6725. observed = (data.get("subtask_name") or "").strip()
  6726. if not observed or item.archive_id is None:
  6727. return True
  6728. from backend.app.models.archive import PrintArchive
  6729. archive = await db.get(PrintArchive, item.archive_id)
  6730. if archive is None or not archive.filename:
  6731. return True
  6732. expected = _subtask_name_from_filename(archive.filename)
  6733. if not expected or _subtask_names_match(expected, observed):
  6734. return True
  6735. logging.getLogger(__name__).warning(
  6736. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6737. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6738. "printing rather than closing a run this event is not about.",
  6739. item.id,
  6740. expected,
  6741. archive.id,
  6742. archive.filename,
  6743. observed,
  6744. )
  6745. return False
  6746. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6747. """Spend the 3MF download cache on a still-empty fallback archive.
  6748. ``on_print_complete`` drops the cache as its first act, which deletes the
  6749. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6750. print ran and the archive never got one, this is the last moment those bytes
  6751. exist (#2957).
  6752. """
  6753. logger = logging.getLogger(__name__)
  6754. names = [
  6755. n
  6756. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6757. if n
  6758. ]
  6759. for name in names:
  6760. try:
  6761. cached = get_cached_3mf(printer_id, name)
  6762. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6763. return
  6764. except Exception as e:
  6765. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6766. async def _cleanup_sd_card_after_print(
  6767. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6768. ) -> None:
  6769. """Delete a finished print's file from the printer's SD card."""
  6770. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6771. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6772. # auto-start files found in root on power cycle, causing ghost prints.
  6773. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6774. try:
  6775. if subtask_name:
  6776. archive_filename: str | None = None
  6777. async with async_session() as db:
  6778. from backend.app.models.archive import PrintArchive
  6779. from backend.app.models.printer import Printer
  6780. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6781. printer = result.scalar_one_or_none()
  6782. if archive_id:
  6783. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6784. archive_filename = archive_row.scalar_one_or_none()
  6785. if printer:
  6786. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6787. from backend.app.utils.filename import derive_remote_filename
  6788. # Primary candidate: the exact path the dispatcher uploaded to
  6789. # (derived from archive.filename via the same rule as upload).
  6790. # Without it, a library row that ended up with a doubled
  6791. # .gcode.3mf (#1542) leaves the real file behind because the
  6792. # subtask_name + ext fallbacks below don't match what's on the
  6793. # SD card. Fallbacks remain for archive-less prints (subtask
  6794. # never resolved to an archive) and for older naming variants.
  6795. candidate_paths: list[str] = []
  6796. if archive_filename:
  6797. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6798. for ext in (".3mf", ".gcode"):
  6799. fallback = f"/{subtask_name}{ext}"
  6800. if fallback not in candidate_paths:
  6801. candidate_paths.append(fallback)
  6802. # Three outcomes track across all candidates so the final log
  6803. # line reflects what actually happened. The A1 in #1721 always
  6804. # ends here with ``any_not_found=True`` and the others False
  6805. # — its firmware auto-cleans the SD card before our cleanup
  6806. # runs, every candidate FTP-DELE returns 550, and the old
  6807. # code burned 3 retries × 2 s × 3 candidates per print
  6808. # logging a misleading "may linger" WARNING on a successful
  6809. # print.
  6810. any_deleted = False
  6811. any_real_failure = False
  6812. any_not_found = False
  6813. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6814. for remote_path in candidate_paths:
  6815. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6816. logger.info(
  6817. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6818. remote_path,
  6819. printer.name,
  6820. )
  6821. continue
  6822. # Retry only the FAILED case — 550 NOT_FOUND will never
  6823. # recover by waiting, so a "file isn't here" answer
  6824. # advances immediately to the next candidate without
  6825. # consuming the retry budget.
  6826. for attempt in range(1, 4):
  6827. try:
  6828. delete_result = await delete_file_async(
  6829. printer.ip_address,
  6830. printer.access_code,
  6831. remote_path,
  6832. printer_model=printer.model,
  6833. )
  6834. except Exception as e:
  6835. delete_result = DeleteResult.FAILED
  6836. logger.warning(
  6837. "SD card cleanup attempt %d/3 raised for %s: %s",
  6838. attempt,
  6839. remote_path,
  6840. e,
  6841. )
  6842. if delete_result == DeleteResult.DELETED:
  6843. any_deleted = True
  6844. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6845. break
  6846. if delete_result == DeleteResult.NOT_FOUND:
  6847. any_not_found = True
  6848. break # 550 will not recover; try next candidate
  6849. # FAILED: real error — retry with backoff, then give up
  6850. if attempt < 3:
  6851. await asyncio.sleep(2)
  6852. else:
  6853. any_real_failure = True
  6854. logger.warning(
  6855. "SD card cleanup failed after 3 attempts for %s "
  6856. "(network/auth/transient error — file may linger on SD card)",
  6857. remote_path,
  6858. )
  6859. if not any_deleted and not any_real_failure and any_not_found:
  6860. # Every candidate said "not here." Either the printer
  6861. # firmware swept the SD card itself (common on A1) or the
  6862. # dispatcher's upload path doesn't match our candidate
  6863. # rule. Either way: nothing to clean up, no warning.
  6864. logger.debug(
  6865. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6866. "(printer likely self-cleaned)",
  6867. printer.name,
  6868. )
  6869. except Exception as e:
  6870. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6871. async def on_print_complete(printer_id: int, data: dict):
  6872. """Handle print completion - update the archive status."""
  6873. import time
  6874. logger = logging.getLogger(__name__)
  6875. start_time = time.time()
  6876. def log_timing(section: str):
  6877. elapsed = time.time() - start_time
  6878. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6879. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6880. # A kill-switch stop sends its provider notification immediately. Keep the
  6881. # task so the later notification path can await it and avoid a duplicate;
  6882. # if that immediate attempt failed, the regular completion path retries.
  6883. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6884. # Last chance before the bytes go: if this print's archive is still an empty
  6885. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6886. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6887. # below deletes the file (#2957).
  6888. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6889. # A pending cool-off retry has nothing left to recover for — the cache is
  6890. # about to be dropped and the print is over.
  6891. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6892. if retry_task and not retry_task.done():
  6893. retry_task.cancel()
  6894. # Drop the 3MF download cache for this printer (#972). The print is over,
  6895. # nothing else legitimately needs the bytes; keeping them would only risk
  6896. # handing a stale file to the next print if it reuses the same name.
  6897. clear_3mf_cache(printer_id)
  6898. try:
  6899. ws_data = {
  6900. "status": data.get("status"),
  6901. "filename": data.get("filename"),
  6902. "subtask_name": data.get("subtask_name"),
  6903. "timelapse_was_active": data.get("timelapse_was_active"),
  6904. }
  6905. await ws_manager.send_print_complete(printer_id, ws_data)
  6906. log_timing("WebSocket send_print_complete")
  6907. except Exception as e:
  6908. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6909. # Capture user info before clearing (needed for print log entry)
  6910. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6911. # Clear current print user tracking (Issue #206)
  6912. printer_manager.clear_current_print_user(printer_id)
  6913. # If the user explicitly stopped this print from the queue UI the printer will
  6914. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6915. # correct "print stopped" notification/email is sent instead of a failure alert.
  6916. _raw_status = data.get("status", "completed")
  6917. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6918. logger.info(
  6919. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6920. _raw_status,
  6921. printer_id,
  6922. )
  6923. data = {**data, "status": "cancelled"}
  6924. _user_stopped_printers.discard(printer_id)
  6925. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6926. # may have left material on the bed: a user can cancel ten hours into a
  6927. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6928. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6929. # `_user_stopped_printers` is only populated when the user stops via the
  6930. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6931. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6932. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6933. # Auto Off power cycles and Bambuddy restarts.
  6934. try:
  6935. notify_live_activities.print_finished(printer_id, data)
  6936. except Exception:
  6937. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  6938. _final_status = data.get("status", "completed")
  6939. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6940. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6941. # MQTT relay - publish print complete
  6942. try:
  6943. printer_info = printer_manager.get_printer(printer_id)
  6944. if printer_info:
  6945. await mqtt_relay.on_print_complete(
  6946. printer_id,
  6947. printer_info.name,
  6948. printer_info.serial_number,
  6949. data.get("filename", ""),
  6950. data.get("subtask_name", ""),
  6951. data.get("status", "completed"),
  6952. )
  6953. except Exception:
  6954. pass # Don't fail print complete callback if MQTT fails
  6955. filename = data.get("filename", "")
  6956. subtask_name = data.get("subtask_name", "")
  6957. if not filename and not subtask_name:
  6958. logger.warning("Print complete without filename or subtask_name")
  6959. return
  6960. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6961. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6962. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6963. # Find the archive for this print
  6964. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6965. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6966. archive_id = None
  6967. for key in possible_keys:
  6968. archive_id = _active_prints.pop(key, None)
  6969. if archive_id:
  6970. logger.info("Found archive %s with key %s", archive_id, key)
  6971. # Also clean up any other keys pointing to this archive
  6972. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6973. for k in keys_to_remove:
  6974. _active_prints.pop(k, None)
  6975. break
  6976. # The archive bound when the print started, before the name search below.
  6977. # Only this one may give the finish-photo plate restore a height (#3240):
  6978. # the search matches names by substring.
  6979. bound_archive_id = archive_id
  6980. if not archive_id:
  6981. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6982. async with async_session() as db:
  6983. from backend.app.models.archive import PrintArchive
  6984. # Try matching by subtask_name (stored as print_name) first
  6985. if subtask_name:
  6986. result = await db.execute(
  6987. select(PrintArchive)
  6988. .where(PrintArchive.printer_id == printer_id)
  6989. .where(PrintArchive.status == "printing")
  6990. .where(
  6991. or_(
  6992. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6993. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6994. )
  6995. )
  6996. .order_by(PrintArchive.created_at.desc())
  6997. .limit(1)
  6998. )
  6999. archive = result.scalar_one_or_none()
  7000. if archive:
  7001. archive_id = archive.id
  7002. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7003. # Also try by filename
  7004. if not archive_id and filename:
  7005. result = await db.execute(
  7006. select(PrintArchive)
  7007. .where(PrintArchive.printer_id == printer_id)
  7008. .where(PrintArchive.filename == filename)
  7009. .where(PrintArchive.status == "printing")
  7010. .order_by(PrintArchive.created_at.desc())
  7011. .limit(1)
  7012. )
  7013. archive = result.scalar_one_or_none()
  7014. if archive:
  7015. archive_id = archive.id
  7016. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  7017. log_timing("SD card cleanup")
  7018. # Update queue item status early — must run before the archive_id early-return
  7019. # so queue items don't get stuck in "printing" when archive lookup fails.
  7020. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7021. queue_item_id = None
  7022. billing_run_id: str | None = None
  7023. billing_user_id: int | None = None
  7024. billing_cost_center_id: int | None = None
  7025. billing_plate_id: int | None = None
  7026. queue_status = None
  7027. queue_auto_off = False
  7028. try:
  7029. from backend.app.core.database import run_with_retry
  7030. from backend.app.models.print_queue import PrintQueueItem
  7031. async def _update_queue_status(db):
  7032. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7033. nonlocal queue_item_id, queue_status, queue_auto_off
  7034. result = await db.execute(
  7035. select(PrintQueueItem)
  7036. .where(PrintQueueItem.printer_id == printer_id)
  7037. .where(PrintQueueItem.status == "printing")
  7038. )
  7039. printing_items = list(result.scalars().all())
  7040. if len(printing_items) > 1:
  7041. logger.warning(
  7042. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7043. printer_id,
  7044. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7045. )
  7046. item = printing_items[0] if printing_items else None
  7047. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7048. return
  7049. if item:
  7050. queue_status = data.get("status", "completed")
  7051. # MQTT sends "aborted" for cancelled prints; normalise to
  7052. # "cancelled" so it matches the queue schema Literal.
  7053. if queue_status == "aborted":
  7054. queue_status = "cancelled"
  7055. item.status = queue_status
  7056. item.completed_at = datetime.now(timezone.utc)
  7057. if queue_status == "failed" and not item.error_message:
  7058. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7059. # Bump usage counters on the source library file so admins can
  7060. # sort by "last printed" and (eventually) auto-purge stale
  7061. # files — #1008.
  7062. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7063. await db.commit()
  7064. queue_item_id = item.id
  7065. billing_run_id = item.billing_run_id
  7066. billing_user_id = item.created_by_id
  7067. billing_cost_center_id = item.cost_center_id
  7068. billing_plate_id = item.plate_id
  7069. queue_auto_off = item.auto_off_after
  7070. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7071. await run_with_retry(_update_queue_status, label="queue status update")
  7072. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7073. # their own sessions and have their own error handling — no retry needed.
  7074. if queue_item_id is not None:
  7075. # Batch orders (#342): this run may have been the last one an order
  7076. # owed. Re-evaluate here rather than lazily on read, so a finished
  7077. # order reports itself complete without someone opening the page.
  7078. try:
  7079. from backend.app.services.print_batch import refresh_batch_status_for_item
  7080. async with async_session() as db:
  7081. await refresh_batch_status_for_item(db, queue_item_id)
  7082. await db.commit()
  7083. except Exception as e:
  7084. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7085. # MQTT relay - publish queue job completed
  7086. try:
  7087. printer_info = printer_manager.get_printer(printer_id)
  7088. await mqtt_relay.on_queue_job_completed(
  7089. job_id=queue_item_id,
  7090. filename=filename or subtask_name,
  7091. printer_id=printer_id,
  7092. printer_name=printer_info.name if printer_info else "Unknown",
  7093. status=queue_status,
  7094. )
  7095. except Exception:
  7096. pass # Don't fail if MQTT fails
  7097. # Check if queue is now empty and send notification
  7098. try:
  7099. from sqlalchemy import func as sa_func
  7100. async with async_session() as db:
  7101. count_result = await db.execute(
  7102. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7103. )
  7104. pending_count = count_result.scalar() or 0
  7105. if pending_count == 0:
  7106. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7107. completed_result = await db.execute(
  7108. select(sa_func.count(PrintQueueItem.id)).where(
  7109. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7110. PrintQueueItem.completed_at >= today_start,
  7111. )
  7112. )
  7113. completed_count = completed_result.scalar() or 1
  7114. await notification_service.on_queue_completed(
  7115. completed_count=completed_count,
  7116. db=db,
  7117. )
  7118. except Exception:
  7119. pass # Don't fail if notification fails
  7120. # Handle auto_off_after - power off printer if the queue item opted
  7121. # in. Delegates to the smart-plug manager so the off honours each
  7122. # plug's configured strategy (time delay or temperature threshold),
  7123. # is cancelled if the printer starts printing again, and never cuts
  7124. # power on a loaded print (#1890). Previously an inline block here
  7125. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7126. # timeout regardless of print state — cutting a touchscreen reprint.
  7127. if queue_auto_off:
  7128. try:
  7129. async with async_session() as db:
  7130. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7131. except Exception as e:
  7132. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7133. except Exception as e:
  7134. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7135. log_timing("Queue item update")
  7136. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7137. # Must run before archive_id early-return so it fires for all prints (including
  7138. # prints started from BambuStudio/touchscreen that have no archive).
  7139. if data.get("status") == "completed":
  7140. try:
  7141. from backend.app.api.routes.settings import get_setting
  7142. async with async_session() as db:
  7143. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7144. threshold = float(threshold_str) if threshold_str else 35.0
  7145. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7146. async with async_session() as db:
  7147. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7148. if providers:
  7149. _bed_cool_waiters[printer_id] = {
  7150. "threshold": threshold,
  7151. "filename": filename or subtask_name or "",
  7152. "registered_at": time.time(),
  7153. }
  7154. logger.info(
  7155. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7156. printer_id,
  7157. threshold,
  7158. )
  7159. else:
  7160. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7161. except Exception as e:
  7162. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7163. # Capture the slicer estimate before usage tracking runs. The tracker may
  7164. # update archive.cost with this run's measured cost; billing partial runs
  7165. # against that already-partial value would discount the charge twice.
  7166. billing_planned_grams: float | None = None
  7167. billing_base_cost: float | None = None
  7168. if archive_id:
  7169. try:
  7170. async with async_session() as db:
  7171. from backend.app.models.archive import PrintArchive
  7172. billing_archive = await db.get(PrintArchive, archive_id)
  7173. if billing_archive:
  7174. billing_path = (
  7175. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7176. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7177. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7178. billing_archive,
  7179. billing_path,
  7180. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7181. )
  7182. except Exception as e:
  7183. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7184. # --- Track filament consumption (must run before archive_id early-return so usage
  7185. # is recorded even when auto-archive is disabled) ---
  7186. usage_results: list[dict] = []
  7187. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7188. stored_ams_mapping = data.get("ams_mapping")
  7189. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  7190. if not stored_ams_mapping and archive_id:
  7191. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  7192. # Always drain the plate_id register on completion — the session already
  7193. # consumed it at print-start injection; leaving it would leak into the next
  7194. # print on the same archive_id (rare but possible with reprints) (#1697).
  7195. # Capture the popped value so the completion notification can scope the
  7196. # archive-level (summed-across-plates per #1593) filament + time totals
  7197. # down to the single plate that was actually printed (#1785).
  7198. notify_plate_id: int | None = None
  7199. if archive_id:
  7200. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7201. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7202. try:
  7203. async with async_session() as db:
  7204. from backend.app.api.routes.settings import get_setting
  7205. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7206. if not _spoolman_on or _spoolman_on.lower() != "true":
  7207. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7208. async with async_session() as db:
  7209. usage_results = await usage_on_print_complete(
  7210. printer_id,
  7211. data,
  7212. printer_manager,
  7213. db,
  7214. archive_id=archive_id,
  7215. ams_mapping=stored_ams_mapping,
  7216. )
  7217. if usage_results:
  7218. await ws_manager.broadcast(
  7219. {
  7220. "type": "spool_usage_logged",
  7221. "printer_id": printer_id,
  7222. "usage": usage_results,
  7223. }
  7224. )
  7225. log_timing("Usage tracker")
  7226. except Exception as e:
  7227. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7228. # Drop the print-start context unconditionally — the Spoolman branch above
  7229. # skips the internal tracker entirely, so nothing else would clear what
  7230. # print start captured, and a row surviving its print would be restored
  7231. # onto the next one after a restart.
  7232. try:
  7233. from backend.app.services.usage_tracker import discard_session
  7234. async with async_session() as db:
  7235. await discard_session(db, printer_id)
  7236. except Exception as e:
  7237. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7238. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7239. if archive_id:
  7240. if data.get("status") == "completed":
  7241. try:
  7242. await _report_spoolman_usage(printer_id, archive_id)
  7243. log_timing("Spoolman usage report")
  7244. except Exception as e:
  7245. logger.warning("Spoolman usage reporting failed: %s", e)
  7246. else:
  7247. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7248. try:
  7249. async with async_session() as db:
  7250. await _cleanup_spoolman_tracking(
  7251. printer_id,
  7252. archive_id,
  7253. db,
  7254. last_layer_num=data.get("last_layer_num"),
  7255. last_progress=data.get("last_progress"),
  7256. )
  7257. except Exception as e:
  7258. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7259. log_timing("Filament usage tracking")
  7260. if not archive_id:
  7261. # The printer's own calibration run has no archive by design, so this
  7262. # arrives here every time one finishes. Returning before the no-archive
  7263. # notification keeps a calibration from being announced as a finished
  7264. # print. Everything above this point has already run — the plate-clear
  7265. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7266. # notification is skipped.
  7267. if is_internal_printer_job(filename, subtask_name):
  7268. logger.info(
  7269. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7270. filename,
  7271. subtask_name,
  7272. )
  7273. return
  7274. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7275. # Still send print-complete/failed/stopped notifications even without an archive.
  7276. # Try to enrich with queue/library-file data so user-specific emails work too.
  7277. async def _notify_no_archive():
  7278. try:
  7279. async with async_session() as db:
  7280. from backend.app.models.library import LibraryFile
  7281. from backend.app.models.print_queue import PrintQueueItem
  7282. from backend.app.models.printer import Printer
  7283. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7284. printer_obj = result.scalar_one_or_none()
  7285. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7286. # Only the queue item this completion itself closed (the
  7287. # reconciliation above, which checks the run belongs to it).
  7288. # A print started outside Bambuddy closed none, and must not
  7289. # borrow an earlier job's owner, email or times.
  7290. no_archive_data: dict | None = None
  7291. try:
  7292. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7293. if queue_item:
  7294. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7295. # How long it really ran, as the archive path reports it (#1198).
  7296. started = to_naive_utc(queue_item.started_at)
  7297. ended = to_naive_utc(queue_item.completed_at)
  7298. if started and ended and (ended - started).total_seconds() > 0:
  7299. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7300. # Estimated time: the queue item caches it from its
  7301. # archive or library file; otherwise read the library
  7302. # file's metadata (LibraryFile has no column for it).
  7303. if queue_item.print_time_seconds:
  7304. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7305. elif queue_item.library_file_id:
  7306. lib_result = await db.execute(
  7307. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7308. )
  7309. lib_file = lib_result.scalar_one_or_none()
  7310. estimate = (
  7311. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7312. )
  7313. if estimate:
  7314. no_archive_data["print_time_seconds"] = estimate
  7315. except Exception as lookup_err:
  7316. logger.debug(
  7317. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7318. )
  7319. # Enrich with usage tracker results (captured in enclosing scope)
  7320. if usage_results:
  7321. if no_archive_data is None:
  7322. no_archive_data = {}
  7323. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7324. if total_from_usage > 0:
  7325. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7326. no_archive_data["usage_results"] = usage_results
  7327. # Try MQTT remaining_time for print duration when no queue/library data
  7328. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7329. mqtt_remaining = data.get("remaining_time")
  7330. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7331. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7332. ps = data.get("status", "completed")
  7333. logger.info(
  7334. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7335. )
  7336. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7337. await notification_service.on_print_complete(
  7338. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7339. )
  7340. else:
  7341. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7342. # Send user-specific email if we have a created_by_id
  7343. if no_archive_data and no_archive_data.get("created_by_id"):
  7344. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7345. await _dispatch_user_print_email(
  7346. ps,
  7347. no_archive_data["created_by_id"],
  7348. p_name,
  7349. raw_filename,
  7350. db,
  7351. )
  7352. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7353. except Exception as e:
  7354. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7355. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7356. return
  7357. log_timing("Archive lookup")
  7358. # Update archive status
  7359. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7360. try:
  7361. async with async_session() as db:
  7362. service = ArchiveService(db)
  7363. status = data.get("status", "completed")
  7364. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7365. if hms_errors:
  7366. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7367. failure_reason = derive_failure_reason(status, hms_errors)
  7368. if data.get("_reconciled"):
  7369. # A reconciled completion closes out a stale archive at
  7370. # reconnect — it is not a user action, so don't mislabel it
  7371. # "userCancelled". It shares the stale-cleanup path's key
  7372. # (issue #2974) and records that the real end time is unknown,
  7373. # which is also why its logged duration is 0 (#2592).
  7374. failure_reason = "noStatusUpdate"
  7375. if failure_reason:
  7376. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7377. elif status == "failed" and hms_errors:
  7378. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7379. await service.update_archive_status(
  7380. archive_id,
  7381. status=status,
  7382. completed_at=(
  7383. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7384. ),
  7385. failure_reason=failure_reason,
  7386. )
  7387. logger.info(
  7388. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7389. )
  7390. await ws_manager.send_archive_updated(
  7391. {
  7392. "id": archive_id,
  7393. "status": status,
  7394. }
  7395. )
  7396. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7397. # MQTT relay - publish archive updated
  7398. try:
  7399. await mqtt_relay.on_archive_updated(
  7400. archive_id=archive_id,
  7401. print_name=filename or subtask_name,
  7402. status=status,
  7403. )
  7404. except Exception:
  7405. pass # Don't fail if MQTT fails
  7406. except Exception as e:
  7407. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7408. # Continue with other operations even if archive update fails
  7409. log_timing("Archive status update")
  7410. # Apply finance wallet charge or release reservations once. For all partial
  7411. # terminal states (failed, aborted at the printer display, or cancelled via
  7412. # Bambuddy) use this run's measured spool delta, falling back to the last
  7413. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7414. # estimate and therefore cannot represent an interrupted run.
  7415. try:
  7416. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7417. async with async_session() as db:
  7418. from backend.app.models.archive import PrintArchive
  7419. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7420. archive = await db.get(PrintArchive, archive_id)
  7421. if archive and billing_run_id is None:
  7422. billing_run_id = getattr(archive, "billing_run_id", None)
  7423. if archive and archive.created_by_id is None and _print_user_info:
  7424. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7425. await db.flush()
  7426. run_status = data.get("status", "completed")
  7427. last_progress = data.get("last_progress")
  7428. if last_progress is None:
  7429. last_progress = data.get("progress")
  7430. actual_run_grams = _compute_run_filament_grams(
  7431. run_status,
  7432. billing_planned_grams,
  7433. last_progress,
  7434. usage_results,
  7435. )
  7436. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7437. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7438. charged = await apply_print_charge_for_archive(
  7439. db,
  7440. archive_id,
  7441. charged_user_id=billing_user_id,
  7442. cost_center_id=(
  7443. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7444. ),
  7445. print_queue_id=queue_item_id,
  7446. print_run_id=billing_run_id,
  7447. base_cost_override=billing_base_cost,
  7448. filament_usage=filament_usage,
  7449. )
  7450. await db.commit()
  7451. if charged:
  7452. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7453. except Exception as e:
  7454. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7455. printer_info = printer_manager.get_printer(printer_id)
  7456. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7457. billing_filename = filename or subtask_name or "Unknown"
  7458. billing_error = str(e)
  7459. try:
  7460. await ws_manager.broadcast(
  7461. {
  7462. "type": "billing_charge_failed",
  7463. "printer_id": printer_id,
  7464. "printer_name": billing_printer_name,
  7465. "filename": billing_filename,
  7466. "archive_id": archive_id,
  7467. }
  7468. )
  7469. except Exception as notification_error:
  7470. logger.error(
  7471. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7472. archive_id,
  7473. notification_error,
  7474. )
  7475. async def _notify_billing_charge_failed() -> None:
  7476. try:
  7477. async with async_session() as notification_db:
  7478. await notification_service.on_billing_charge_failed(
  7479. printer_id,
  7480. billing_printer_name,
  7481. billing_filename,
  7482. archive_id,
  7483. billing_error,
  7484. notification_db,
  7485. )
  7486. except Exception as provider_error:
  7487. logger.error(
  7488. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7489. archive_id,
  7490. provider_error,
  7491. exc_info=True,
  7492. )
  7493. spawn_background_task(
  7494. _notify_billing_charge_failed(),
  7495. name=f"billing-charge-failed-{archive_id}",
  7496. )
  7497. log_timing("Finance charge update")
  7498. # Write independent print log entry (separate table, never touches archives)
  7499. try:
  7500. async with async_session() as db:
  7501. from backend.app.models.archive import PrintArchive
  7502. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7503. archive = await db.get(PrintArchive, archive_id)
  7504. if archive:
  7505. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7506. # source archive row rather than creating a new one, so an
  7507. # archive that was auto-created from a printer-initiated
  7508. # print (created_by_id=NULL) would otherwise stay unattributed
  7509. # forever. When we have a print-session user AND the archive
  7510. # has no attribution yet, credit the current user. Never
  7511. # overwrite an existing attribution — the original uploader
  7512. # keeps ownership.
  7513. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7514. if archive.created_by_id is None and _print_user_id is not None:
  7515. archive.created_by_id = _print_user_id
  7516. p_info = printer_manager.get_printer(printer_id)
  7517. # Per-run actuals — written to PrintLogEntry so stats reflect
  7518. # what THIS print actually used, not the source archive's
  7519. # first-run values (#1378). Helper handles the partial-print
  7520. # math (failed / cancelled / stopped get scaled to progress
  7521. # or to tracked spool deltas).
  7522. _run_status = data.get("status", "completed")
  7523. # #2614: scope the per-run estimate to the printed plate. For a
  7524. # multi-plate 3MF dispatched one plate at a time, the archive's
  7525. # filament/cost are the whole-file totals; the PrintLogEntry must
  7526. # reflect only this plate. No effect on single-plate archives (the
  7527. # plate estimate equals the whole-file value) or on the tracker
  7528. # path (measured spool deltas win in _compute_run_filament_grams).
  7529. _est_full_path = (
  7530. app_settings.base_dir / archive.file_path if archive.file_path else None
  7531. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7532. # The plate that printed, as billing reads it: a reprint of
  7533. # another plate must not log the archive's first plate.
  7534. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7535. archive,
  7536. _est_full_path,
  7537. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7538. )
  7539. _run_grams = _compute_run_filament_grams(
  7540. _run_status,
  7541. _est_grams,
  7542. data.get("last_progress", data.get("progress")),
  7543. usage_results,
  7544. )
  7545. # Per-run cost — prefer usage_results sum. For partial prints
  7546. # we deliberately skip the topup-to-estimate logic in
  7547. # usage_tracker (which assumes the print completed); the raw
  7548. # tracked-spool sum is closer to what THIS run actually cost.
  7549. _run_cost: float | None = None
  7550. if usage_results:
  7551. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7552. if _run_cost is None and _run_status == "completed":
  7553. _run_cost = _est_cost
  7554. from backend.app.models.printer import Printer as _Printer
  7555. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7556. run_entry = await write_log_entry(
  7557. db,
  7558. archive_id=archive.id,
  7559. # Captured by _update_queue_status above; None for
  7560. # printer-initiated prints with no queue row. Batch
  7561. # cost/energy roll-up joins on it (#342).
  7562. queue_item_id=queue_item_id,
  7563. status=_run_status,
  7564. print_name=archive.print_name,
  7565. printer_name=p_info.name if p_info else None,
  7566. printer_id=printer_id,
  7567. started_at=archive.started_at,
  7568. completed_at=archive.completed_at,
  7569. filament_type=archive.filament_type,
  7570. filament_color=archive.filament_color,
  7571. filament_used_grams=_run_grams,
  7572. cost=_run_cost,
  7573. wear_cost_per_hour=_wear_rate,
  7574. failure_reason=archive.failure_reason,
  7575. thumbnail_path=archive.thumbnail_path,
  7576. created_by_id=archive.created_by_id,
  7577. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7578. # Reconciled completions have an unknown real end time —
  7579. # log 0 duration instead of the whole disconnect gap (#2592).
  7580. reconciled=bool(data.get("_reconciled")),
  7581. )
  7582. await record_archive_wear(db, archive, run_entry)
  7583. await db.commit()
  7584. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7585. except Exception as e:
  7586. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7587. log_timing("Print log entry")
  7588. # Run slow operations as background tasks to avoid blocking the event loop
  7589. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7590. async def _background_energy_calculation():
  7591. """Calculate and save energy usage in background.
  7592. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7593. backend restart no longer loses per-print energy data).
  7594. """
  7595. try:
  7596. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7597. async with async_session() as db:
  7598. from backend.app.models.archive import PrintArchive
  7599. archive = await db.get(PrintArchive, archive_id)
  7600. if archive is None:
  7601. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7602. return
  7603. starting_kwh = archive.energy_start_kwh
  7604. if starting_kwh is None:
  7605. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7606. return
  7607. candidates = await energy_plug_candidates(db, printer_id)
  7608. if not candidates:
  7609. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7610. return
  7611. # Same ordering as the start reading, so the delta below is
  7612. # against the counter that produced `starting_kwh` (#2859).
  7613. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7614. if selected is None:
  7615. logger.warning(
  7616. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7617. printer_id,
  7618. ", ".join(plug.name for plug in candidates),
  7619. )
  7620. return
  7621. plug, energy = selected
  7622. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7623. energy_used = round(energy["total"] - starting_kwh, 4)
  7624. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7625. if energy_used < 0:
  7626. logger.warning(
  7627. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7628. archive_id,
  7629. starting_kwh,
  7630. energy["total"],
  7631. )
  7632. return
  7633. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7634. # Each hour of the print at the price of that hour (#1251). If
  7635. # that fails, the last price known, as before, rather than no
  7636. # energy at all. Read first: the session may be unusable after.
  7637. last_price = await stored_price(db)
  7638. try:
  7639. energy_cost_value = round(
  7640. await print_energy_cost(
  7641. db,
  7642. plug_id=archive.energy_start_plug_id,
  7643. start_at=archive.energy_start_at,
  7644. start_kwh=starting_kwh,
  7645. start_price=archive.energy_start_price,
  7646. end_kwh=energy["total"],
  7647. end_plug_id=plug.id,
  7648. price_now=await current_price(db),
  7649. ),
  7650. 3,
  7651. )
  7652. except Exception as e:
  7653. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7654. energy_cost_value = round(energy_used * last_price, 3)
  7655. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7656. # reprint doesn't visually clobber the source archive's energy data
  7657. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7658. from sqlalchemy import func
  7659. from backend.app.models.print_log import PrintLogEntry
  7660. existing_runs = await db.scalar(
  7661. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7662. )
  7663. if (existing_runs or 0) <= 1:
  7664. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7665. # we just wrote for THIS print. Either way it's the first run.
  7666. archive.energy_kwh = energy_used
  7667. archive.energy_cost = energy_cost_value
  7668. # Backfill the latest PrintLogEntry for this archive with energy
  7669. # (write_log_entry above ran before this background task completed,
  7670. # so energy fields are still NULL on that row).
  7671. latest_run = await db.execute(
  7672. select(PrintLogEntry)
  7673. .where(PrintLogEntry.archive_id == archive_id)
  7674. .order_by(PrintLogEntry.id.desc())
  7675. .limit(1)
  7676. )
  7677. run_row = latest_run.scalar_one_or_none()
  7678. if run_row is not None:
  7679. run_row.energy_kwh = energy_used
  7680. run_row.energy_cost = energy_cost_value
  7681. await db.commit()
  7682. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7683. except Exception as e:
  7684. logger.warning("[ENERGY-BG] Failed: %s", e)
  7685. async def _background_finish_photo() -> str | None:
  7686. """Capture finish photo in background. Returns photo filename if captured."""
  7687. # #2547: set once this function has raised the plate itself (the
  7688. # timelapse path, where the moment producer returned without doing it).
  7689. # Declared out here so the `finally` can lower it again no matter where
  7690. # the capture below fails.
  7691. plate_restored_z: float | None = None
  7692. try:
  7693. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7694. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7695. # Read phase: settings + printer + archive in a short session, released
  7696. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7697. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7698. # tens of seconds; holding this session across it pinned one pooled
  7699. # connection idle-in-transaction per finishing print (issue #2572).
  7700. async with async_session() as db:
  7701. from backend.app.api.routes.settings import get_setting
  7702. from backend.app.models.archive import PrintArchive
  7703. from backend.app.models.printer import Printer
  7704. capture_enabled = await get_setting(db, "capture_finish_photo")
  7705. if capture_enabled is not None and capture_enabled.lower() != "true":
  7706. return None
  7707. if not archive_id:
  7708. return None
  7709. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7710. archive = (
  7711. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7712. ).scalar_one_or_none()
  7713. if not printer or not archive:
  7714. return None
  7715. import uuid
  7716. from datetime import datetime
  7717. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7718. if not archive.file_path:
  7719. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7720. archive_dir = resolve_archive_dir(archive)
  7721. photo_filename = None
  7722. # Prefer the timelapse last-frame source when a timelapse was
  7723. # recording — it captures the moment after the toolhead parks
  7724. # but before the bed drops, which the live-camera grab below
  7725. # would miss (#1397). Skipped for external cameras (those have
  7726. # their own framing and don't see a Bambu timelapse). Only
  7727. # runs when the USER explicitly enabled timelapse for this
  7728. # print — #1721 removed Bambuddy's force-on at dispatch
  7729. # because it caused per-layer nozzle parking on Smooth-mode
  7730. # slicer profiles.
  7731. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7732. printer.external_camera_enabled and printer.external_camera_url
  7733. )
  7734. timelapse_still_pending = False
  7735. if prefer_timelapse_source:
  7736. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7737. archive_id=archive_id,
  7738. archive_dir=archive_dir,
  7739. rotation=getattr(printer, "camera_rotation", 0),
  7740. )
  7741. # #1721: replacement framing path — on_finish_photo_moment
  7742. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7743. # parked, bed not yet dropped) and cached the JPEG bytes in
  7744. # _stage22_finish_frames. Consume them now so the saved photo
  7745. # has the better framing instead of the post-bed-drop angle
  7746. # the live-camera fallback below would give.
  7747. if not photo_filename:
  7748. # #1790: on the FINISH-state fallback path the producer
  7749. # task is dispatched back-to-back with this consumer, so
  7750. # a bare pop would race past with an empty result and
  7751. # the RTSP fallback below would collide with the
  7752. # producer's still-in-flight grab (single-client RTSP
  7753. # on Bambu printers). Wait for the producer to finish
  7754. # or give up before touching the cache.
  7755. #
  7756. # #2547: 20s was enough when the producer only ever grabbed a
  7757. # frame. It now also raises the plate first, which costs the
  7758. # settle window before the grab even starts — so the budget has
  7759. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7760. # under the notification's own photo wait below.
  7761. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7762. if in_flight is not None:
  7763. try:
  7764. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7765. except TimeoutError:
  7766. logger.warning(
  7767. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7768. printer_id,
  7769. )
  7770. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7771. if cached_frame:
  7772. # Already rotated by the producer (#2708) — rotating again
  7773. # here would undo the fix on the banked-frame path, whose
  7774. # bytes reach the cache having been rotated once already.
  7775. photos_dir = archive_dir / "photos"
  7776. photos_dir.mkdir(parents=True, exist_ok=True)
  7777. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7778. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7779. photo_path = photos_dir / photo_filename
  7780. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7781. logger.info(
  7782. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7783. photo_filename,
  7784. len(cached_frame),
  7785. )
  7786. # #2547: the timelapse path reaches the live grab below whenever the
  7787. # video hasn't landed in time — the documented usual outcome on
  7788. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7789. # returned early for those prints without raising the plate, so
  7790. # without this the photo that actually ships in the notification is
  7791. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7792. # asked us to fix. The archive still gets the better video frame
  7793. # later; this is about the image the user is sent.
  7794. #
  7795. # Gated on `timelapse_was_active` precisely because that is the
  7796. # condition under which the producer skipped. On every other path it
  7797. # has already raised and lowered the plate, and repeating that here
  7798. # would be a second pointless round trip.
  7799. if (
  7800. not photo_filename
  7801. and data.get("timelapse_was_active")
  7802. and not print_dispatch_context.end_gcode_injected(printer_id)
  7803. ):
  7804. try:
  7805. async with async_session() as db:
  7806. from backend.app.api.routes.settings import get_setting
  7807. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7808. if restore_setting is None or restore_setting.lower() == "true":
  7809. max_z = await _max_z_for_current_print(
  7810. printer_id, data, logger, bound_archive_id, notify_plate_id
  7811. )
  7812. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7813. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7814. plate_restored_z = max_z
  7815. except Exception as e:
  7816. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7817. # Fallback chain: external camera → buffered live frame →
  7818. # fresh RTSP capture. Only runs if the timelapse path above
  7819. # didn't already produce a photo.
  7820. # Chamber light for the live capture below (#1655).
  7821. async with camera_light(printer if not photo_filename else None):
  7822. if not photo_filename:
  7823. if printer.external_camera_enabled and printer.external_camera_url:
  7824. logger.info("[PHOTO-BG] Using external camera")
  7825. from backend.app.api.routes.camera import live_frame_for_capture
  7826. from backend.app.services.external_camera import capture_frame
  7827. # #2707: the second half of the finish-photo failure — the
  7828. # pre-capture and this fallback both collided with the live
  7829. # view. None here continues down the fallback chain.
  7830. defer, buffered = live_frame_for_capture(printer_id)
  7831. if defer:
  7832. frame_data = buffered
  7833. else:
  7834. frame_data = await capture_frame(
  7835. printer.external_camera_url,
  7836. printer.external_camera_type or "mjpeg",
  7837. snapshot_url=printer.external_camera_snapshot_url,
  7838. )
  7839. if frame_data:
  7840. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7841. photos_dir = archive_dir / "photos"
  7842. photos_dir.mkdir(parents=True, exist_ok=True)
  7843. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7844. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7845. photo_path = photos_dir / photo_filename
  7846. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7847. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7848. else:
  7849. # Check if camera stream is active - use buffered frame to avoid freeze
  7850. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7851. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7852. active_chamber_for_printer = [
  7853. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7854. ]
  7855. buffered_frame = get_buffered_frame(printer_id)
  7856. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7857. # Use frame from active stream
  7858. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7859. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7860. photos_dir = archive_dir / "photos"
  7861. photos_dir.mkdir(parents=True, exist_ok=True)
  7862. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7863. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7864. photo_path = photos_dir / photo_filename
  7865. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7866. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7867. else:
  7868. # No active stream - capture new frame
  7869. from backend.app.services.camera import capture_finish_photo
  7870. photo_filename = await capture_finish_photo(
  7871. printer_id=printer_id,
  7872. ip_address=printer.ip_address,
  7873. access_code=printer.access_code,
  7874. model=printer.model,
  7875. archive_dir=archive_dir,
  7876. rotation=getattr(printer, "camera_rotation", 0),
  7877. )
  7878. # Write phase: attach the photo in a fresh short-lived session.
  7879. if photo_filename:
  7880. async with async_session() as db:
  7881. from backend.app.models.archive import PrintArchive
  7882. arch = await db.get(PrintArchive, archive_id)
  7883. if arch is not None:
  7884. photos = arch.photos or []
  7885. photos.append(photo_filename)
  7886. arch.photos = photos
  7887. await db.commit()
  7888. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7889. # The short wait above is bounded so a slow printer can't hold up
  7890. # the print-complete notification, which is what the caller is
  7891. # blocking on. When it ran out with the video still on its way,
  7892. # keep waiting off to the side and add the better frame to the
  7893. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7894. # users, whose videos routinely take minutes to transfer, never get
  7895. # the pre-bed-drop framing this path exists to provide.
  7896. #
  7897. # Spawned here rather than at the point the wait gave up: both this
  7898. # function and the upgrade do a read-modify-write on `photos`, and
  7899. # the live-camera fallback above can take tens of seconds. Starting
  7900. # the upgrade before that write means the two can interleave and one
  7901. # silently drops the other's entry, leaving a JPEG on disk that the
  7902. # gallery never lists.
  7903. if timelapse_still_pending:
  7904. spawn_background_task(
  7905. _upgrade_finish_photo_from_timelapse(
  7906. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7907. ),
  7908. name=f"finish-photo-upgrade-{archive_id}",
  7909. )
  7910. return photo_filename
  7911. except Exception as e:
  7912. logger.warning("[PHOTO-BG] Failed: %s", e)
  7913. return None
  7914. finally:
  7915. # #2547: we raised the plate, so we owe the move back down — even if
  7916. # the capture in between threw. Otherwise the user finds the print
  7917. # pinned under the nozzle.
  7918. if plate_restored_z is not None:
  7919. try:
  7920. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7921. except Exception as e:
  7922. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7923. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7924. # Photo capture task - result will be used by notifications
  7925. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7926. log_timing("Background tasks scheduled (energy, photo)")
  7927. # Also run smart plug, notifications, and maintenance as background tasks
  7928. print_status = data.get("status", "completed")
  7929. async def _background_smart_plug():
  7930. """Handle smart plug automation in background."""
  7931. try:
  7932. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7933. async with async_session() as db:
  7934. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7935. logger.info("[AUTO-OFF-BG] Completed")
  7936. except Exception as e:
  7937. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7938. async def _background_notifications(finish_photo_filename: str | None = None):
  7939. """Send print complete notifications in background."""
  7940. try:
  7941. logger.info(
  7942. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7943. )
  7944. async with async_session() as db:
  7945. from backend.app.models.archive import PrintArchive
  7946. from backend.app.models.printer import Printer
  7947. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7948. printer = result.scalar_one_or_none()
  7949. printer_name = printer.name if printer else f"Printer {printer_id}"
  7950. archive_data = None
  7951. if archive_id:
  7952. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7953. archive = archive_result.scalar_one_or_none()
  7954. if archive:
  7955. # Actual elapsed time from started_at/completed_at when both are
  7956. # populated (every terminal status sets completed_at after #1198).
  7957. # Falls back to None so the notification path can decide whether to
  7958. # render the slicer estimate as a last resort.
  7959. actual_time_seconds = None
  7960. if archive.started_at and archive.completed_at:
  7961. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7962. if elapsed > 0:
  7963. actual_time_seconds = int(elapsed)
  7964. archive_data = {
  7965. "print_time_seconds": archive.print_time_seconds,
  7966. "actual_time_seconds": actual_time_seconds,
  7967. "actual_filament_grams": archive.filament_used_grams,
  7968. "failure_reason": archive.failure_reason,
  7969. "created_by_id": archive.created_by_id,
  7970. }
  7971. # Scale filament usage for partial prints
  7972. if print_status != "completed" and archive.filament_used_grams:
  7973. progress = data.get("progress") or 0
  7974. scale = _partial_progress_scale(progress)
  7975. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7976. archive_data["progress"] = progress
  7977. # Pass per-slot data from archive.extra_data
  7978. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7979. slots = archive.extra_data["filament_slots"]
  7980. if print_status != "completed":
  7981. scale = _partial_progress_scale(data.get("progress"))
  7982. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7983. archive_data["filament_slots"] = slots
  7984. # Scope project-summed totals down to the plate that was
  7985. # actually printed — see _scope_notification_archive_data_to_plate
  7986. # for the why (#1785).
  7987. archive_data = _scope_notification_archive_data_to_plate(
  7988. archive_data,
  7989. archive.file_path,
  7990. notify_plate_id,
  7991. print_status,
  7992. data.get("progress"),
  7993. app_settings.base_dir,
  7994. )
  7995. # Enrich filament_grams from usage_results when archive has no 3MF data
  7996. if not archive_data.get("actual_filament_grams") and usage_results:
  7997. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7998. if total_from_usage > 0:
  7999. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8000. # Pass usage tracker results for AMS slot info in notifications
  8001. if usage_results:
  8002. archive_data["usage_results"] = usage_results
  8003. # Add finish photo URL and image bytes if available
  8004. if finish_photo_filename:
  8005. photo_url, photo_bytes = await _finish_photo_for_notification(
  8006. db, archive, archive_id, finish_photo_filename
  8007. )
  8008. if photo_url:
  8009. archive_data["finish_photo_url"] = photo_url
  8010. if photo_bytes:
  8011. archive_data["image_data"] = photo_bytes
  8012. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8013. await notification_service.on_print_complete(
  8014. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8015. )
  8016. else:
  8017. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8018. # Post-print outcome confirmation (#1898). Runs in this
  8019. # background task so the finish photo fetched above rides
  8020. # along with the prompt.
  8021. if print_status == "completed" and archive_id:
  8022. await _dispatch_outcome_confirmation_safely(
  8023. db, printer_id, printer_name, data, archive_id, archive_data
  8024. )
  8025. # Send user-specific email notification
  8026. if archive_data:
  8027. created_by_id = archive_data.get("created_by_id")
  8028. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8029. await _dispatch_user_print_email(
  8030. print_status,
  8031. created_by_id,
  8032. printer_name,
  8033. raw_filename,
  8034. db,
  8035. image_data=archive_data.get("image_data"),
  8036. finish_photo_url=archive_data.get("finish_photo_url"),
  8037. )
  8038. logger.info("[NOTIFY-BG] Completed")
  8039. except Exception as e:
  8040. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8041. async def _background_maintenance_check():
  8042. """Check for maintenance due in background."""
  8043. if print_status != "completed":
  8044. return
  8045. try:
  8046. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8047. async with async_session() as db:
  8048. from backend.app.models.printer import Printer
  8049. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8050. printer = result.scalar_one_or_none()
  8051. printer_name = printer.name if printer else f"Printer {printer_id}"
  8052. await ensure_default_types(db)
  8053. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8054. attention = [
  8055. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8056. ]
  8057. items_needing_attention = [
  8058. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8059. for item in attention
  8060. ]
  8061. if items_needing_attention:
  8062. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8063. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8064. # MQTT relay - publish maintenance alerts
  8065. for item in attention:
  8066. current_value, threshold, unit = maintenance_alert_values(item)
  8067. try:
  8068. await mqtt_relay.on_maintenance_alert(
  8069. printer_id=printer_id,
  8070. printer_name=printer_name,
  8071. maintenance_type=item.maintenance_type_name,
  8072. current_value=current_value,
  8073. threshold=threshold,
  8074. unit=unit,
  8075. )
  8076. except Exception:
  8077. pass # Don't fail if MQTT fails
  8078. else:
  8079. logger.info("[MAINT-BG] Completed (no items need attention)")
  8080. except Exception as e:
  8081. logger.warning("[MAINT-BG] Failed: %s", e)
  8082. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8083. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8084. # Notification task waits for photo capture to complete first (with timeout).
  8085. # When a timelapse was recording, photo sourcing polls the per-print
  8086. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8087. # carries the correct bed-up photo instead of falling through to the
  8088. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8089. #
  8090. # #2547: both budgets now have to cover a plate restore as well.
  8091. #
  8092. # Without timelapse, the wait is on the moment producer, which raises the
  8093. # plate before its grab — so this has to outlast that producer's own budget.
  8094. #
  8095. # With timelapse, the capture polls up to
  8096. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8097. # falls back to a live grab, which is the case that raises the plate. At the
  8098. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8099. # restore would have moved the plate for a photo nobody waited for.
  8100. photo_wait_timeout = (
  8101. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8102. if data.get("timelapse_was_active")
  8103. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8104. )
  8105. async def _photo_then_notify():
  8106. """Wait for photo capture, then send notification with photo URL."""
  8107. finish_photo = None
  8108. try:
  8109. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8110. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8111. except TimeoutError:
  8112. logger.warning(
  8113. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8114. photo_wait_timeout,
  8115. )
  8116. except Exception as e:
  8117. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8118. try:
  8119. await _background_notifications(finish_photo)
  8120. except Exception as e:
  8121. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8122. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8123. # Stitch external camera layer timelapse if session was active
  8124. print_status = data.get("status", "completed")
  8125. async def _background_layer_timelapse():
  8126. """Stitch layer timelapse and attach to archive."""
  8127. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8128. try:
  8129. if print_status == "completed":
  8130. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8131. timelapse_path = await tl_complete(printer_id)
  8132. if timelapse_path and archive_id:
  8133. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  8134. async with async_session() as db:
  8135. service = ArchiveService(db)
  8136. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  8137. await service.attach_timelapse(
  8138. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  8139. )
  8140. # Clean up the temp file
  8141. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8142. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  8143. elif timelapse_path:
  8144. # Timelapse created but no archive - just clean up
  8145. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8146. else:
  8147. # Print failed or cancelled - cancel timelapse session
  8148. cancel_session(printer_id)
  8149. logger.info(
  8150. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8151. )
  8152. except Exception as e:
  8153. logger.warning("[LAYER-TL] Failed: %s", e)
  8154. # Try to cancel session on error
  8155. try:
  8156. cancel_session(printer_id)
  8157. except Exception:
  8158. pass # Best-effort timelapse session cancellation on error
  8159. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8160. log_timing("All background tasks scheduled")
  8161. # Auto-scan for timelapse if recording was active during the print
  8162. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8163. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8164. # Schedule timelapse scan as background task with retries
  8165. # The printer needs time to encode the video after print completion
  8166. baseline = _timelapse_baselines.pop(printer_id, None)
  8167. spawn_background_task(
  8168. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8169. name=f"scan-timelapse-{archive_id}",
  8170. )
  8171. log_timing("Timelapse scan scheduled")
  8172. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8173. # AMS sensor history recording
  8174. _ams_history_task: asyncio.Task | None = None
  8175. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8176. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8177. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8178. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8179. _ams_alarm_cooldown: dict[str, datetime] = {}
  8180. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8181. # (printer_id, ams_id) already reported as sending the drop index and no
  8182. # percentage. Logged once each so a supported printer that turns out to do this
  8183. # shows up in a support bundle rather than as a user wondering where the
  8184. # humidity reading went -- see the note at the read site below (#3140).
  8185. _ams_index_only_logged: set[tuple[int, int]] = set()
  8186. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8187. """Temperature at which the AMS alarm fires, falling back to the display band.
  8188. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8189. when a notification was sent as well, which is why a room above it made the
  8190. alarm fire once an hour for as long as the weather lasted -- and the only way
  8191. to stop that was to raise the display band and lose the colour that says the
  8192. unit is warm (#2905).
  8193. Unset resolves to the fair threshold, so an install that never sets one is
  8194. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8195. so that arrives here as a string and is handled by the same branch as any
  8196. other unparseable value -- there is no separate sentinel to keep in sync.
  8197. A non-positive value is refused rather than honoured: zero would alarm
  8198. permanently, and it is far more likely to be a cleared field than a
  8199. deliberate choice.
  8200. """
  8201. if raw_alarm_value is None:
  8202. return fair_threshold
  8203. try:
  8204. value = float(raw_alarm_value)
  8205. except (TypeError, ValueError):
  8206. return fair_threshold
  8207. if not math.isfinite(value) or value <= 0:
  8208. return fair_threshold
  8209. return value
  8210. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8211. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8212. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8213. # partway through a cool-down would otherwise resume alarming about heat the
  8214. # user asked for — the same internal-timestamp-row pattern as
  8215. # support.py's debug_logging_enabled_at.
  8216. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8217. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8218. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8219. # matters when it never does.
  8220. AMS_DRYING_GRACE_MINUTES = 120
  8221. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8222. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8223. Anything older than the grace cap would expire on its next visit anyway, so
  8224. discarding it here costs nothing and stops rows for deleted printers from
  8225. accumulating.
  8226. Stamps ahead of now get two defences, because a box whose clock jumps
  8227. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8228. ones are discarded outright, and the rest are clamped to now. Without the
  8229. clamp the cap would measure from a moment that has not happened yet and hold
  8230. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8231. after a clock jump is a far better failure than an alarm silently disabled
  8232. for hours.
  8233. """
  8234. from backend.app.models.settings import Settings
  8235. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8236. setting = result.scalar_one_or_none()
  8237. if not setting or not setting.value:
  8238. return {}
  8239. try:
  8240. raw = json.loads(setting.value)
  8241. except (ValueError, TypeError):
  8242. return {} # Corrupted row → no latch, alarms behave as they did before
  8243. if not isinstance(raw, dict):
  8244. return {}
  8245. now = datetime.now(timezone.utc)
  8246. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8247. latch: dict[str, datetime] = {}
  8248. for key, value in raw.items():
  8249. try:
  8250. stamp = datetime.fromisoformat(str(value))
  8251. except (ValueError, TypeError):
  8252. continue
  8253. if stamp.tzinfo is None:
  8254. stamp = stamp.replace(tzinfo=timezone.utc)
  8255. if not (now - window <= stamp <= now + window):
  8256. continue
  8257. # Nothing may sit in the future: suppression is measured as now minus
  8258. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8259. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8260. latch[str(key)] = min(stamp, now)
  8261. return latch
  8262. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8263. """Persist the latch, writing only when it actually changed.
  8264. Adds the session change but does not commit — the caller's own commit
  8265. carries it, so the latch lands in the same transaction as the sensor rows
  8266. that produced it.
  8267. """
  8268. from backend.app.models.settings import Settings
  8269. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8270. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8271. setting = result.scalar_one_or_none()
  8272. if setting is None:
  8273. # Don't create the row on installs that never dry anything.
  8274. if payload != "{}":
  8275. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8276. elif setting.value != payload:
  8277. setting.value = payload
  8278. def _ams_has_filament(ams_data: dict) -> bool:
  8279. """True if this AMS unit has at least one tray slot holding filament.
  8280. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8281. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8282. still report sensor readings, but those readings are ambient and not
  8283. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8284. humidity/temperature alarms on this check so empty units don't generate
  8285. hourly noise. Sensor history still records regardless so the UI charts
  8286. stay continuous.
  8287. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8288. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8289. """
  8290. bits = ams_data.get("tray_exist_bits")
  8291. if isinstance(bits, str) and bits.strip():
  8292. try:
  8293. return int(bits, 16) > 0
  8294. except ValueError:
  8295. pass
  8296. trays = ams_data.get("tray")
  8297. if isinstance(trays, list):
  8298. return any(
  8299. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8300. )
  8301. return False
  8302. async def record_ams_history():
  8303. """Background task to record AMS humidity and temperature data."""
  8304. logger = logging.getLogger(__name__)
  8305. # Wait a short time for MQTT connections to establish on startup
  8306. await asyncio.sleep(10)
  8307. while True:
  8308. try:
  8309. from backend.app.models.ams_history import AMSSensorHistory
  8310. from backend.app.models.printer import Printer
  8311. from backend.app.models.settings import Settings
  8312. async with async_session() as db:
  8313. # Get all active printers
  8314. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8315. printers = result.scalars().all()
  8316. # Get alarm thresholds from settings
  8317. humidity_threshold = 60.0 # Default: fair threshold
  8318. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8319. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8320. setting = result.scalar_one_or_none()
  8321. if setting:
  8322. try:
  8323. humidity_threshold = float(setting.value)
  8324. except (ValueError, TypeError):
  8325. pass # Keep default threshold if stored value is invalid
  8326. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8327. setting = result.scalar_one_or_none()
  8328. if setting:
  8329. try:
  8330. temp_fair_threshold = float(setting.value)
  8331. except (ValueError, TypeError):
  8332. pass # Keep default threshold if stored value is invalid
  8333. # The alarm gets its own threshold, seeded from the resolved fair
  8334. # value so an install that has never set one behaves exactly as
  8335. # it did before (#2905). ams_temp_fair decides when the card turns
  8336. # amber; 35 C is a reasonable place to change a colour and not a
  8337. # reasonable place to page someone. A room above it makes the
  8338. # alarm fire once an hour for as long as the weather lasts, and
  8339. # the only way to stop it was to raise the display band and lose
  8340. # the colour that says the unit is warm.
  8341. #
  8342. # An unset value is stored as the literal "None", which the except
  8343. # below swallows the same way it swallows garbage -- so the
  8344. # fallback costs nothing and needs no sentinel of its own.
  8345. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8346. setting = result.scalar_one_or_none()
  8347. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8348. temp_fair_threshold, setting.value if setting else None
  8349. )
  8350. # Per-filament humidity threshold overrides (#1605) — resolved
  8351. # per-AMS below from the loaded tray types. Reuses the same
  8352. # resolver as the auto-drying scheduler so behavior stays in
  8353. # lockstep across both consumers.
  8354. from backend.app.services.print_scheduler import PrintScheduler
  8355. per_type_humidity_thresholds: dict[str, int] = {}
  8356. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8357. setting = result.scalar_one_or_none()
  8358. if setting and setting.value:
  8359. try:
  8360. raw = json.loads(setting.value)
  8361. if isinstance(raw, dict):
  8362. for k, v in raw.items():
  8363. try:
  8364. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8365. v
  8366. )
  8367. except (TypeError, ValueError):
  8368. continue
  8369. except (ValueError, TypeError):
  8370. pass # Invalid JSON → no overrides, fall through to global threshold
  8371. # Per-AMS drying latch (#1802), loaded once per pass and written
  8372. # back below only if a unit changed it.
  8373. drying_latch = await _load_ams_drying_latch(db)
  8374. drying_latch_before = dict(drying_latch)
  8375. recorded_count = 0
  8376. for printer in printers:
  8377. # Get current state from printer manager
  8378. state = printer_manager.get_status(printer.id)
  8379. if not state or not state.connected or not state.raw_data:
  8380. continue # Skip disconnected printers - don't use stale data
  8381. raw_data = state.raw_data
  8382. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8383. continue
  8384. # Record data for each AMS unit
  8385. for ams_data in raw_data["ams"]:
  8386. ams_id = int(ams_data.get("id", 0))
  8387. # Percentage only. The 1-5 index is inverted, so
  8388. # charting it as a percentage drew the wettest units as
  8389. # the driest (#3140); a unit that reports no percentage
  8390. # leaves a gap in the chart instead. See
  8391. # utils/ams_humidity.
  8392. humidity = ams_humidity_percent(ams_data)
  8393. # No supported printer is known to send the index
  8394. # alone -- the report came from unsupported firmware,
  8395. # and no install has been seen using the old fallback.
  8396. # "Known" is doing work there, so say so once per unit:
  8397. # the alternative is a silent blank card.
  8398. if humidity is None and ams_data.get("humidity") is not None:
  8399. unit_key = (printer.id, ams_id)
  8400. if unit_key not in _ams_index_only_logged:
  8401. _ams_index_only_logged.add(unit_key)
  8402. logger.info(
  8403. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8404. "percentage. The index is inverted and is not shown as a percentage "
  8405. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8406. "Please report this with the printer and AMS firmware versions.",
  8407. printer.name,
  8408. ams_id,
  8409. )
  8410. # Get temperature
  8411. temperature = None
  8412. temp_str = ams_data.get("temp")
  8413. if temp_str is not None:
  8414. try:
  8415. temperature = float(temp_str)
  8416. except (ValueError, TypeError):
  8417. pass # Skip unparseable temperature value
  8418. # Skip if no data
  8419. if humidity is None and temperature is None:
  8420. continue
  8421. # Record the data point
  8422. history = AMSSensorHistory(
  8423. printer_id=printer.id,
  8424. ams_id=ams_id,
  8425. humidity=humidity,
  8426. # Both columns hold the same reading now that the
  8427. # index can no longer reach ``humidity``. Writing it
  8428. # through the same value also stops a genuine 0%
  8429. # from being stored as NULL, which the old truthiness
  8430. # test did.
  8431. humidity_raw=humidity,
  8432. temperature=temperature,
  8433. )
  8434. db.add(history)
  8435. recorded_count += 1
  8436. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8437. is_ams_ht = ams_id >= 128
  8438. if is_ams_ht:
  8439. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8440. else:
  8441. ams_label = f"AMS-{chr(65 + ams_id)}"
  8442. # Skip alarm dispatch for empty AMS units — humidity /
  8443. # temperature readings are ambient with no filament to
  8444. # protect, and the hourly notification just becomes
  8445. # noise. Sensor history was already recorded above so
  8446. # the UI charts stay continuous (#1619). Per-AMS check
  8447. # so a multi-AMS setup with one loaded + one empty
  8448. # still alarms on the loaded unit.
  8449. if not _ams_has_filament(ams_data):
  8450. continue
  8451. # Resolve per-filament humidity threshold for this AMS
  8452. # unit (#1605). Falls back to the global ams_humidity_fair
  8453. # when no per-type overrides are configured.
  8454. trays = ams_data.get("tray", []) or []
  8455. effective_humidity_threshold = float(
  8456. PrintScheduler.resolve_humidity_threshold(
  8457. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8458. )
  8459. )
  8460. # Check humidity alarm (only if above threshold)
  8461. if humidity is not None and humidity > effective_humidity_threshold:
  8462. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8463. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8464. now = datetime.now(timezone.utc)
  8465. if (
  8466. last_alarm is None
  8467. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8468. ):
  8469. _ams_alarm_cooldown[cooldown_key] = now
  8470. logger.info(
  8471. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8472. )
  8473. try:
  8474. # Call different notification method based on AMS type
  8475. if is_ams_ht:
  8476. await notification_service.on_ams_ht_humidity_high(
  8477. printer.id,
  8478. printer.name,
  8479. ams_label,
  8480. humidity,
  8481. effective_humidity_threshold,
  8482. db,
  8483. )
  8484. else:
  8485. await notification_service.on_ams_humidity_high(
  8486. printer.id,
  8487. printer.name,
  8488. ams_label,
  8489. humidity,
  8490. effective_humidity_threshold,
  8491. db,
  8492. )
  8493. except Exception as e:
  8494. logger.warning("Failed to send humidity alarm: %s", e)
  8495. # A drying cycle heats the unit far past ams_temp_fair on
  8496. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8497. # AMS-HT, against a 35 C default — so the alarm fired
  8498. # once an hour for the whole cycle and kept firing while
  8499. # the unit cooled back down (#1802). Latch on the
  8500. # firmware's own drying state and hold until the reading
  8501. # returns to normal. Humidity is deliberately left alone:
  8502. # it falls during drying, which is the whole point.
  8503. latch_key = f"{printer.id}:{ams_id}"
  8504. # The latch releases at `threshold`, so it takes the alarm
  8505. # number too. Handing it the display band would strand the
  8506. # latch on any unit that settles back above it -- a room
  8507. # where the AMS rests at 37.7 C never returns under a 35 C
  8508. # band, so the latch could only expire on the grace cap
  8509. # rather than releasing when the unit had actually cooled.
  8510. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8511. drying_active=is_drying_active(ams_data),
  8512. temperature=temperature,
  8513. threshold=temp_alarm_threshold,
  8514. latched_at=drying_latch.get(latch_key),
  8515. now=datetime.now(timezone.utc),
  8516. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8517. )
  8518. if new_latch is None:
  8519. drying_latch.pop(latch_key, None)
  8520. else:
  8521. drying_latch[latch_key] = new_latch
  8522. # Check temperature alarm (only if above threshold)
  8523. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8524. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8525. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8526. now = datetime.now(timezone.utc)
  8527. if (
  8528. last_alarm is None
  8529. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8530. ):
  8531. _ams_alarm_cooldown[cooldown_key] = now
  8532. logger.info(
  8533. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8534. f"{temperature}°C > {temp_alarm_threshold}°C"
  8535. )
  8536. try:
  8537. # Call different notification method based on AMS type
  8538. if is_ams_ht:
  8539. # The reported threshold has to be the one
  8540. # that fired, or the message says "> 35 °C"
  8541. # while firing at 45.
  8542. await notification_service.on_ams_ht_temperature_high(
  8543. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8544. )
  8545. else:
  8546. await notification_service.on_ams_temperature_high(
  8547. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8548. )
  8549. except Exception as e:
  8550. logger.warning("Failed to send temperature alarm: %s", e)
  8551. if drying_latch != drying_latch_before:
  8552. await _save_ams_drying_latch(db, drying_latch)
  8553. await db.commit()
  8554. if recorded_count > 0:
  8555. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8556. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8557. global _ams_cleanup_counter
  8558. _ams_cleanup_counter += 1
  8559. if _ams_cleanup_counter >= 288:
  8560. _ams_cleanup_counter = 0
  8561. # Get retention days from settings
  8562. from backend.app.models.settings import Settings
  8563. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8564. setting = result.scalar_one_or_none()
  8565. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8566. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8567. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8568. await db.commit()
  8569. if result.rowcount > 0:
  8570. logger.info(
  8571. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8572. )
  8573. # Wait until next recording interval
  8574. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8575. except asyncio.CancelledError:
  8576. break
  8577. except Exception as e:
  8578. logger.warning("AMS history recording failed: %s", e)
  8579. await asyncio.sleep(60) # Wait a bit before retrying
  8580. def start_ams_history_recording():
  8581. """Start the AMS history recording background task."""
  8582. global _ams_history_task
  8583. if _ams_history_task is None:
  8584. _ams_history_task = asyncio.create_task(record_ams_history())
  8585. logging.getLogger(__name__).info("AMS history recording started")
  8586. def stop_ams_history_recording():
  8587. """Stop the AMS history recording background task."""
  8588. global _ams_history_task
  8589. if _ams_history_task:
  8590. _ams_history_task.cancel()
  8591. _ams_history_task = None
  8592. logging.getLogger(__name__).info("AMS history recording stopped")
  8593. # Printer sensor history recording (nozzle / bed / chamber)
  8594. _printer_sensor_history_task: asyncio.Task | None = None
  8595. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8596. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8597. _printer_sensor_cleanup_counter = 0
  8598. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8599. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8600. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8601. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8602. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8603. _SENSOR_TARGET_KEYS = {
  8604. "nozzle": "nozzle_target",
  8605. "nozzle_2": "nozzle_2_target",
  8606. "bed": "bed_target",
  8607. "chamber": "chamber_target",
  8608. }
  8609. async def record_printer_sensor_history():
  8610. """Background task to record nozzle / bed / chamber readings.
  8611. Pulls from `state.temperatures` (already normalised across all printer
  8612. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8613. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8614. """
  8615. logger = logging.getLogger(__name__)
  8616. await asyncio.sleep(10)
  8617. while True:
  8618. try:
  8619. from backend.app.models.printer import Printer
  8620. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8621. from backend.app.models.settings import Settings
  8622. async with async_session() as db:
  8623. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8624. printers = result.scalars().all()
  8625. recorded_count = 0
  8626. for printer in printers:
  8627. state = printer_manager.get_status(printer.id)
  8628. if not state or not state.connected:
  8629. continue
  8630. temps = getattr(state, "temperatures", None) or {}
  8631. if not isinstance(temps, dict):
  8632. continue
  8633. for kind in _SENSOR_KINDS:
  8634. if kind not in temps:
  8635. continue
  8636. try:
  8637. value = float(temps[kind])
  8638. except (ValueError, TypeError):
  8639. continue
  8640. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8641. target_val: float | None = None
  8642. if target_raw is not None:
  8643. try:
  8644. target_val = float(target_raw)
  8645. except (ValueError, TypeError):
  8646. target_val = None
  8647. db.add(
  8648. PrinterSensorHistory(
  8649. printer_id=printer.id,
  8650. sensor_kind=kind,
  8651. value=value,
  8652. target=target_val,
  8653. )
  8654. )
  8655. recorded_count += 1
  8656. await db.commit()
  8657. if recorded_count > 0:
  8658. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8659. # Periodic cleanup — once every ~24h at this interval.
  8660. global _printer_sensor_cleanup_counter
  8661. _printer_sensor_cleanup_counter += 1
  8662. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8663. if _printer_sensor_cleanup_counter >= cleanup_every:
  8664. _printer_sensor_cleanup_counter = 0
  8665. result = await db.execute(
  8666. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8667. )
  8668. setting = result.scalar_one_or_none()
  8669. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8670. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8671. cleanup = await db.execute(
  8672. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8673. )
  8674. await db.commit()
  8675. if cleanup.rowcount > 0:
  8676. logger.info(
  8677. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8678. cleanup.rowcount,
  8679. retention_days,
  8680. )
  8681. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8682. except asyncio.CancelledError:
  8683. break
  8684. except Exception as e:
  8685. logger.warning("Printer sensor history recording failed: %s", e)
  8686. await asyncio.sleep(60)
  8687. def start_printer_sensor_history_recording():
  8688. global _printer_sensor_history_task
  8689. if _printer_sensor_history_task is None:
  8690. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8691. logging.getLogger(__name__).info("Printer sensor history recording started")
  8692. def stop_printer_sensor_history_recording():
  8693. global _printer_sensor_history_task
  8694. if _printer_sensor_history_task:
  8695. _printer_sensor_history_task.cancel()
  8696. _printer_sensor_history_task = None
  8697. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8698. # Printer runtime tracking
  8699. _runtime_tracking_task: asyncio.Task | None = None
  8700. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8701. async def track_printer_runtime():
  8702. """Background task to track printer active runtime (RUNNING state only).
  8703. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8704. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8705. which track mechanical wear. Pause time has no motion and no wear, so
  8706. counting it inflates maintenance warnings (#1521).
  8707. """
  8708. logger = logging.getLogger(__name__)
  8709. # Wait for MQTT connections to establish on startup
  8710. await asyncio.sleep(15)
  8711. while True:
  8712. try:
  8713. from backend.app.models.printer import Printer
  8714. # Fetch printer IDs in a short-lived read-only session
  8715. async with async_session() as db:
  8716. result = await db.execute(
  8717. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8718. Printer.is_active.is_(True)
  8719. )
  8720. )
  8721. printer_rows = result.all()
  8722. now = datetime.now(timezone.utc)
  8723. updated_count = 0
  8724. # Update each printer in its own short session to minimise write-lock
  8725. # hold time and avoid blocking critical commits like queue status
  8726. # updates (#897).
  8727. for pid, pname, runtime_secs, last_update in printer_rows:
  8728. state = printer_manager.get_status(pid)
  8729. if not state:
  8730. logger.debug("[%s] Runtime tracking: no state available", pname)
  8731. continue
  8732. if not state.connected:
  8733. logger.debug("[%s] Runtime tracking: not connected", pname)
  8734. continue
  8735. needs_commit = False
  8736. new_runtime = runtime_secs
  8737. new_last_update = last_update
  8738. if state.state == "RUNNING":
  8739. if last_update:
  8740. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8741. elapsed = (now - lu).total_seconds()
  8742. if elapsed > 0:
  8743. new_runtime = runtime_secs + int(elapsed)
  8744. updated_count += 1
  8745. needs_commit = True
  8746. logger.debug(
  8747. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8748. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8749. )
  8750. else:
  8751. needs_commit = True
  8752. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8753. new_last_update = now
  8754. else:
  8755. if last_update is not None:
  8756. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8757. new_last_update = None
  8758. needs_commit = True
  8759. if needs_commit:
  8760. try:
  8761. async with async_session() as db:
  8762. result = await db.execute(select(Printer).where(Printer.id == pid))
  8763. printer = result.scalar_one_or_none()
  8764. if printer:
  8765. printer.runtime_seconds = new_runtime
  8766. printer.last_runtime_update = new_last_update
  8767. await db.commit()
  8768. except Exception as e:
  8769. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8770. if updated_count > 0:
  8771. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8772. except asyncio.CancelledError:
  8773. logger.info("Runtime tracking cancelled")
  8774. break
  8775. except Exception as e:
  8776. logger.warning("Runtime tracking failed: %s", e)
  8777. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8778. def start_runtime_tracking():
  8779. """Start the printer runtime tracking background task."""
  8780. global _runtime_tracking_task
  8781. if _runtime_tracking_task is None:
  8782. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8783. logging.getLogger(__name__).info("Printer runtime tracking started")
  8784. def stop_runtime_tracking():
  8785. """Stop the printer runtime tracking background task."""
  8786. global _runtime_tracking_task
  8787. if _runtime_tracking_task:
  8788. _runtime_tracking_task.cancel()
  8789. _runtime_tracking_task = None
  8790. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8791. # SpoolBuddy device watchdog
  8792. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8793. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8794. async def _spoolbuddy_watchdog_loop():
  8795. """Periodic check for SpoolBuddy devices that have gone offline."""
  8796. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8797. while True:
  8798. try:
  8799. await spoolbuddy_watchdog()
  8800. except asyncio.CancelledError:
  8801. break
  8802. except Exception as e:
  8803. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8804. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8805. def start_spoolbuddy_watchdog():
  8806. global _spoolbuddy_watchdog_task
  8807. if _spoolbuddy_watchdog_task is None:
  8808. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8809. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8810. def stop_spoolbuddy_watchdog():
  8811. global _spoolbuddy_watchdog_task
  8812. if _spoolbuddy_watchdog_task:
  8813. _spoolbuddy_watchdog_task.cancel()
  8814. _spoolbuddy_watchdog_task = None
  8815. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8816. # Dead-MQTT-session recovery
  8817. #
  8818. # check_staleness() covers the "connected but silent" half-broken session. It
  8819. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8820. # is the only thing left watching at that point. When paho stops making
  8821. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8822. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8823. # offline with the UI open the whole time, recovered only when something
  8824. # happened to nudge it.
  8825. #
  8826. # This loop is that backstop. It only touches printers that had a working
  8827. # session and lost it, and only when the MQTT port still answers — a printer
  8828. # that is simply switched off is left to paho, since rebuilding a client
  8829. # against an unreachable host achieves nothing and would fill the log every
  8830. # night.
  8831. _connection_watchdog_task: asyncio.Task | None = None
  8832. CONNECTION_WATCHDOG_INTERVAL = 60
  8833. # How long a printer must have been silent before we stop trusting paho.
  8834. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8835. # so a session that is recovering on its own is never interrupted.
  8836. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8837. # Per-printer floor between rebuild attempts.
  8838. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8839. _connection_watchdog_last_attempt: dict[int, float] = {}
  8840. async def _recover_dead_printer_sessions() -> int:
  8841. """Rebuild MQTT clients that have been offline too long to still be trying.
  8842. Returns the number of printers a rebuild was attempted for (for tests and
  8843. for the caller's logging). Never raises: one unreachable printer must not
  8844. stop the sweep for the rest of the farm.
  8845. """
  8846. logger = logging.getLogger(__name__)
  8847. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8848. now = time.monotonic()
  8849. recovered = 0
  8850. for printer_id, client in list(printer_manager._clients.items()):
  8851. try:
  8852. if client.state.connected:
  8853. _connection_watchdog_last_attempt.pop(printer_id, None)
  8854. continue
  8855. # Time since the last inbound message is the age of the last known
  8856. # good session — no extra bookkeeping needed, and it is the same
  8857. # clock is_stale() reads. 0 means this client has never had one:
  8858. # that is the initial-connect path, where paho retrying is the
  8859. # correct and only behaviour, so leave it be.
  8860. last_msg = client._last_message_time
  8861. if not last_msg:
  8862. continue
  8863. offline_for = time.time() - last_msg
  8864. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8865. continue
  8866. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8867. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8868. continue
  8869. if not await check_port(client.ip_address, PORT_MQTT):
  8870. # Switched off, unplugged, or off the network. Paho's retry is
  8871. # the right handler; say so at debug level and move on.
  8872. logger.debug(
  8873. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8874. "— leaving the reconnect to paho",
  8875. printer_id,
  8876. offline_for,
  8877. )
  8878. _connection_watchdog_last_attempt[printer_id] = now
  8879. continue
  8880. _connection_watchdog_last_attempt[printer_id] = now
  8881. recovered += 1
  8882. logger.warning(
  8883. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8884. "rebuilding the client with a fresh session (last connect error: %s)",
  8885. printer_id,
  8886. offline_for,
  8887. PORT_MQTT,
  8888. client.last_connect_error or "none recorded",
  8889. )
  8890. # Async context, so this takes the hard-reset path: fresh client_id,
  8891. # paho's QoS 1 queue dropped. That matters — a project_file left
  8892. # unacked on the dead session would otherwise replay into the new
  8893. # one and trip 0500_4003 on the printer (#1136).
  8894. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8895. except Exception as e:
  8896. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8897. return recovered
  8898. async def _connection_watchdog_loop():
  8899. logger = logging.getLogger(__name__)
  8900. # Let the initial connects settle before judging anyone offline.
  8901. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8902. while True:
  8903. try:
  8904. await _recover_dead_printer_sessions()
  8905. except asyncio.CancelledError:
  8906. break
  8907. except Exception as e:
  8908. logger.warning("Connection watchdog sweep failed: %s", e)
  8909. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8910. def start_connection_watchdog():
  8911. global _connection_watchdog_task
  8912. if _connection_watchdog_task is None:
  8913. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8914. logging.getLogger(__name__).info("Printer connection watchdog started")
  8915. def stop_connection_watchdog():
  8916. global _connection_watchdog_task
  8917. if _connection_watchdog_task:
  8918. _connection_watchdog_task.cancel()
  8919. _connection_watchdog_task = None
  8920. _connection_watchdog_last_attempt.clear()
  8921. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8922. # Camera stream orphan cleanup
  8923. _camera_cleanup_task: asyncio.Task | None = None
  8924. CAMERA_CLEANUP_INTERVAL = 60
  8925. async def _camera_cleanup_loop():
  8926. """Periodically clean up orphaned ffmpeg processes."""
  8927. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8928. while True:
  8929. try:
  8930. await cleanup_orphaned_streams()
  8931. except asyncio.CancelledError:
  8932. break
  8933. except Exception as e:
  8934. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8935. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8936. def start_camera_cleanup():
  8937. global _camera_cleanup_task
  8938. if _camera_cleanup_task is None:
  8939. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8940. logging.getLogger(__name__).info("Camera stream cleanup started")
  8941. def stop_camera_cleanup():
  8942. global _camera_cleanup_task
  8943. if _camera_cleanup_task:
  8944. _camera_cleanup_task.cancel()
  8945. _camera_cleanup_task = None
  8946. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8947. # ---------------------------------------------------------------------------
  8948. # Expected-print TTL eviction
  8949. # ---------------------------------------------------------------------------
  8950. def _evict_stale_expected_prints() -> None:
  8951. """Remove entries from _expected_prints / _expected_print_creators that are
  8952. older than _EXPECTED_PRINT_TTL_SECONDS.
  8953. This prevents unbounded growth when a print is registered (via
  8954. register_expected_print) but on_print_start never fires — e.g. because the
  8955. printer disconnects, the app restarts, or the print is started directly from
  8956. the printer panel without going through the queue.
  8957. """
  8958. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8959. # (e.g. NTP sync, DST changes).
  8960. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8961. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8962. if not stale_keys:
  8963. return
  8964. evicted_archive_ids: set[int] = set()
  8965. for key in stale_keys:
  8966. archive_id = _expected_prints.pop(key, None)
  8967. if archive_id is not None:
  8968. evicted_archive_ids.add(archive_id)
  8969. _expected_print_creators.pop(key, None)
  8970. _expected_print_registered_at.pop(key, None)
  8971. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8972. # that have no remaining live keys in _expected_prints (all variants
  8973. # were just evicted) and are not printing right now. Print start pops
  8974. # only the names the printer reported, so the "<base>.gcode" variant
  8975. # outlives it; without the printing check its eviction two hours after
  8976. # dispatch threw away a running print's plate, AMS mapping and cost
  8977. # centre, which completion still reads (#3275).
  8978. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  8979. for archive_id in evicted_archive_ids:
  8980. if archive_id not in live_archive_ids:
  8981. _print_ams_mappings.pop(archive_id, None)
  8982. _print_cost_center_ids.pop(archive_id, None)
  8983. _print_plate_ids.pop(archive_id, None)
  8984. logging.getLogger(__name__).info(
  8985. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8986. )
  8987. async def _expected_prints_cleanup_loop() -> None:
  8988. """Background task: periodically evict stale expected-print entries."""
  8989. while True:
  8990. try:
  8991. _evict_stale_expected_prints()
  8992. except asyncio.CancelledError:
  8993. raise
  8994. except Exception as e:
  8995. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8996. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8997. def start_expected_prints_cleanup() -> None:
  8998. global _expected_prints_cleanup_task
  8999. if _expected_prints_cleanup_task is None:
  9000. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9001. logging.getLogger(__name__).info("Expected prints cleanup started")
  9002. def stop_expected_prints_cleanup() -> None:
  9003. global _expected_prints_cleanup_task
  9004. if _expected_prints_cleanup_task:
  9005. _expected_prints_cleanup_task.cancel()
  9006. _expected_prints_cleanup_task = None
  9007. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9008. # ---------------------------------------------------------------------------
  9009. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9010. # ---------------------------------------------------------------------------
  9011. _auth_cleanup_task: asyncio.Task | None = None
  9012. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9013. async def _run_auth_cleanup() -> None:
  9014. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9015. from backend.app.core.database import async_session
  9016. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9017. from backend.app.models.user_totp import UserTOTP
  9018. now = datetime.now(timezone.utc)
  9019. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9020. try:
  9021. async with async_session() as db:
  9022. stale_cutoff = now - timedelta(hours=1)
  9023. result = await db.execute(
  9024. select(UserTOTP).where(
  9025. UserTOTP.is_enabled.is_(False),
  9026. UserTOTP.created_at < stale_cutoff,
  9027. )
  9028. )
  9029. stale_records = result.scalars().all()
  9030. if stale_records:
  9031. for rec in stale_records:
  9032. await db.delete(rec)
  9033. await db.commit()
  9034. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9035. except Exception as e:
  9036. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9037. # Remove expired revoked-JTI entries (they are no longer needed once the
  9038. # original token's exp has passed — the token would be rejected by JWT
  9039. # signature verification regardless).
  9040. try:
  9041. async with async_session() as db:
  9042. await db.execute(
  9043. delete(AuthEphemeralToken).where(
  9044. AuthEphemeralToken.token_type == "revoked_jti",
  9045. AuthEphemeralToken.expires_at < now,
  9046. )
  9047. )
  9048. await db.commit()
  9049. except Exception as e:
  9050. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9051. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9052. # Events outside this window can never affect rate-limit decisions — they only
  9053. # consume DB space. Use the same window constant as the rate limiter so the
  9054. # two are always in sync.
  9055. try:
  9056. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9057. async with async_session() as db:
  9058. await db.execute(
  9059. delete(AuthRateLimitEvent).where(
  9060. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9061. )
  9062. )
  9063. await db.commit()
  9064. except Exception as e:
  9065. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9066. async def _auth_cleanup_loop() -> None:
  9067. """Periodic background task: run auth cleanup every hour."""
  9068. while True:
  9069. try:
  9070. await _run_auth_cleanup()
  9071. except asyncio.CancelledError:
  9072. break
  9073. except Exception as e:
  9074. logging.warning("Auth cleanup loop error: %s", e)
  9075. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9076. def start_auth_cleanup() -> None:
  9077. global _auth_cleanup_task
  9078. if _auth_cleanup_task is None:
  9079. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9080. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9081. def stop_auth_cleanup() -> None:
  9082. global _auth_cleanup_task
  9083. if _auth_cleanup_task:
  9084. _auth_cleanup_task.cancel()
  9085. _auth_cleanup_task = None
  9086. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9087. @asynccontextmanager
  9088. async def lifespan(app: FastAPI):
  9089. # Startup
  9090. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9091. # anything else can spawn tasks that might trip it.
  9092. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9093. install_proactor_reset_filter()
  9094. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9095. # what turned descriptor exhaustion into a corrupted database (#2883).
  9096. from backend.app.core.fd_limit import raise_open_file_limit
  9097. raise_open_file_limit()
  9098. # Before init_db, so the warning is near the top of the log rather than
  9099. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9100. warn_if_running_on_uvloop()
  9101. await init_db()
  9102. # Browser download tokens expire after five minutes. Remove abandoned
  9103. # prepared ZIPs at startup as well as before each new preparation so a
  9104. # quiet appliance cannot retain an unusable bundle indefinitely.
  9105. try:
  9106. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9107. await prune_stale_printer_file_bundles()
  9108. except Exception as exc:
  9109. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9110. # After migrations, so the is_env_managed column exists. Never raises --
  9111. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9112. # startup (see apply_env_oidc_provider).
  9113. from backend.app.core.oidc_env import apply_env_oidc_provider
  9114. async with async_session() as oidc_db:
  9115. await apply_env_oidc_provider(oidc_db)
  9116. # Close out batches that finished before `completed` was a reachable status
  9117. # (#342). Without this the Batches tab opens on every batch created since
  9118. # the feature shipped, all still marked active. Never blocks startup.
  9119. try:
  9120. from backend.app.services.print_batch import backfill_batch_statuses
  9121. async with async_session() as batch_db:
  9122. await backfill_batch_statuses(batch_db)
  9123. except Exception as exc:
  9124. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9125. # Register an app-scoped httpx client for Bambu Cloud services so
  9126. # per-request BambuCloudService instances reuse the same connection pool
  9127. # (important for routes like /cloud/filament-info that chain many
  9128. # get_setting_detail calls). The shared client stores no region/token
  9129. # state, so the per-request ownership pattern that fixed the region-bleed
  9130. # bug is preserved.
  9131. import httpx as _httpx
  9132. from backend.app.services.bambu_cloud import set_shared_http_client
  9133. from backend.app.services.model_providers.makerworld.service import (
  9134. set_shared_http_client as set_shared_makerworld_http_client,
  9135. )
  9136. from backend.app.services.orca_cloud import (
  9137. set_shared_http_client as set_shared_orca_http_client,
  9138. )
  9139. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9140. set_shared_http_client(_shared_cloud_http_client)
  9141. # Reuse the same connection pool for MakerWorld — different host, same
  9142. # keep-alive pool saves a TLS handshake per request.
  9143. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9144. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9145. # each spun up (and never closed) its own client, leaking sockets.
  9146. set_shared_orca_http_client(_shared_cloud_http_client)
  9147. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9148. # This can happen when a print was cancelled mid-print on versions before this fix.
  9149. try:
  9150. async with async_session() as db:
  9151. from backend.app.models.print_queue import PrintQueueItem
  9152. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9153. aborted_items = result.scalars().all()
  9154. if aborted_items:
  9155. for item in aborted_items:
  9156. item.status = "cancelled"
  9157. await db.commit()
  9158. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9159. except Exception as e:
  9160. logging.warning("Failed to fix aborted queue items: %s", e)
  9161. # Restore debug logging state from previous session
  9162. await init_debug_logging()
  9163. # Set up printer manager callbacks
  9164. loop = asyncio.get_event_loop()
  9165. printer_manager.set_event_loop(loop)
  9166. printer_manager.set_status_change_callback(on_printer_status_change)
  9167. printer_manager.set_print_start_callback(on_print_start)
  9168. printer_manager.set_print_complete_callback(on_print_complete)
  9169. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9170. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9171. printer_manager.set_ams_change_callback(on_ams_change)
  9172. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9173. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9174. await printer_manager.load_awaiting_plate_clear_from_db()
  9175. # Layer change callback for external camera timelapse
  9176. async def on_layer_change(printer_id: int, layer_num: int):
  9177. """Capture timelapse frame on layer change + first layer notification."""
  9178. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9179. await tl_layer_change(printer_id, layer_num)
  9180. # #1867: bank a recent in-print frame so the finish-photo path has a
  9181. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9182. # #2547 added `on_print_progress` as a second driver — this one alone
  9183. # stops firing once the final layer begins.
  9184. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9185. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9186. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9187. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9188. # nozzle clean), so a bare layer_num check can fire minutes before the
  9189. # first real extrusion. We require gcode_state == RUNNING and
  9190. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9191. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9192. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9193. # edge fires later; _first_layer_notified stays clear until we actually send
  9194. # so a deferred re-evaluation can win. See issue #1837.
  9195. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9196. client = printer_manager.get_client(printer_id)
  9197. state = client.state if client else None
  9198. if not state or state.state != "RUNNING":
  9199. return
  9200. if state.mc_print_sub_stage not in (None, 0):
  9201. return
  9202. _first_layer_notified[printer_id] = True
  9203. try:
  9204. async with async_session() as db:
  9205. from backend.app.models.printer import Printer
  9206. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9207. printer = result.scalar_one_or_none()
  9208. if not printer:
  9209. return
  9210. printer_name = printer.name
  9211. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9212. total_layers = state.total_layers if state else 0
  9213. image_data = await _capture_snapshot_for_notification(
  9214. printer_id, printer, logging.getLogger(__name__)
  9215. )
  9216. await notification_service.on_first_layer_complete(
  9217. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9218. )
  9219. except Exception as e:
  9220. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9221. printer_manager.set_layer_change_callback(on_layer_change)
  9222. async def on_print_progress(printer_id: int, percent: int):
  9223. """#2547: keep the in-print frame bank fresh through the final layer.
  9224. `on_layer_change` stops the moment the last layer starts, which on the
  9225. H2C capture that closed #2547 left the bank stale for the three minutes
  9226. that layer took. Progress is the only field that keeps advancing there,
  9227. and it freezes before the End G-code runs — so banking on it stays
  9228. inside the print and never sees a swapped plate.
  9229. """
  9230. client = printer_manager.get_client(printer_id)
  9231. state = client.state if client else None
  9232. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9233. printer_manager.set_print_progress_callback(on_print_progress)
  9234. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9235. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9236. waiter = _bed_cool_waiters.get(printer_id)
  9237. if not waiter:
  9238. return
  9239. threshold = waiter["threshold"]
  9240. if bed_temp > threshold:
  9241. return
  9242. # Bed is at or below threshold — fire notification and remove waiter
  9243. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9244. if not waiter_info:
  9245. return # Another callback already handled it
  9246. bed_cool_logger = logging.getLogger(__name__)
  9247. bed_cool_logger.info(
  9248. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9249. bed_temp,
  9250. printer_id,
  9251. threshold,
  9252. )
  9253. try:
  9254. printer_info = printer_manager.get_printer(printer_id)
  9255. p_name = printer_info.name if printer_info else "Unknown"
  9256. async with async_session() as db:
  9257. await notification_service.on_bed_cooled(
  9258. printer_id=printer_id,
  9259. printer_name=p_name,
  9260. bed_temp=bed_temp,
  9261. threshold=threshold,
  9262. filename=waiter_info["filename"],
  9263. db=db,
  9264. )
  9265. except Exception as e:
  9266. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9267. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9268. async def on_drying_complete(printer_id: int, ams_id: int):
  9269. """Smart-plug auto-off-after-drying trigger (#1349).
  9270. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9271. manager walks all plugs linked to this printer and turns off only
  9272. the ones with ``auto_off_after_drying`` enabled, after their
  9273. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9274. dual-AMS dry that ends within the same MQTT push) call this once
  9275. per unit — the manager's ``_cancel_pending_off`` collapses
  9276. repeated scheduling on the same plug to one timer, so duplicate
  9277. fires are safe.
  9278. """
  9279. try:
  9280. async with async_session() as db:
  9281. await smart_plug_manager.on_drying_complete(printer_id, db)
  9282. except Exception as e:
  9283. logging.getLogger(__name__).warning(
  9284. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9285. printer_id,
  9286. ams_id,
  9287. e,
  9288. )
  9289. printer_manager.set_drying_complete_callback(on_drying_complete)
  9290. async def on_drying_cycle_end(printer_id: int, cycle):
  9291. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9292. from backend.app.services.spool_drying import record_drying_cycle
  9293. try:
  9294. async with async_session() as db:
  9295. await record_drying_cycle(db, printer_id, cycle)
  9296. except Exception as e:
  9297. logging.getLogger(__name__).warning(
  9298. "Failed to record drying for printer %d (AMS %d): %s",
  9299. printer_id,
  9300. cycle.ams_id,
  9301. e,
  9302. )
  9303. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9304. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9305. """Surface the read-back result of a spool assignment to the UI (#2582).
  9306. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9307. echoed back the filament id we pushed. We relay that as a websocket
  9308. event so the frontend can toast "loaded" / "assignment didn't take"
  9309. instead of the historic silent fire-and-forget, which made the
  9310. AMS→Studio hand-off feel random to users.
  9311. """
  9312. try:
  9313. from backend.app.services.spool_assignment_notifications import (
  9314. _slot_label_from_global_tray,
  9315. )
  9316. if ams_id == 255:
  9317. global_id = 254 + tray_id
  9318. elif ams_id >= 128:
  9319. global_id = ams_id
  9320. else:
  9321. global_id = ams_id * 4 + tray_id
  9322. slot_label = _slot_label_from_global_tray(global_id)
  9323. printer_info = printer_manager.get_printer(printer_id)
  9324. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9325. await ws_manager.broadcast(
  9326. {
  9327. "type": "spool_assignment_verified",
  9328. "printer_id": printer_id,
  9329. "printer_name": printer_name,
  9330. "ams_id": ams_id,
  9331. "tray_id": tray_id,
  9332. "slot": slot_label,
  9333. "verified": verified,
  9334. # Present on success: False means the filament setting landed
  9335. # but the K-profile (cali_idx) did not — the reporter's exact
  9336. # "loaded but no flow profile" symptom.
  9337. "kprofile_applied": detail.get("kprofile_applied", True),
  9338. # Present on failure: whether any tray telemetry was seen in
  9339. # the window (distinguishes "printer silent" from "printer
  9340. # stored something else").
  9341. "saw_tray": detail.get("saw_tray", False),
  9342. }
  9343. )
  9344. except Exception as e:
  9345. logging.getLogger(__name__).warning(
  9346. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9347. printer_id,
  9348. ams_id,
  9349. tray_id,
  9350. e,
  9351. )
  9352. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9353. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9354. """Persist a mid-print tray change for completion-time attribution.
  9355. AMS filament backup switches trays without telling the slicer, so the
  9356. tray-change log is the only record of which spool fed which layers.
  9357. Keeping it only in memory meant a restart mid-print charged everything
  9358. to the tray that finished the job.
  9359. """
  9360. try:
  9361. from backend.app.services.usage_tracker import record_tray_change
  9362. async with async_session() as db:
  9363. await record_tray_change(db, printer_id, tray_global, layer_num)
  9364. except Exception as e:
  9365. logging.getLogger(__name__).warning(
  9366. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9367. printer_id,
  9368. tray_global,
  9369. layer_num,
  9370. e,
  9371. )
  9372. printer_manager.set_tray_change_callback(on_tray_change)
  9373. # Initialize MQTT relay from settings
  9374. async with async_session() as db:
  9375. from backend.app.api.routes.settings import get_setting
  9376. mqtt_settings = {
  9377. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9378. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9379. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9380. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9381. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9382. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9383. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9384. }
  9385. await mqtt_relay.configure(mqtt_settings)
  9386. # Restore MQTT smart plug subscriptions
  9387. if mqtt_settings.get("mqtt_enabled"):
  9388. from backend.app.models.smart_plug import SmartPlug
  9389. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9390. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9391. mqtt_plugs = result.scalars().all()
  9392. restored = 0
  9393. for plug in mqtt_plugs:
  9394. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9395. restored += 1
  9396. if restored:
  9397. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9398. # Connect to all active printers
  9399. async with async_session() as db:
  9400. await init_printer_connections(db)
  9401. # Auto-connect to Spoolman if enabled
  9402. async with async_session() as db:
  9403. from backend.app.api.routes.settings import get_setting
  9404. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9405. spoolman_url = await get_setting(db, "spoolman_url")
  9406. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9407. try:
  9408. client = await init_spoolman_client(spoolman_url)
  9409. if await client.health_check():
  9410. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9411. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9412. field_ok = await client.ensure_tag_extra_field()
  9413. if not field_ok:
  9414. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9415. # Register the BambuStudio slicer-preset fields used by the
  9416. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9417. # unknown extra keys, so these must exist before any update
  9418. # that touches them.
  9419. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9420. if not await client.ensure_extra_field(field_name):
  9421. logging.warning(
  9422. "Spoolman extra field %r registration failed — "
  9423. "spool slicer-preset edits will return 502",
  9424. field_name,
  9425. )
  9426. else:
  9427. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9428. except Exception as e:
  9429. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9430. # Start the print scheduler
  9431. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9432. # Start the smart plug scheduler for time-based on/off
  9433. smart_plug_manager.start_scheduler()
  9434. # Start the Home Assistant sensor poller (#1148)
  9435. ha_sensor_manager.start()
  9436. location_ha_sensor_manager.start()
  9437. # Resume any pending auto-offs that were interrupted by restart
  9438. await smart_plug_manager.resume_pending_auto_offs()
  9439. # Start the notification digest scheduler
  9440. notification_service.start_digest_scheduler()
  9441. notify_live_activities.start()
  9442. notify_widgets.start()
  9443. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9444. # provider in reactions/both mode; the notification routes resync them.
  9445. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9446. # until the next provider save, not the whole startup.
  9447. try:
  9448. await telegram_reaction_poller.start()
  9449. except Exception as e:
  9450. logging.warning("Telegram reaction poller did not start: %s", e)
  9451. # Start the GitHub backup scheduler
  9452. await github_backup_service.start_scheduler()
  9453. # Start the local backup scheduler
  9454. await local_backup_service.start_scheduler()
  9455. await obico_detection_service.start()
  9456. # Start the library trash sweeper (#1008)
  9457. await library_trash_service.start_scheduler()
  9458. # Start the archive auto-purge sweeper (#1008 follow-up)
  9459. await archive_purge_service.start_scheduler()
  9460. # Start AMS history recording
  9461. start_ams_history_recording()
  9462. # Start printer sensor (nozzle / bed / chamber) history recording
  9463. start_printer_sensor_history_recording()
  9464. # Start printer runtime tracking
  9465. start_runtime_tracking()
  9466. # Start SpoolBuddy device watchdog
  9467. start_spoolbuddy_watchdog()
  9468. # Start camera stream orphan cleanup
  9469. start_camera_cleanup()
  9470. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9471. start_connection_watchdog()
  9472. # One-shot sweep for timelapse session directories orphaned by a crash
  9473. # or restart that happened mid-print (in-memory session tracking can't
  9474. # survive that, and nothing else reaps the leftover frames/output file)
  9475. try:
  9476. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9477. removed = cleanup_orphaned_timelapse_sessions()
  9478. if removed:
  9479. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9480. except Exception as e:
  9481. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9482. # Start expected-print TTL eviction (prevents memory leak when prints are
  9483. # registered but on_print_start never fires)
  9484. start_expected_prints_cleanup()
  9485. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9486. start_auth_cleanup()
  9487. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9488. from backend.app.services import announcements as announcements_service
  9489. announcements_service.start()
  9490. from backend.app.services.printer_media import start_printer_download_cleanup
  9491. start_printer_download_cleanup()
  9492. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9493. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9494. from backend.app.services.loop_watchdog import start_loop_watchdog
  9495. start_loop_watchdog()
  9496. # Initialize virtual printer manager and sync from DB
  9497. from backend.app.services.virtual_printer import virtual_printer_manager
  9498. virtual_printer_manager.set_session_factory(async_session)
  9499. virtual_printer_manager.set_printer_manager(printer_manager)
  9500. try:
  9501. await virtual_printer_manager.sync_from_db()
  9502. logging.info("Virtual printer manager synced from database")
  9503. except Exception as e:
  9504. logging.warning("Failed to sync virtual printers: %s", e)
  9505. yield
  9506. # Shutdown
  9507. print_scheduler.stop()
  9508. smart_plug_manager.stop_scheduler()
  9509. ha_sensor_manager.stop()
  9510. location_ha_sensor_manager.stop()
  9511. notification_service.stop_digest_scheduler()
  9512. await notify_live_activities.close()
  9513. await notify_widgets.close()
  9514. await telegram_reaction_poller.aclose()
  9515. github_backup_service.stop_scheduler()
  9516. local_backup_service.stop_scheduler()
  9517. library_trash_service.stop_scheduler()
  9518. archive_purge_service.stop_scheduler()
  9519. obico_detection_service.stop()
  9520. stop_ams_history_recording()
  9521. stop_printer_sensor_history_recording()
  9522. stop_runtime_tracking()
  9523. stop_spoolbuddy_watchdog()
  9524. stop_camera_cleanup()
  9525. stop_connection_watchdog()
  9526. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9527. stop_loop_watchdog()
  9528. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9529. # cleanly rather than waiting on a queue that nothing will ever fill.
  9530. try:
  9531. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9532. await shutdown_all_broadcasters()
  9533. except Exception as e:
  9534. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9535. stop_expected_prints_cleanup()
  9536. stop_auth_cleanup()
  9537. from backend.app.services import announcements as announcements_service
  9538. announcements_service.stop()
  9539. from backend.app.services.printer_media import stop_printer_download_cleanup
  9540. await stop_printer_download_cleanup()
  9541. printer_manager.disconnect_all()
  9542. slot_unlink_grace.reset()
  9543. await close_spoolman_client()
  9544. # Stop all virtual printer services
  9545. await virtual_printer_manager.stop_all()
  9546. await mqtt_smart_plug_service.disconnect(timeout=2)
  9547. await mqtt_relay.disconnect(timeout=2)
  9548. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9549. set_shared_http_client(None)
  9550. set_shared_makerworld_http_client(None)
  9551. set_shared_orca_http_client(None)
  9552. await _shared_cloud_http_client.aclose()
  9553. # Checkpoint WAL (SQLite only) and close all database connections
  9554. from backend.app.core.db_dialect import is_sqlite
  9555. if is_sqlite():
  9556. try:
  9557. async with engine.begin() as conn:
  9558. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9559. logging.info("WAL checkpoint completed")
  9560. except Exception as e:
  9561. logging.warning("WAL checkpoint failed: %s", e)
  9562. await engine.dispose()
  9563. app = FastAPI(
  9564. title=app_settings.app_name,
  9565. description="Archive and manage Bambu Lab 3MF files",
  9566. version=APP_VERSION,
  9567. lifespan=lifespan,
  9568. )
  9569. # Added first so it sits innermost, next to the routes: a refused header's value
  9570. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9571. app.add_middleware(RefusedHeaderResponseMask)
  9572. # =============================================================================
  9573. # Authentication Middleware - Secures ALL API routes by default
  9574. # =============================================================================
  9575. # Public routes that don't require authentication even when auth is enabled
  9576. PUBLIC_API_ROUTES = {
  9577. # Auth routes needed before/during login
  9578. "/api/v1/auth/status",
  9579. "/api/v1/auth/login",
  9580. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9581. # Advanced auth status needed for login page
  9582. "/api/v1/auth/advanced-auth/status",
  9583. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9584. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9585. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9586. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9587. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9588. # OIDC routes that must be reachable without a JWT
  9589. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9590. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9591. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9592. # Connected apps: the app's server swaps a code for the user's identity,
  9593. # authenticated by its client secret rather than a login token.
  9594. "/api/v1/connect/token",
  9595. # Version check for updates (no sensitive data)
  9596. "/api/v1/updates/version",
  9597. # Metrics endpoint handles its own prometheus_token authentication
  9598. "/api/v1/metrics",
  9599. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9600. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9601. # hostname / timezone / locale and the chrony NTP-gate state. The
  9602. # response contains user-set defaults and a public sync flag — no
  9603. # secrets. Without this entry the global auth middleware returns 401
  9604. # before the route handler runs, regardless of the route's own
  9605. # "no auth required" intent.
  9606. "/api/v1/system/appliance",
  9607. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9608. # authenticates with a long-lived ``camwall``-scoped token in the query
  9609. # string — exactly like the camera streams two lists below, and for the same
  9610. # reason (no header to put a JWT in). "Public" here only means the middleware
  9611. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9612. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9613. # plain ``camera_stream`` token does NOT open this door.
  9614. "/api/v1/camwall/printers",
  9615. # Overlay branding: the route enforces overlay-scoped token authentication.
  9616. "/api/v1/overlay-branding/logo",
  9617. }
  9618. # Route prefixes that are public (for routes with dynamic segments)
  9619. PUBLIC_API_PREFIXES = [
  9620. # WebSocket connections handle their own auth
  9621. "/api/v1/ws",
  9622. # OIDC authorize redirects — include provider_id in path
  9623. "/api/v1/auth/oidc/authorize/",
  9624. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9625. # a phone with no session, so no header can carry a JWT — the single-use
  9626. # capability token in the path IS the credential (same reasoning as the
  9627. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9628. # good/reject on the one archive the token was minted for.
  9629. "/api/v1/archives/confirm/",
  9630. ]
  9631. # Route patterns that are public (read-only display data)
  9632. # These are checked with "in path" - needed because browsers load images/videos
  9633. # via <img src> and <video src> which don't include Authorization headers
  9634. PUBLIC_API_PATTERNS = [
  9635. # Thumbnails
  9636. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9637. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9638. # Images and media
  9639. "/photos/", # /archives/{id}/photos/{filename}
  9640. "/project-image/", # /archives/{id}/project-image/{path}
  9641. "/qrcode", # /archives/{id}/qrcode
  9642. "/timelapse", # /archives/{id}/timelapse (video)
  9643. "/cover", # /printers/{id}/cover
  9644. "/icon", # /external-links/{id}/icon
  9645. # Camera (streams loaded via <img> tag)
  9646. "/camera/stream", # /printers/{id}/camera/stream
  9647. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9648. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9649. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9650. # string (same reasoning as the camera streams above — no header to carry a
  9651. # JWT). "Public" only means the middleware steps aside; the route still runs
  9652. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9653. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9654. "/overlay-status", # /printers/{id}/overlay-status
  9655. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9656. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9657. # download token in the URL path instead.
  9658. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9659. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9660. # and these patterns match by substring. Without its own entry the middleware
  9661. # 401s the slicer's header-less request before the route's token check runs,
  9662. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9663. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9664. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9665. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9666. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9667. ]
  9668. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9669. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9670. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9671. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9672. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9673. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9674. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9675. Invalid entries are dropped with a warning rather than failing startup, so
  9676. a typo in one origin doesn't take the whole deployment down.
  9677. """
  9678. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9679. if not raw:
  9680. return ()
  9681. valid: list[str] = []
  9682. for item in raw.split(","):
  9683. candidate = item.strip()
  9684. if not candidate:
  9685. continue
  9686. try:
  9687. parsed = urlparse(candidate)
  9688. except ValueError as e:
  9689. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9690. continue
  9691. if parsed.scheme not in ("http", "https"):
  9692. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9693. continue
  9694. if not parsed.netloc:
  9695. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9696. continue
  9697. if parsed.path and parsed.path != "/":
  9698. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9699. continue
  9700. if parsed.query or parsed.fragment:
  9701. _security_headers_logger.warning(
  9702. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9703. )
  9704. continue
  9705. if "*" in parsed.netloc:
  9706. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9707. continue
  9708. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9709. if valid:
  9710. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9711. return tuple(valid)
  9712. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9713. def _frame_ancestors(default_value: str) -> str:
  9714. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9715. ``default_value`` is the strict directive used when the operator has not
  9716. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9717. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9718. Settings URL builder's preview). When trusted origins
  9719. are configured, ``'self'`` is always included so same-origin embedding never
  9720. breaks even if an operator forgets to add their own origin to the list.
  9721. """
  9722. if _TRUSTED_FRAME_ORIGINS:
  9723. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9724. return f"frame-ancestors {default_value};"
  9725. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9726. # patterns are anchored on the exact emitted name so the relaxed policies
  9727. # below can never apply to any other asset.
  9728. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9729. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9730. # -> /assets/pdf.worker.min-<hash>.js
  9731. # Vite also emits a one-line chunk under the second name that only exports the
  9732. # worker's URL. The page imports it as a module, and a module script is run
  9733. # under the importing document's policy, never its own response's, so it
  9734. # matching as well changes nothing.
  9735. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9736. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9737. @app.middleware("http")
  9738. async def security_headers_middleware(request, call_next):
  9739. """Add standard HTTP security headers to every response."""
  9740. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9741. # changes nothing for Bambuddy's own pages — index.html has no inline
  9742. # scripts since the SW registration moved to /sw-register.js. The reason
  9743. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9744. # script injected into the HTML on the edge, with a fresh hash on every
  9745. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9746. # it clones the same nonce onto its injected <script>, and the inline
  9747. # script passes the policy without us needing 'unsafe-inline'. See
  9748. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9749. csp_nonce = secrets.token_urlsafe(16)
  9750. # Routes that render their own HTML need it too, or their inline script is
  9751. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9752. # one that does: it submits its own form so a verdict still costs one tap.
  9753. request.state.csp_nonce = csp_nonce
  9754. response = await call_next(request)
  9755. response.headers["X-Content-Type-Options"] = "nosniff"
  9756. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9757. # browsers honour CSP frame-ancestors instead, and the legacy
  9758. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9759. # When operators have explicitly allowlisted trusted frame origins (#1191
  9760. # — typically Home Assistant on a different port), drop X-Frame-Options
  9761. # and let the CSP-side frame-ancestors directive govern embedding.
  9762. if not _TRUSTED_FRAME_ORIGINS:
  9763. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9764. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9765. # Content-Security-Policy for the React SPA.
  9766. # Notes:
  9767. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9768. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9769. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9770. # - media-src blob:: timelapse video player uses Blob URLs.
  9771. # - font-src data:: some icon fonts are embedded as data URIs.
  9772. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9773. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9774. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9775. # default CSP would render a blank page.
  9776. response.headers["Content-Security-Policy"] = (
  9777. "default-src 'self'; "
  9778. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9779. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9780. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9781. "connect-src 'self'; "
  9782. "font-src 'self' data: https://fonts.gstatic.com; "
  9783. "worker-src 'self' blob:; "
  9784. "object-src 'none'; "
  9785. "base-uri 'self'; " + _frame_ancestors("'none'")
  9786. )
  9787. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9788. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9789. # its emscripten/embind glue generates invoker functions with `new
  9790. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9791. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9792. # own response — not the document's — so relaxing it here confines
  9793. # eval to that DOM-less worker context. The document policy below
  9794. # stays nonce-strict, and this response header has no effect when the
  9795. # file is merely fetched (a fetch's CSP is enforced against the
  9796. # requesting document, not the resource's own headers).
  9797. response.headers["Content-Security-Policy"] = (
  9798. "default-src 'self'; "
  9799. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9800. "connect-src 'self'; "
  9801. "object-src 'none'; "
  9802. "base-uri 'self'; " + _frame_ancestors("'none'")
  9803. )
  9804. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9805. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9806. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9807. # rule as the STEP worker above: the policy that governs a dedicated
  9808. # worker is the one delivered with its own script, so the wasm compile
  9809. # has to be permitted here rather than on the document. Unlike the STEP
  9810. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9811. response.headers["Content-Security-Policy"] = (
  9812. "default-src 'self'; "
  9813. "script-src 'self' 'wasm-unsafe-eval'; "
  9814. "connect-src 'self'; "
  9815. "object-src 'none'; "
  9816. "base-uri 'self'; " + _frame_ancestors("'none'")
  9817. )
  9818. else:
  9819. # The streaming overlay is embedded same-origin by the URL builder's
  9820. # preview in Settings (#1422), so this branch allows 'self'.
  9821. # Embedding from anywhere else is still refused: 'self'
  9822. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9823. # a clickjacking page on another host is blocked exactly as before.
  9824. # (The overlay draws status over a camera feed and its only interactive
  9825. # element is the logo link, so there is nothing to bait a click into
  9826. # even from a same-origin framer.) Cross-origin embedding of the
  9827. # overlay — Home Assistant on another port — remains what
  9828. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9829. # allowlist in.
  9830. #
  9831. # The connected-app consent page (/connect/authorize) gets the same
  9832. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9833. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9834. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9835. # requires every ancestor to be this origin, so a foreign page -- a
  9836. # sidebar link's site included -- still cannot frame the consent
  9837. # screen to bait a click.
  9838. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9839. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9840. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9841. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9842. # the policy served with their own script, so each gets it in its own
  9843. # branch above and the document policy stays as strict as it was.
  9844. response.headers["Content-Security-Policy"] = (
  9845. "default-src 'self'; "
  9846. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9847. "style-src 'self' 'unsafe-inline'; "
  9848. "img-src 'self' data: blob:; "
  9849. "media-src 'self' blob:; "
  9850. "connect-src 'self' ws: wss:; "
  9851. "font-src 'self' data:; "
  9852. "object-src 'none'; "
  9853. "base-uri 'self'; "
  9854. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9855. )
  9856. if request.url.scheme == "https":
  9857. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9858. return response
  9859. @app.middleware("http")
  9860. async def auth_middleware(request, call_next):
  9861. """Enforce authentication on all API routes when auth is enabled.
  9862. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9863. regardless of whether individual routes have auth dependencies.
  9864. """
  9865. from starlette.responses import JSONResponse
  9866. path = request.url.path
  9867. # Only apply to API routes
  9868. if not path.startswith("/api/"):
  9869. return await call_next(request)
  9870. # Allow public routes
  9871. if path in PUBLIC_API_ROUTES:
  9872. return await call_next(request)
  9873. # Allow public prefixes
  9874. for prefix in PUBLIC_API_PREFIXES:
  9875. if path.startswith(prefix):
  9876. return await call_next(request)
  9877. # Allow public patterns (read-only display data like thumbnails)
  9878. for pattern in PUBLIC_API_PATTERNS:
  9879. if pattern in path:
  9880. return await call_next(request)
  9881. # Check if auth is enabled. Fail CLOSED on any exception during the
  9882. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9883. # an attacker who could force a DB exception (e.g. file-descriptor
  9884. # exhaustion via login flood) bypass auth on every protected endpoint.
  9885. # Only the probe is guarded: the request itself runs outside the try, so an
  9886. # error in a route surfaces as the 500 it is rather than as an auth outage.
  9887. try:
  9888. async with async_session() as db:
  9889. from backend.app.core.auth import is_auth_enabled
  9890. auth_enabled = await is_auth_enabled(db)
  9891. except Exception:
  9892. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9893. return JSONResponse(
  9894. status_code=503,
  9895. content={"detail": "Authentication service temporarily unavailable"},
  9896. )
  9897. if not auth_enabled:
  9898. # Auth disabled, allow all requests
  9899. return await call_next(request)
  9900. # Auth is enabled - require valid token
  9901. auth_header = request.headers.get("Authorization")
  9902. x_api_key = request.headers.get("X-API-Key")
  9903. # Check for API key auth first
  9904. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9905. # API key authentication - let the request through to be validated by route handler
  9906. # API keys are validated per-route since they have different permission levels
  9907. return await call_next(request)
  9908. # Check for JWT auth
  9909. if not auth_header or not auth_header.startswith("Bearer "):
  9910. return JSONResponse(
  9911. status_code=401,
  9912. content={"detail": "Authentication required"},
  9913. headers={"WWW-Authenticate": "Bearer"},
  9914. )
  9915. # Validate JWT token
  9916. import jwt
  9917. try:
  9918. from backend.app.core.auth import (
  9919. ALGORITHM,
  9920. SECRET_KEY,
  9921. _is_token_fresh,
  9922. get_user_by_username,
  9923. is_jti_revoked,
  9924. )
  9925. token = auth_header.replace("Bearer ", "")
  9926. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9927. username = payload.get("sub")
  9928. if not username:
  9929. raise ValueError("No username in token")
  9930. jti = payload.get("jti")
  9931. if not jti:
  9932. raise ValueError("No jti in token")
  9933. iat = payload.get("iat")
  9934. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9935. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9936. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9937. async with async_session() as db:
  9938. if await is_jti_revoked(jti, db):
  9939. return JSONResponse(
  9940. status_code=401,
  9941. content={"detail": "Token has been revoked"},
  9942. headers={"WWW-Authenticate": "Bearer"},
  9943. )
  9944. user = await get_user_by_username(db, username)
  9945. if not user or not user.is_active:
  9946. return JSONResponse(
  9947. status_code=401,
  9948. content={"detail": "User not found or inactive"},
  9949. headers={"WWW-Authenticate": "Bearer"},
  9950. )
  9951. if not _is_token_fresh(iat, user):
  9952. return JSONResponse(
  9953. status_code=401,
  9954. content={"detail": "Token no longer valid"},
  9955. headers={"WWW-Authenticate": "Bearer"},
  9956. )
  9957. except jwt.ExpiredSignatureError:
  9958. return JSONResponse(
  9959. status_code=401,
  9960. content={"detail": "Token has expired"},
  9961. headers={"WWW-Authenticate": "Bearer"},
  9962. )
  9963. except (jwt.InvalidTokenError, ValueError):
  9964. return JSONResponse(
  9965. status_code=401,
  9966. content={"detail": "Invalid token"},
  9967. headers={"WWW-Authenticate": "Bearer"},
  9968. )
  9969. except Exception:
  9970. # Not a bad token but a failure checking it (database, pool): refuse,
  9971. # as for the probe above, rather than answer 401 -- the frontend reads
  9972. # a 401 from /auth/me as final and signs the user out.
  9973. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  9974. return JSONResponse(
  9975. status_code=503,
  9976. content={"detail": "Authentication service temporarily unavailable"},
  9977. )
  9978. return await call_next(request)
  9979. @app.middleware("http")
  9980. async def trace_id_middleware(request, call_next):
  9981. """Stamp every HTTP request with a trace ID and echo it back.
  9982. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9983. @app.middleware decorators LIFO, so the last-decorated runs first
  9984. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9985. which means auth-middleware log lines (and every line emitted on the
  9986. way down to and back from the route handler) all carry the same
  9987. trace ID. If we put it before auth, auth's logs would be stamped
  9988. with the *previous* request's ID — useless for correlation.
  9989. Honours an inbound ``X-Trace-Id`` header so callers running their
  9990. own tracing can correlate their span IDs with our log lines, but
  9991. only if the value passes the whitelist gate in
  9992. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9993. rejected (too long, contains control chars, etc.) silently triggers
  9994. a freshly minted server-side ID rather than failing the request.
  9995. The minted (or echoed) ID is set on a ContextVar so that every log
  9996. record emitted during the request — application logs *and* uvicorn's
  9997. access log — carries it via TraceIDFilter, and is also written to
  9998. the ``X-Trace-Id`` response header so clients can pin a server-side
  9999. log search to the exact request they made.
  10000. """
  10001. from backend.app.core.trace import (
  10002. generate_trace_id,
  10003. normalise_inbound_trace_id,
  10004. trace_id_var,
  10005. )
  10006. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10007. trace_id = inbound if inbound is not None else generate_trace_id()
  10008. token = trace_id_var.set(trace_id)
  10009. try:
  10010. response = await call_next(request)
  10011. finally:
  10012. # Reset the ContextVar so a record emitted in a totally
  10013. # unrelated background task that just happens to inherit this
  10014. # context doesn't keep referencing this request's ID forever.
  10015. # In practice ContextVar.reset is best-effort under asyncio
  10016. # task-spawn semantics, but the cost is one attribute write so
  10017. # we may as well do it.
  10018. trace_id_var.reset(token)
  10019. response.headers["X-Trace-Id"] = trace_id
  10020. return response
  10021. # API routes
  10022. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10023. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10024. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10025. app.include_router(users.router, prefix=app_settings.api_prefix)
  10026. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10027. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10028. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10029. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10030. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10031. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10032. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10033. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10034. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10035. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10036. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10037. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10038. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10039. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10040. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10041. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10042. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10043. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10044. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10045. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10046. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10047. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10048. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10049. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10050. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10051. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10052. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10053. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10054. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10055. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10056. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10057. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10058. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10059. app.include_router(library.router, prefix=app_settings.api_prefix)
  10060. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10061. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10062. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10063. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10064. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10065. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10066. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10067. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10068. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10069. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10070. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10071. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10072. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10073. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10074. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10075. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10076. app.include_router(system.router, prefix=app_settings.api_prefix)
  10077. app.include_router(support.router, prefix=app_settings.api_prefix)
  10078. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10079. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10080. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10081. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10082. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10083. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10084. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10085. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10086. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10087. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10088. # Serve static files (React build)
  10089. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10090. # Compressed, and cached for good where Vite hashed the name (#3175).
  10091. app.mount(
  10092. "/assets",
  10093. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10094. name="assets",
  10095. )
  10096. if (app_settings.static_dir / "img").exists():
  10097. app.mount(
  10098. "/img",
  10099. StaticFiles(directory=app_settings.static_dir / "img"),
  10100. name="img",
  10101. )
  10102. if (app_settings.static_dir / "icons").exists():
  10103. app.mount(
  10104. "/icons",
  10105. StaticFiles(directory=app_settings.static_dir / "icons"),
  10106. name="icons",
  10107. )
  10108. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10109. # falls through to the SPA catch-all and returns index.html, which the
  10110. # browser's font sanitizer rejects ("downloadable font: rejected by
  10111. # sanitizer").
  10112. if (app_settings.static_dir / "fonts").exists():
  10113. app.mount(
  10114. "/fonts",
  10115. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10116. name="fonts",
  10117. )
  10118. @app.get("/")
  10119. async def serve_frontend():
  10120. """Serve the React frontend."""
  10121. index_file = app_settings.static_dir / "index.html"
  10122. if index_file.exists():
  10123. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10124. return {
  10125. "message": "Bambuddy API",
  10126. "docs": "/docs",
  10127. "frontend": "Build and place React app in /static directory",
  10128. }
  10129. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10130. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10131. # forever, but the HTML wrapping it is the only file that knows which hash
  10132. # is current. Without explicit cache-control headers Chromium decides
  10133. # heuristically (typically 10% of the time since Last-Modified) and on
  10134. # long-running kiosks happily serves stale HTML across browser restarts.
  10135. # That stale HTML references an old bundle hash, the old bundle is also
  10136. # in the disk cache, and the user ends up running pre-update JS forever
  10137. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10138. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10139. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10140. @app.get("/health")
  10141. async def health_check():
  10142. """Health check endpoint."""
  10143. return {"status": "healthy"}
  10144. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10145. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10146. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10147. # in deployment debugging.
  10148. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10149. async def serve_manifest():
  10150. """Serve PWA manifest."""
  10151. manifest_file = app_settings.static_dir / "manifest.json"
  10152. if manifest_file.exists():
  10153. return FileResponse(manifest_file, media_type="application/manifest+json")
  10154. return {"error": "Manifest not found"}
  10155. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10156. async def serve_service_worker():
  10157. """Serve service worker."""
  10158. sw_file = app_settings.static_dir / "sw.js"
  10159. if sw_file.exists():
  10160. return FileResponse(
  10161. sw_file,
  10162. media_type="application/javascript",
  10163. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10164. )
  10165. return {"error": "Service worker not found"}
  10166. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10167. async def serve_sw_register():
  10168. """Serve the service-worker registration bootstrap script.
  10169. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10170. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10171. """
  10172. reg_file = app_settings.static_dir / "sw-register.js"
  10173. if reg_file.exists():
  10174. return FileResponse(reg_file, media_type="application/javascript")
  10175. return {"error": "sw-register.js not found"}
  10176. # ── GCode viewer static files ────────────────────────────────────────────────
  10177. # Catch-all route for React Router (must be last)
  10178. @app.get("/{full_path:path}")
  10179. async def serve_spa(full_path: str):
  10180. """Serve React app for client-side routing."""
  10181. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10182. if full_path.startswith("api/"):
  10183. from fastapi import HTTPException
  10184. raise HTTPException(status_code=404, detail="Not found")
  10185. index_file = app_settings.static_dir / "index.html"
  10186. if index_file.exists():
  10187. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10188. return {"error": "Frontend not built"}