main.py 617 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741
  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 shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Archives whose last run still has work after it completed: the timelapse
  512. # scan and the layer timelapse stitch. Both tell their run from a later one by
  513. # the archive's start time, so a queue dispatch of the same file must not start
  514. # a new run on the archive until they end (_claim_reusable_archive in the
  515. # scheduler). archive_id -> number of such tasks.
  516. _archive_runs_finishing: dict[int, int] = {}
  517. async def _while_run_finishes(archive_id: int, work):
  518. """Run ``work`` with the archive marked as still finishing its last run.
  519. Marked by the caller's spawn already: see ``_mark_run_finishing``."""
  520. try:
  521. return await work
  522. finally:
  523. left = _archive_runs_finishing.get(archive_id, 0) - 1
  524. if left > 0:
  525. _archive_runs_finishing[archive_id] = left
  526. else:
  527. _archive_runs_finishing.pop(archive_id, None)
  528. def _mark_run_finishing(archive_id: int, work):
  529. """``work`` wrapped to keep the archive marked until it ends. Marked now,
  530. before the task starts, so no dispatch between the spawn and its first
  531. step can take the archive."""
  532. _archive_runs_finishing[archive_id] = _archive_runs_finishing.get(archive_id, 0) + 1
  533. return _while_run_finishes(archive_id, work)
  534. # Track printers waiting for bed to cool after print completion.
  535. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  536. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  537. _bed_cool_waiters: dict[int, dict] = {}
  538. # Track printers where the user explicitly stopped the print from the queue UI.
  539. # When on_print_complete fires with status "failed" for these printers we treat it
  540. # as "cancelled" (stopped by user) so the correct notification email is sent.
  541. _user_stopped_printers: set[int] = set()
  542. # Printers whose running print the kill switch stopped. Their completion is a
  543. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  544. _kill_switch_stopped: set[int] = set()
  545. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  546. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  547. # holds the previous observation so we only fire on the True → False edge (a
  548. # False → False repeat doesn't notify; an initial False at startup doesn't
  549. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  550. # holds the per-printer pending asyncio task that fires the notification
  551. # after a debounce window — cancelled if the printer reconnects before the
  552. # window elapses, so transient MQTT blips don't flood the user.
  553. _printer_last_connected: dict[int, bool] = {}
  554. # Printers whose relay offline event went out, so the reconnect publishes the
  555. # matching online event and a blip shorter than the debounce publishes neither.
  556. _printer_offline_published: set[int] = set()
  557. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  558. # Debounce: a printer must stay offline this long before we notify. Sized
  559. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  560. # so a single stale-trigger cooldown isn't enough to fire — only a real
  561. # offline that survives one reconnect attempt notifies.
  562. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  563. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  564. # when status="failed" to label the print's failure_reason in archives.
  565. #
  566. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  567. # which is wrong on two counts:
  568. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  569. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  570. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  571. # the public wiki) as part of its user-cancel sequence. Matching on the module
  572. # alone caused user-cancellations to be archived as "Layer shift" failures.
  573. # We now match by full short code only — anything not in this map leaves
  574. # failure_reason=None rather than guessing.
  575. # Values are the canonical camelCase failure-reason keys, NOT display labels
  576. # (issue #2974). The vocabulary is enforced on writes by
  577. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  578. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  579. # Statistics breakdown. Storing a label here instead put a second spelling of
  580. # the same cause into one column: the Failure Analysis widget groups on the raw
  581. # value, so a print the backend classified and an identical one a user
  582. # classified counted as two different reasons, and the label form could never
  583. # be translated because there was no key for ``t()`` to resolve.
  584. _HMS_FAILURE_REASONS: dict[str, str] = {
  585. # Layer shift / step loss
  586. "0300_4057": "layerShift",
  587. "0300_4068": "layerShift",
  588. "0300_800C": "layerShift",
  589. # Filament runout (printer-side & per-AMS-slot)
  590. "0300_8004": "filamentRunout",
  591. "0700_8011": "filamentRunout",
  592. "0701_8011": "filamentRunout",
  593. "0702_8011": "filamentRunout",
  594. "0703_8011": "filamentRunout",
  595. "0704_8011": "filamentRunout",
  596. "0705_8011": "filamentRunout",
  597. "0706_8011": "filamentRunout",
  598. "0707_8011": "filamentRunout",
  599. "07FF_8011": "filamentRunout",
  600. # Clogged nozzle / extruder
  601. "0300_4006": "cloggedNozzle",
  602. "0300_8016": "cloggedNozzle",
  603. "0300_801C": "cloggedNozzle",
  604. "0700_8003": "cloggedNozzle",
  605. "0700_8007": "cloggedNozzle",
  606. "0700_8013": "cloggedNozzle",
  607. "0701_8003": "cloggedNozzle",
  608. "0701_8007": "cloggedNozzle",
  609. "0701_8013": "cloggedNozzle",
  610. "0702_8003": "cloggedNozzle",
  611. # AI print monitoring — spaghetti / the model coming off the plate.
  612. # `spaghettiDetached` is a key the archive editor already offers for this
  613. # failure mode, not a new one, so a derived reason opens the dropdown on
  614. # that option rather than blank — and survives the next save, which clears
  615. # any value the editor does not recognise.
  616. #
  617. # A module-0x0C row is safe here despite the warning above: that warning is
  618. # about matching on the module alone, and 0C00_8042 is a full short code
  619. # with a documented meaning ("The AI print monitor has detected a spaghetti
  620. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  621. # cannot collide.
  622. #
  623. # 0300_8003's own text ends "before continuing your print", but on an X2D
  624. # it arrives with the print already paused, offering only
  625. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  626. #
  627. # Two neighbours are left out on purpose, so this does not get re-derived:
  628. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  629. # reads as a warning about a print that is still running, not a halt.
  630. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  631. # the waste chute. That is not the print failing.
  632. #
  633. # That line is drawn from the text, not from `severity`, because severity
  634. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  635. # module/error word with no level in it, and bambu_mqtt.py gives every
  636. # print_error entry a flat severity=3. Matching on the short code alone is
  637. # the right shape for derive_failure_reason, not an omission.
  638. "0300_8003": "spaghettiDetached",
  639. "0C00_8042": "spaghettiDetached",
  640. }
  641. def _hms_short_code(attr: int, code: int | str) -> str:
  642. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  643. if isinstance(code, str):
  644. code_int = int(code.replace("0x", ""), 16) if code else 0
  645. else:
  646. code_int = int(code or 0)
  647. attr_int = int(attr or 0)
  648. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  649. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  650. """Derive the failure_reason key for an archived print.
  651. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  652. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  653. no HMS code matches (don't guess — null is honest). The keys are the
  654. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  655. translated at render time.
  656. """
  657. if status in ("aborted", "cancelled"):
  658. return "userCancelled"
  659. if status != "failed":
  660. return None
  661. for err in hms_errors or []:
  662. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  663. if short_code in _HMS_FAILURE_REASONS:
  664. return _HMS_FAILURE_REASONS[short_code]
  665. return None
  666. # Track created_by_id for expected prints so the user email can be sent even when
  667. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  668. # {(printer_id, filename): created_by_id}
  669. _expected_print_creators: dict[tuple[int, str], int] = {}
  670. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  671. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  672. # tag tuple changes for the slot. Cleared when the slot is reported empty
  673. # so remove + reinsert reliably re-prompts the UI.
  674. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  675. async def _broadcast_unknown_tag(
  676. *,
  677. printer_id: int,
  678. ams_id: int,
  679. tray_id: int,
  680. tag_uid: str,
  681. tray_uuid: str,
  682. tray_type: str | None = None,
  683. tray_color: str | None = None,
  684. tray_sub_brands: str | None = None,
  685. tray_count: int | None = None,
  686. ) -> None:
  687. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  688. _logger = logging.getLogger(__name__)
  689. slot_key = (ams_id, tray_id)
  690. tag_key = (tag_uid or "", tray_uuid or "")
  691. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  692. if per_printer.get(slot_key) == tag_key:
  693. _logger.debug(
  694. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  695. printer_id,
  696. ams_id,
  697. tray_id,
  698. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  699. )
  700. return
  701. _logger.info(
  702. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  703. printer_id,
  704. ams_id,
  705. tray_id,
  706. tray_type,
  707. tray_color,
  708. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  709. )
  710. # Broadcast first; only commit the dedup if the WS write succeeds.
  711. # If broadcast raises, the next MQTT push retries instead of being
  712. # permanently silenced by a poisoned dedup entry.
  713. await ws_manager.broadcast(
  714. {
  715. "type": "unknown_tag",
  716. "printer_id": printer_id,
  717. "ams_id": ams_id,
  718. "tray_id": tray_id,
  719. "tag_uid": tag_uid,
  720. "tray_uuid": tray_uuid,
  721. "tray_type": tray_type,
  722. "tray_color": tray_color,
  723. "tray_sub_brands": tray_sub_brands,
  724. "tray_count": tray_count,
  725. }
  726. )
  727. per_printer[slot_key] = tag_key
  728. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  729. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  730. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  731. if per_printer is None:
  732. return
  733. per_printer.pop((ams_id, tray_id), None)
  734. # TTL for expected-print entries: evict registrations older than this to prevent
  735. # unbounded growth when a print is registered but never starts (e.g. printer
  736. # disconnect, app restart, print started from the printer panel).
  737. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  738. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  739. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  740. # Cleanup loop interval
  741. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  742. _expected_prints_cleanup_task: asyncio.Task | None = None
  743. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  744. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  745. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  746. possible_keys: list[tuple[int, str]] = []
  747. filename = (state.gcode_file or state.current_print or "").strip()
  748. subtask_name = (state.subtask_name or "").strip()
  749. if subtask_name:
  750. possible_keys.append((printer_id, subtask_name))
  751. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  752. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  753. if filename:
  754. base_name = filename.rsplit("/", 1)[-1]
  755. if base_name.endswith(".gcode.3mf"):
  756. root_name = base_name[: -len(".gcode.3mf")]
  757. possible_keys.append((printer_id, root_name))
  758. possible_keys.append((printer_id, base_name))
  759. possible_keys.append((printer_id, f"{root_name}.gcode"))
  760. possible_keys.append((printer_id, f"{root_name}.3mf"))
  761. elif base_name.endswith(".3mf"):
  762. root_name = base_name[: -len(".3mf")]
  763. possible_keys.append((printer_id, root_name))
  764. possible_keys.append((printer_id, base_name))
  765. elif base_name.endswith(".gcode"):
  766. root_name = base_name[: -len(".gcode")]
  767. possible_keys.append((printer_id, root_name))
  768. possible_keys.append((printer_id, f"{root_name}.3mf"))
  769. possible_keys.append((printer_id, base_name))
  770. else:
  771. possible_keys.append((printer_id, base_name))
  772. possible_keys.append((printer_id, f"{base_name}.3mf"))
  773. return possible_keys
  774. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  775. """The id of who started the print, unless that user has been deleted since.
  776. Deleting a user forgets them in printer_manager, but a print that ended a
  777. moment before still holds them.
  778. """
  779. if not print_user or print_user.get("user_id") is None:
  780. return None
  781. from backend.app.models.user import User
  782. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  783. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  784. """Check the cheap, process-local print ownership signals."""
  785. if printer_manager.get_current_print_user(printer_id):
  786. return True
  787. return any(
  788. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  789. for key in _build_status_print_keys(printer_id, state)
  790. )
  791. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  792. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  793. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  794. async def _printing_archive_without_job_id(
  795. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  796. ):
  797. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  798. An archive with a real id of its own is a print that reported one: a "0"
  799. print is not it, even under the same name (one whose completion was missed
  800. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  801. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  802. """
  803. from backend.app.models.archive import PrintArchive
  804. query = select(PrintArchive).where(
  805. PrintArchive.printer_id == printer_id,
  806. PrintArchive.status == "printing",
  807. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  808. )
  809. if dispatched_only:
  810. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  811. if live_only:
  812. query = query.where(PrintArchive.deleted_at.is_(None))
  813. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  814. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  815. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  816. """The archive of the print running on ``printer_id``, or None (#3327).
  817. By the print's subtask_id first, which the firmware mints per print; with
  818. ``printing_only`` only an archive that is still printing (a leftover row of
  819. a completion never seen must not stand in for another job). A print
  820. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  821. screen) reports subtask_id "0", which links it to nothing: the archive
  822. Bambuddy bound to the running print comes next, the one completion charges
  823. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  824. own prints, so with ``by_name`` a "0" print last falls back to its printing
  825. archive under the name the printer reports. That can be an earlier run of
  826. the same name whose completion was missed while Bambuddy was down: good
  827. enough for a plate label or a cover, not for which objects skip-objects
  828. offers, so those callers leave it off. None until the archive exists, and
  829. never a deleted one.
  830. """
  831. from backend.app.models.archive import PrintArchive
  832. from backend.app.services.print_log import open_run_on_printer
  833. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  834. if subtask_id not in ("", "0"):
  835. # The run open on the printer for this job: the archive row is shared
  836. # by every plate of it, its printer and job id the latest start's.
  837. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  838. if run is not None and run.archive_id is not None:
  839. archive = await db.scalar(
  840. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  841. )
  842. if archive is not None:
  843. return archive
  844. query = select(PrintArchive).where(
  845. PrintArchive.printer_id == printer_id,
  846. PrintArchive.subtask_id == subtask_id,
  847. PrintArchive.deleted_at.is_(None),
  848. )
  849. if printing_only:
  850. query = query.where(PrintArchive.status == "printing")
  851. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  852. if archive is not None:
  853. return archive
  854. bound = next(
  855. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  856. None,
  857. )
  858. if bound is not None:
  859. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  860. if not by_name or subtask_id != "0":
  861. return None
  862. reported = _reported_print_names(printer_id, state)
  863. if not reported:
  864. return None
  865. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  866. def _bind_active_print(
  867. printer_id: int,
  868. archive_id: int,
  869. archive_filename: str | None,
  870. filename: str | None = None,
  871. subtask_name: str | None = None,
  872. ) -> None:
  873. """Track a running print under every name its completion may report.
  874. One set for every path that binds a print (new archive, expected print,
  875. restart resume, fallback): the archive's file name, the name the printer
  876. reported, and the subtask with and without ``.3mf``. Paths that registered
  877. fewer names lost the bound archive at completion, and with it the plate
  878. restore's height (#3240), whenever MQTT reported a name they had left out.
  879. """
  880. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  881. if name:
  882. _active_prints[(printer_id, name)] = archive_id
  883. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  884. """The archive of the run open on the printer, if it is still there.
  885. With ``subtask_id``, only a run of that job."""
  886. try:
  887. from backend.app.models.archive import PrintArchive
  888. from backend.app.services.print_log import open_run_on_printer
  889. async with async_session() as db:
  890. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  891. if run is None or run.archive_id is None:
  892. return None
  893. return await db.scalar(
  894. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  895. )
  896. except Exception as e:
  897. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  898. return None
  899. async def _open_run_for(archive_id: int, printer_id: int) -> None:
  900. """Write the run of the print that just started on the archive (archive
  901. redesign). In a session of its own and never in the way of the print
  902. start: until its readers move over, the archive still carries the print.
  903. The archive's start must be committed before."""
  904. try:
  905. from backend.app.models.archive import PrintArchive
  906. from backend.app.models.printer import Printer
  907. from backend.app.services.print_log import open_run
  908. async with async_session() as db:
  909. archive = await db.get(PrintArchive, archive_id)
  910. if archive is None:
  911. return
  912. printer_name = await db.scalar(select(Printer.name).where(Printer.id == printer_id))
  913. await open_run(
  914. db,
  915. archive,
  916. printer_id=printer_id,
  917. printer_name=printer_name,
  918. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  919. )
  920. await db.commit()
  921. except Exception as e:
  922. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  923. def _mark_owned_if_dispatched(archive) -> None:
  924. """Remember a running print's archive as Bambuddy's when it carries a
  925. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  926. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  927. if archive.billing_run_id is not None or archive.created_by_id is not None:
  928. _owned_print_archive_ids.add(archive.id)
  929. async def _is_printer_kill_switch_enabled_cached() -> bool:
  930. """Return the kill-switch setting without querying on every MQTT frame."""
  931. global _kill_switch_setting_cache
  932. now = time.monotonic()
  933. if _kill_switch_setting_cache is not None:
  934. enabled, expires_at = _kill_switch_setting_cache
  935. if now < expires_at:
  936. return enabled
  937. async with async_session() as db:
  938. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  939. enabled = await is_printer_kill_switch_enabled(db)
  940. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  941. return enabled
  942. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  943. """Resolve whether the current print was started by Bambuddy.
  944. ``None`` means identity is not yet safe to decide. The kill switch must
  945. defer in that case: stopping a print is irreversible, and the first status
  946. frames after a restart may arrive before all subtask fields are populated.
  947. """
  948. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  949. return True
  950. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  951. # printer's screen) play gcode from its read-only system partition, where no
  952. # user file can be. Only that path counts: a calibration *name* proves
  953. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  954. # path, and any print can be given that name.
  955. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  956. return True
  957. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  958. # which nothing distinguishes from a user's file given that name, so it is
  959. # not exempt: with the kill switch on, calibrate on those printers with the
  960. # switch off.
  961. possible_keys = _build_status_print_keys(printer_id, state)
  962. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  963. # is on disk. subtask_id is minted per print and pins the answer to the job
  964. # actually running, rather than to an unrelated one that reuses a filename.
  965. raw_subtask_id = getattr(state, "subtask_id", None)
  966. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  967. if subtask_id == "":
  968. # Not reported yet: the first frames after a restart can lack it.
  969. return None
  970. from backend.app.models.archive import PrintArchive
  971. if subtask_id == "0":
  972. # A print started outside the cloud from Bambu Studio, Handy or the
  973. # printer's screen reports "0", so there is no id to match: one of
  974. # Bambuddy's printing archives on this printer under the name the
  975. # printer reports, compared as the printer echoes names (spaces become
  976. # underscores). Nothing reported to compare yet: wait.
  977. reported = _reported_print_names(printer_id, state)
  978. if not reported:
  979. return None
  980. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  981. else:
  982. from backend.app.services.print_log import open_run_on_printer
  983. # This job's run open on the printer: the archive is shared by every
  984. # plate of it, and its status, printer and job id are the latest
  985. # start's, which may be another printer's.
  986. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  987. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  988. if archive is None:
  989. result = await db.execute(
  990. select(PrintArchive)
  991. .where(
  992. PrintArchive.printer_id == printer_id,
  993. PrintArchive.status == "printing",
  994. PrintArchive.subtask_id == subtask_id,
  995. )
  996. .order_by(PrintArchive.created_at.desc())
  997. .limit(1)
  998. )
  999. archive = result.scalar_one_or_none()
  1000. # An archive row on its own proves nothing: `on_print_start` archives every
  1001. # print it observes, including ones started from Bambu Studio or Handy, and
  1002. # stamps them with the same status and subtask_id. Authorizing on its mere
  1003. # existence would disable the kill switch the moment the 3MF finishes
  1004. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1005. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1006. # (carried over from the queue item that started it).
  1007. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1008. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1009. # both the archive filename and every normalized key reported by MQTT.
  1010. _owned_print_archive_ids.add(archive.id)
  1011. _active_prints[(printer_id, archive.filename)] = archive.id
  1012. for key in possible_keys:
  1013. _active_prints[key] = archive.id
  1014. return True
  1015. # No dispatch marker. Before calling this someone else's print, check whether
  1016. # Bambuddy has a job of its own running on this printer: a library-file
  1017. # dispatch has no archive at send time, and an archive created seconds later
  1018. # by `on_print_start` carries neither marker. The queue row, which the
  1019. # scheduler commits to status="printing" before the MQTT send, is the one
  1020. # durable record every Bambuddy print has. It cannot be tied to this
  1021. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1022. # print is irreversible, and refusing to act costs nothing but a log line.
  1023. from backend.app.models.print_queue import PrintQueueItem
  1024. dispatched_here = await db.scalar(
  1025. select(PrintQueueItem.id)
  1026. .where(
  1027. PrintQueueItem.printer_id == printer_id,
  1028. PrintQueueItem.status == "printing",
  1029. )
  1030. .limit(1)
  1031. )
  1032. if dispatched_here is not None:
  1033. return None
  1034. return False
  1035. async def _send_kill_switch_provider_notification(
  1036. printer_id: int,
  1037. printer_name: str,
  1038. data: dict,
  1039. ) -> bool:
  1040. """Send the immediate print-stopped provider notification.
  1041. Returning a success flag lets the normal MQTT completion path retry when
  1042. this early notification could not be delivered.
  1043. """
  1044. logger = logging.getLogger(__name__)
  1045. try:
  1046. async with async_session() as db:
  1047. await notification_service.on_print_complete(
  1048. printer_id,
  1049. printer_name,
  1050. "stopped",
  1051. data,
  1052. db,
  1053. )
  1054. return True
  1055. except Exception as e:
  1056. logger.warning(
  1057. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1058. printer_id,
  1059. e,
  1060. )
  1061. return False
  1062. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1063. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1064. if task is None:
  1065. return False
  1066. try:
  1067. return await task
  1068. except Exception as e:
  1069. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1070. return False
  1071. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1072. """Capture the smart plug lifetime counter on the archive at print start.
  1073. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1074. tracking survives a backend restart mid-print. The print-end handler reads
  1075. this value back from the DB and computes the delta against the current
  1076. plug counter.
  1077. """
  1078. _logger = logging.getLogger(__name__)
  1079. try:
  1080. candidates = await energy_plug_candidates(db, printer_id)
  1081. if not candidates:
  1082. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1083. return False
  1084. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1085. if selected is None:
  1086. # Naming the plugs matters here: with several linked to one printer
  1087. # this is the difference between "the meter is offline" and "you
  1088. # linked only accessories" (#2859).
  1089. _logger.warning(
  1090. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1091. printer_id,
  1092. archive.id,
  1093. ", ".join(plug.name for plug in candidates),
  1094. )
  1095. return False
  1096. plug, energy = selected
  1097. archive.energy_start_kwh = float(energy["total"])
  1098. # With the plug's snapshots, what lets the cost follow the price over
  1099. # the print rather than take the price at its end (#1251). A price that
  1100. # can't be had must not cost the print its energy reading.
  1101. archive.energy_start_at = utcnow_naive()
  1102. archive.energy_start_plug_id = plug.id
  1103. try:
  1104. from backend.app.services.energy_price import current_price
  1105. archive.energy_start_price = await current_price(db)
  1106. except Exception as e:
  1107. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1108. archive.energy_start_price = None
  1109. try:
  1110. from backend.app.services.print_log import mirror_energy_start
  1111. await mirror_energy_start(db, archive, printer_id=printer_id)
  1112. except Exception as e:
  1113. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1114. await db.commit()
  1115. _logger.info(
  1116. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1117. f" ({context})" if context else "",
  1118. archive.id,
  1119. plug.name,
  1120. energy["total"],
  1121. )
  1122. return True
  1123. except Exception as e:
  1124. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1125. return False
  1126. def forget_print_creator(user_id: int) -> None:
  1127. """The print-start emails of a deleted user's jobs go to nobody, not to
  1128. whoever is given the id next (SQLite reuses it)."""
  1129. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1130. del _expected_print_creators[key]
  1131. async def forget_printer(printer_id: int) -> None:
  1132. """Drop what is kept for a deleted printer's id, here and in the services.
  1133. SQLite used to give the id to the next printer created, which inherited it
  1134. all: the running print's owner (its prints passed the kill switch and were
  1135. billed to that user), the plate-clear gate, pending and suppressed
  1136. notifications, the camera feed, the plate references. Ids are no longer
  1137. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1138. stay. Called after the delete is committed, and again by work that was in
  1139. flight and wrote state back.
  1140. Every printer-keyed map of this module is listed here or, with the reason,
  1141. in tests/unit/test_forget_printer.py.
  1142. """
  1143. from backend.app.api.routes import camera
  1144. from backend.app.services import (
  1145. bambu_ftp,
  1146. kprofile_drift,
  1147. layer_timelapse,
  1148. plate_detection,
  1149. print_dispatch_context,
  1150. usage_tracker,
  1151. )
  1152. from backend.app.services.notify_live_activities import notify_live_activities
  1153. from backend.app.services.obico_detection import obico_detection_service
  1154. from backend.app.services.printer_file_cache import printer_file_cache
  1155. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1156. archive_ids = set()
  1157. for tracked in (_active_prints, _expected_prints):
  1158. for key in [key for key in tracked if key[0] == printer_id]:
  1159. archive_ids.add(tracked.pop(key))
  1160. for archive_id in archive_ids:
  1161. _owned_print_archive_ids.discard(archive_id)
  1162. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1163. for key in [key for key in registered if key[0] == printer_id]:
  1164. del registered[key]
  1165. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1166. for key in [key for key in tracked if key[0] == printer_id]:
  1167. del tracked[key]
  1168. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1169. _ams_index_only_logged.discard(key)
  1170. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1171. del _ams_alarm_cooldown[key]
  1172. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1173. # A kill-switch notice is about a stop that happened and is left to finish.
  1174. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1175. task = tasks.pop(printer_id, None)
  1176. if task is not None:
  1177. task.cancel()
  1178. for keyed in (
  1179. _stage22_finish_frames,
  1180. _stage22_finish_in_flight,
  1181. _inprint_frame_bank,
  1182. _inprint_frame_bank_ts,
  1183. _printer_reconciled_since_connect,
  1184. _printer_kprofiles_primed_since_connect,
  1185. _last_progress_milestone,
  1186. _first_layer_notified,
  1187. _kill_switch_notification_tasks,
  1188. _notified_hms_errors,
  1189. _hms_print_state,
  1190. _hms_forget_when_gone,
  1191. _timelapse_baselines,
  1192. _bed_cool_waiters,
  1193. _printer_last_connected,
  1194. _unknown_tag_last_broadcast,
  1195. _last_status_broadcast,
  1196. _connection_watchdog_last_attempt,
  1197. ):
  1198. keyed.pop(printer_id, None)
  1199. for marked in (
  1200. _unauthorized_print_kill_sent,
  1201. _user_stopped_printers,
  1202. _kill_switch_stopped,
  1203. _printer_offline_published,
  1204. _nozzle_count_updated,
  1205. _runtime_seen_connected,
  1206. _timelapse_baselines_unread,
  1207. ):
  1208. marked.discard(printer_id)
  1209. printer_manager.forget_printer(printer_id)
  1210. printer_file_cache.forget_printer(printer_id)
  1211. print_dispatch_context.clear(printer_id)
  1212. kprofile_drift.forget_printer(printer_id, deleted=True)
  1213. layer_timelapse.cancel_session(printer_id)
  1214. usage_tracker.forget_printer(printer_id)
  1215. obico_detection_service.forget_printer(printer_id)
  1216. bambu_ftp.clear_3mf_cache(printer_id)
  1217. await camera.forget_printer(printer_id)
  1218. printers.clear_cover_cache(printer_id)
  1219. print_scheduler.forget_printer(printer_id)
  1220. notify_live_activities.forget_printer(printer_id)
  1221. plate_detection.remove_printer_references(printer_id)
  1222. def register_expected_print(
  1223. printer_id: int,
  1224. filename: str,
  1225. archive_id: int,
  1226. ams_mapping: list[int] | None = None,
  1227. created_by_id: int | None = None,
  1228. cost_center_id: int | None = None,
  1229. plate_id: int | None = None,
  1230. ):
  1231. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1232. # Store with multiple filename variations to catch different naming patterns
  1233. _expected_prints[(printer_id, filename)] = archive_id
  1234. # Also store without .3mf extension if present
  1235. if filename.endswith(".3mf"):
  1236. base = filename[:-4]
  1237. _expected_prints[(printer_id, base)] = archive_id
  1238. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1239. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1240. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1241. # path attributes the whole file's filament total to the spool instead of just
  1242. # the printed plate (#1697). They describe this dispatch: one that has none
  1243. # drops what an earlier dispatch of the archive left (sent, never started),
  1244. # unless a plate of the archive is printing now and still needs them.
  1245. dispatch = (printer_id, archive_id)
  1246. archive_printing = _printing_here(printer_id, archive_id)
  1247. if ams_mapping is not None:
  1248. _print_ams_mappings[dispatch] = ams_mapping
  1249. elif not archive_printing:
  1250. _print_ams_mappings.pop(dispatch, None)
  1251. if cost_center_id is not None:
  1252. _print_cost_center_ids[dispatch] = cost_center_id
  1253. elif not archive_printing:
  1254. _print_cost_center_ids.pop(dispatch, None)
  1255. if plate_id is not None:
  1256. _print_plate_ids[dispatch] = plate_id
  1257. elif not archive_printing:
  1258. _print_plate_ids.pop(dispatch, None)
  1259. # Store created_by_id so the user start email can be sent even when the archive
  1260. # itself has no created_by_id (e.g. library-file-based queue prints)
  1261. if created_by_id is not None:
  1262. _expected_print_creators[(printer_id, filename)] = created_by_id
  1263. if filename.endswith(".3mf"):
  1264. base = filename[:-4]
  1265. _expected_print_creators[(printer_id, base)] = created_by_id
  1266. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1267. # Record registration time for TTL-based eviction
  1268. _registered_at = time.monotonic()
  1269. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1270. if filename.endswith(".3mf"):
  1271. base = filename[:-4]
  1272. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1273. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1274. logging.getLogger(__name__).info(
  1275. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1276. )
  1277. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1278. """Undo :func:`register_expected_print` when the print never went out.
  1279. Registration has to happen *before* the MQTT print command, because the
  1280. printer can report the print before the line after the send executes. So
  1281. every path that registers and then fails to send — a cancel winning the
  1282. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1283. between — leaves an expectation for a print that will never arrive.
  1284. The TTL sweep evicts those after two hours, which is far longer than it
  1285. takes a user to react to a failed dispatch by pressing print again: that
  1286. reprint would be folded into the *old* archive and take the stale
  1287. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1288. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1289. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1290. are keyed by printer and archive, not by file, so they may only be dropped
  1291. once no live key of the printer still points at that archive.
  1292. """
  1293. keys = [(printer_id, filename)]
  1294. if filename.endswith(".3mf"):
  1295. base = filename[:-4]
  1296. keys.append((printer_id, base))
  1297. keys.append((printer_id, f"{base}.gcode"))
  1298. removed = False
  1299. for key in keys:
  1300. if _expected_prints.pop(key, None) is not None:
  1301. removed = True
  1302. _expected_print_creators.pop(key, None)
  1303. _expected_print_registered_at.pop(key, None)
  1304. # Still needed by another expected print of the archive on the printer,
  1305. # or a plate of it printing there, as in the sweep.
  1306. if not _expected_or_printing_here(printer_id, archive_id):
  1307. _drop_dispatch(printer_id, archive_id)
  1308. if removed:
  1309. logging.getLogger(__name__).info(
  1310. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1311. printer_id,
  1312. filename,
  1313. archive_id,
  1314. )
  1315. def _compute_run_filament_grams(
  1316. status: str,
  1317. archive_filament_used_grams: float | None,
  1318. progress: float | int | None,
  1319. usage_results: list[dict] | None,
  1320. ) -> float | None:
  1321. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1322. Priority for every status:
  1323. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1324. weight delta — same source that drives "Total Consumed" on the
  1325. Inventory page, so Stats and Inventory totals stay aligned).
  1326. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1327. back to the canonical "this print used X" value).
  1328. 3. For partial statuses: ``estimate * progress%``.
  1329. 4. ``None`` if nothing is known.
  1330. """
  1331. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1332. if tracked_grams > 0:
  1333. return round(tracked_grams, 1)
  1334. if status == "completed":
  1335. return archive_filament_used_grams
  1336. if archive_filament_used_grams:
  1337. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1338. if scale > 0:
  1339. return round(archive_filament_used_grams * scale, 1)
  1340. return None
  1341. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1342. """Whether a plate of the archive is printing on the printer."""
  1343. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1344. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1345. """Whether a print of the archive is expected or printing on the printer."""
  1346. return _printing_here(printer_id, archive_id) or any(
  1347. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1348. )
  1349. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1350. """Forget what the dispatch of the archive to the printer registered."""
  1351. dispatch = (printer_id, archive_id)
  1352. _print_ams_mappings.pop(dispatch, None)
  1353. _print_cost_center_ids.pop(dispatch, None)
  1354. _print_plate_ids.pop(dispatch, None)
  1355. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1356. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1357. stored_ams_mapping = data.get("ams_mapping")
  1358. if not stored_ams_mapping and archive_id:
  1359. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1360. return stored_ams_mapping
  1361. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1362. """Resolve plate_id for print start without consuming stored direct-Print state.
  1363. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1364. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1365. read it back at print-start without popping (the entry is popped on print
  1366. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1367. """
  1368. if archive_id is None:
  1369. return None
  1370. return _print_plate_ids.get((printer_id, archive_id))
  1371. def _partial_progress_scale(progress: int | float | None) -> float:
  1372. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1373. Used by every site that multiplies a "would-have-used" slicer estimate
  1374. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1375. so the three sites in ``_background_notifications`` (and the per-plate
  1376. override helper) can't drift apart on the coercion shape.
  1377. """
  1378. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1379. def _scope_notification_archive_data_to_plate(
  1380. archive_data: dict,
  1381. archive_file_path: str | None,
  1382. plate_id: int | None,
  1383. print_status: str,
  1384. progress: int | float | None,
  1385. base_dir: Path,
  1386. ) -> dict:
  1387. """Override summed-across-plates totals in ``archive_data`` with the values
  1388. for ``plate_id`` so the completion notification reports what was actually
  1389. printed, not the whole project (#1785).
  1390. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1391. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1392. the archive card's "whole project" headline, wrong for the completion
  1393. notification of a single-plate print. The queue UI already re-reads the
  1394. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1395. notification payload (filament grams, time estimate, per-slot breakdown).
  1396. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1397. no per-plate values — in every fail case the original ``archive_data`` is
  1398. returned unchanged so the notification still sends.
  1399. """
  1400. if plate_id is None or not archive_file_path:
  1401. return archive_data
  1402. from backend.app.utils.threemf_tools import (
  1403. extract_filament_usage_from_3mf,
  1404. extract_print_time_from_3mf,
  1405. )
  1406. archive_path = base_dir / archive_file_path
  1407. if not archive_path.exists():
  1408. return archive_data
  1409. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1410. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1411. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1412. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1413. if plate_time:
  1414. archive_data["print_time_seconds"] = plate_time
  1415. # Gate both the grams headline AND the per-slot breakdown on the same
  1416. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1417. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1418. # to the project-level grams the archive columns already provide rather
  1419. # than ship a project-level headline next to an all-zero per-plate
  1420. # breakdown.
  1421. if plate_grams > 0:
  1422. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1423. archive_data["filament_slots"] = [
  1424. {
  1425. "slot_id": s.get("slot_id"),
  1426. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1427. "type": s.get("type", ""),
  1428. "color": s.get("color", ""),
  1429. }
  1430. for s in plate_slots
  1431. ]
  1432. return archive_data
  1433. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1434. """Best-effort filament metadata from the MQTT print-start snapshot.
  1435. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1436. file during print, see #1533) so the fallback PrintArchive still has
  1437. enough filament info to support the inventory views and AMS-expansion
  1438. planning the operator opens it for. Returns a dict with optional
  1439. ``filament_type`` and ``filament_color`` keys in the same
  1440. comma-separated format the 3MF extractor produces, so the rest of the
  1441. codebase treats the fallback archive identically to a normal one.
  1442. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1443. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1444. entries). When supplied, only the slots actually consumed by this
  1445. print contribute. Without it the function falls back to every loaded
  1446. AMS slot — less accurate but still useful.
  1447. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1448. that the unit tests pass directly, AND the on_print_start callback
  1449. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1450. bambu_mqtt service hands to main.py at runtime. The original
  1451. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1452. handled the inner shape and silently returned ``{}`` for every real
  1453. print start, leaving fallback archives' filament fields NULL — the
  1454. exact regression the fix was meant to close. Reported with a log
  1455. proving the AMS state was right there at
  1456. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1457. """
  1458. result: dict[str, str] = {}
  1459. # Look at the on_print_start wrapper first, then the inner shape.
  1460. raw_data = (data or {}).get("raw_data")
  1461. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1462. if not isinstance(ams_root, dict):
  1463. ams_root = (data or {}).get("ams") or {}
  1464. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1465. if not isinstance(ams_units, list) or not ams_units:
  1466. return result
  1467. from backend.app.services.print_scheduler import _global_tray_id
  1468. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1469. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1470. loaded: dict[int, tuple[str, str]] = {}
  1471. for unit in ams_units:
  1472. if not isinstance(unit, dict):
  1473. continue
  1474. try:
  1475. unit_id = int(unit.get("id", 0))
  1476. except (TypeError, ValueError):
  1477. continue
  1478. for tray in unit.get("tray") or []:
  1479. if not isinstance(tray, dict):
  1480. continue
  1481. try:
  1482. tray_id = int(tray.get("id", 0))
  1483. except (TypeError, ValueError):
  1484. continue
  1485. ttype = (tray.get("tray_type") or "").strip()
  1486. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1487. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1488. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1489. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1490. if not ttype:
  1491. continue # Empty / unloaded slot.
  1492. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1493. if not loaded:
  1494. return result
  1495. if ams_mapping:
  1496. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1497. filaments = [loaded[g] for g in used_ids if g in loaded]
  1498. if not filaments:
  1499. return result # Mapping points entirely at slots we have no data for.
  1500. else:
  1501. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1502. types_joined = ",".join(f[0] for f in filaments)
  1503. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1504. # Column limits per backend/app/models/archive.py: filament_type=50,
  1505. # filament_color=200.
  1506. if types_joined:
  1507. result["filament_type"] = types_joined[:50]
  1508. if colors_joined:
  1509. result["filament_color"] = colors_joined[:200]
  1510. return result
  1511. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1512. """Start a layer-timelapse session for *archive_id* when the printer has
  1513. an external camera configured. Returns True if a session was started.
  1514. Three call sites in on_print_start (expected-archive promotion, fallback
  1515. archive creation, fresh-archive creation) used to inline this same
  1516. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1517. on the first pass). Centralising the conditional + call here makes the
  1518. contract testable in isolation and keeps the three sites locked in step.
  1519. """
  1520. if not (printer.external_camera_enabled and printer.external_camera_url):
  1521. return False
  1522. from backend.app.services.layer_timelapse import start_session
  1523. start_session(
  1524. printer_id,
  1525. archive_id,
  1526. printer.external_camera_url,
  1527. printer.external_camera_type or "mjpeg",
  1528. snapshot_url=printer.external_camera_snapshot_url,
  1529. rotation=getattr(printer, "camera_rotation", 0),
  1530. )
  1531. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1532. return True
  1533. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1534. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1535. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1536. — since #2926 — the description the parser already resolved, which is preferred
  1537. when present so the queue's failure reason reads the same as the status
  1538. response. The short code still produces the bracketed label, and still
  1539. resolves the sentence for a caller whose entries predate the field. An entry
  1540. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1541. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1542. label when no description is on file. Returns None for an empty list so
  1543. callers can leave error_message unset.
  1544. """
  1545. if not hms_errors:
  1546. return None
  1547. from backend.app.services.hms_errors import get_error_description
  1548. parts: list[str] = []
  1549. for err in hms_errors:
  1550. try:
  1551. # `_hms_short_code` rather than a local derivation: this one used to
  1552. # format the error without masking it to 16 bits, so an `hms[]` entry
  1553. # whose code carries an alert-level group produced a five-digit label
  1554. # like "0500_3000A" — not a code the user can look up, and never a
  1555. # catalogue key, so the sentence was lost with it.
  1556. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1557. except (TypeError, ValueError):
  1558. continue
  1559. description = err.get("description") or get_error_description(short_code)
  1560. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1561. # groups and is not a code anyone can look up; its full code in the
  1562. # printer screen's four groups is (#2728).
  1563. full_code = str(err.get("full_code") or "")
  1564. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1565. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1566. return "; ".join(parts) if parts else None
  1567. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1568. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1569. print completes successfully. Gated to status=='completed': failed, cancelled
  1570. and aborted prints do not count as usage. Caller is responsible for committing
  1571. the session. No-op when the queue item has no linked library file (e.g. reprints
  1572. from an archive). See #1008."""
  1573. if queue_status != "completed" or item.library_file_id is None:
  1574. return
  1575. from backend.app.models.library import LibraryFile
  1576. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1577. if lib_file is None:
  1578. return
  1579. lib_file.print_count = (lib_file.print_count or 0) + 1
  1580. lib_file.last_printed_at = datetime.now(timezone.utc)
  1581. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1582. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1583. When on_print_complete fires with status 'failed' for a printer in this set we
  1584. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1585. rather than a 'print failed' notification.
  1586. """
  1587. _user_stopped_printers.add(printer_id)
  1588. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1589. _last_status_broadcast: dict[int, str] = {}
  1590. # Track printers where we've updated nozzle_count
  1591. _nozzle_count_updated: set[int] = set()
  1592. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1593. """Wait the debounce window then fire `on_printer_offline` if the printer
  1594. is still offline.
  1595. Scheduled by `on_printer_status_change` on the connected → disconnected
  1596. edge (#1752). Cancelled by the same handler if the printer reconnects
  1597. before the window elapses, so a single MQTT blip + recovery doesn't
  1598. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1599. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1600. route through the same status-change callback, so this covers both.
  1601. """
  1602. logger = logging.getLogger(__name__)
  1603. try:
  1604. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1605. still_offline = not printer_manager.is_connected(printer_id)
  1606. logger.info(
  1607. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1608. printer_id,
  1609. still_offline,
  1610. )
  1611. if not still_offline:
  1612. return
  1613. async with async_session() as db:
  1614. from backend.app.models.printer import Printer
  1615. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1616. printer = result.scalar_one_or_none()
  1617. if not printer:
  1618. logger.warning(
  1619. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1620. printer_id,
  1621. )
  1622. return
  1623. # Recorded only when the relay can publish it, so the reconnect's
  1624. # online event always has an offline before it.
  1625. if mqtt_relay.enabled and mqtt_relay.connected:
  1626. _printer_offline_published.add(printer_id)
  1627. try:
  1628. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1629. except Exception as e:
  1630. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1631. logger.info(
  1632. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1633. printer_id,
  1634. printer.name,
  1635. )
  1636. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1637. except asyncio.CancelledError:
  1638. raise
  1639. except Exception as e:
  1640. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1641. finally:
  1642. _printer_offline_notify_tasks.pop(printer_id, None)
  1643. def _hms_notify_key(error) -> str:
  1644. """What identifies a fault for notification de-duplication.
  1645. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1646. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1647. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1648. and -0006 together) shared a key and only the first was ever notified. An
  1649. entry without a full code falls back to attr and code together.
  1650. """
  1651. full_code = getattr(error, "full_code", "") or ""
  1652. if full_code:
  1653. return full_code.upper()
  1654. return f"{error.attr:08X}:{error.code}"
  1655. def _hms_fault_counts(error) -> bool:
  1656. """Whether a fault counts as a problem: the same rule the frontend's
  1657. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1658. It counts when Bambu publishes text for it or it offers action buttons, and
  1659. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1660. no actions does not count: those are things like "the top cover is open" or
  1661. "the chamber is hot, fan speed increased", which a printer can hold through
  1662. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1663. it always has; those are prompts such as "unable to start drying" (#2728).
  1664. """
  1665. if error.severity < 1:
  1666. return False
  1667. has_actions = bool(getattr(error, "actions", None))
  1668. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1669. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1670. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1671. """The new faults that count (see ``_hms_fault_counts``).
  1672. These go to the MQTT relay; the caller also needs a description before it
  1673. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1674. used to read ``severity >= 2`` when severity held the part byte; on the real
  1675. level that would drop the task-stopping errors (#2728).
  1676. """
  1677. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1678. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1679. """The faults on this printer not notified yet, and record them as notified.
  1680. Tracking is updated before anything is sent, so concurrent status callbacks
  1681. cannot notify the same fault twice. A notified fault is forgotten once it
  1682. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1683. and on is notified once (#3226), while one that clears and comes back much
  1684. later is notified again.
  1685. When ``print_state`` changes (a print resumed, started or finished), every
  1686. fault recorded so far is forgotten the first time it is gone, without the
  1687. wait: a runout fixed before resuming must be notified if it happens again a
  1688. few minutes later, while the printer sits paused. Not only the faults gone
  1689. at the change itself, because the update that flips the state can still
  1690. carry the old fault (a ``print_error`` entry stays until a payload brings
  1691. ``hms``).
  1692. """
  1693. now = time.time()
  1694. current = {_hms_notify_key(e) for e in errors}
  1695. seen = _notified_hms_errors.setdefault(printer_id, {})
  1696. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1697. if print_state is not None:
  1698. print_state = print_state.upper()
  1699. if _hms_print_state.get(printer_id, print_state) != print_state:
  1700. forget_when_gone.update(seen)
  1701. _hms_print_state[printer_id] = print_state
  1702. for key, last_seen in list(seen.items()):
  1703. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1704. del seen[key]
  1705. forget_when_gone.discard(key)
  1706. new = current - seen.keys()
  1707. for key in current:
  1708. seen[key] = now
  1709. if not seen:
  1710. _notified_hms_errors.pop(printer_id, None)
  1711. if not forget_when_gone:
  1712. _hms_forget_when_gone.pop(printer_id, None)
  1713. return _hms_errors_to_notify(errors, new)
  1714. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1715. # "Printing", -1 and 255 are "no stage" (#3211).
  1716. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1717. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1718. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1719. Records it as notified. Called only for a printing state with progress above 0.
  1720. Progress before the first layer is not progress through the print (#3211).
  1721. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1722. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1723. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1724. 75% notification together with Print Started, and since 75 was then on
  1725. record, 25 and 50 could never fire. So nothing counts while the printer
  1726. reports a layer count but has not started layer 1.
  1727. Without a layer count -- a print whose first frame carried no
  1728. ``total_layer_num``, until the pushall that asks for it is answered
  1729. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1730. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1731. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1732. reports neither keeps the old behaviour rather than never notifying.
  1733. """
  1734. if (state.layer_num or 0) < 1:
  1735. if (state.total_layers or 0) > 0:
  1736. return None
  1737. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1738. return None
  1739. progress = state.progress or 0
  1740. current_milestone = 0
  1741. if progress >= 75:
  1742. current_milestone = 75
  1743. elif progress >= 50:
  1744. current_milestone = 50
  1745. elif progress >= 25:
  1746. current_milestone = 25
  1747. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1748. _last_progress_milestone[printer_id] = current_milestone
  1749. return current_milestone
  1750. return None
  1751. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1752. """Handle printer status changes - broadcast via WebSocket."""
  1753. try:
  1754. notify_live_activities.observe(printer_id, state)
  1755. except Exception:
  1756. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1757. try:
  1758. pause_eta.observe(printer_id, state)
  1759. except Exception:
  1760. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1761. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1762. # transitions disconnected → connected — which covers both Bambuddy
  1763. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1764. # `reconcile_stale_active_prints` exactly once for this connection so
  1765. # any archive still in `status="printing"` that can't actually be
  1766. # running anymore (printer IDLE / different subtask / empty subtask)
  1767. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1768. # finished during a disconnect window + a smart-plug power cycle
  1769. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1770. # next boot. Reconciliation runs concurrently — it must not block the
  1771. # WebSocket dedup / broadcast logic below, and the connected edge is
  1772. # marked True BEFORE the await so concurrent status updates inside
  1773. # the same connection don't re-trigger reconciliation.
  1774. #
  1775. # Wait for a real push_status before reconciling (#1679): MQTT
  1776. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1777. # the connection, BEFORE `_request_push_all` round-trips. At that
  1778. # instant the `PrinterState` is still on construction defaults — most
  1779. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1780. # If reconcile spawns here, every in-flight archive falls through to
  1781. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1782. # creates a duplicate archive on the real PRINT COMPLETE and
  1783. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1784. # keeps the #1542 mechanism intact: once the first real push_status
  1785. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1786. # fires again with the flag still False — reconcile then runs against
  1787. # actual evidence.
  1788. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1789. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1790. _printer_reconciled_since_connect[printer_id] = True
  1791. spawn_background_task(
  1792. reconcile_stale_active_prints(printer_id),
  1793. name=f"reconcile-stale-prints-{printer_id}",
  1794. )
  1795. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1796. # Re-arm so the next reconnect triggers reconciliation again.
  1797. _printer_reconciled_since_connect[printer_id] = False
  1798. # Same edge, for the calibration table the AMS card reads its K values from.
  1799. #
  1800. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1801. # tables to ask for. A `state_known` gate alone is not enough: the first
  1802. # real push_status is what makes the state known, and the nozzle fields do
  1803. # not always arrive in it. Latching there would spend this connection's one
  1804. # attempt on a printer that could not yet say what was fitted.
  1805. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1806. if (
  1807. state.connected
  1808. and state_known
  1809. and nozzle_known
  1810. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1811. ):
  1812. _printer_kprofiles_primed_since_connect[printer_id] = True
  1813. spawn_background_task(
  1814. prime_kprofile_table(printer_id),
  1815. name=f"prime-kprofiles-{printer_id}",
  1816. )
  1817. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1818. _printer_kprofiles_primed_since_connect[printer_id] = False
  1819. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1820. # else in the AMS report changing -- a power cycle does it to every slot --
  1821. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1822. # while the printer is idle; needs_check is cheap and throttled per slot.
  1823. # Guarded: nothing here may stop the status broadcast below.
  1824. try:
  1825. if not state.connected:
  1826. kprofile_drift.forget_printer(printer_id)
  1827. elif kprofile_drift.needs_check(printer_id, state):
  1828. spawn_background_task(
  1829. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1830. name=f"reapply-kprofiles-{printer_id}",
  1831. )
  1832. except Exception:
  1833. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1834. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1835. # connected → disconnected. The "back online" channel is already covered
  1836. # by the print-failure notification (firmware reports gcode_state=FAILED
  1837. # on reconnect of an interrupted print), so there is no online
  1838. # notification. The MQTT relay gets both: offline after the debounce, and
  1839. # online on the reconnect that follows a published offline.
  1840. prev_connected = _printer_last_connected.get(printer_id)
  1841. _printer_last_connected[printer_id] = state.connected
  1842. if prev_connected is True and not state.connected:
  1843. existing = _printer_offline_notify_tasks.get(printer_id)
  1844. if existing is None or existing.done():
  1845. logging.getLogger(__name__).info(
  1846. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1847. printer_id,
  1848. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1849. )
  1850. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1851. _maybe_notify_printer_offline(printer_id),
  1852. name=f"printer-offline-notify-{printer_id}",
  1853. )
  1854. elif state.connected:
  1855. # Kept until the relay can actually send online: with its broker down
  1856. # now, the next status update after the reconnect sends it.
  1857. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1858. _printer_offline_published.discard(printer_id)
  1859. printer_info = printer_manager.get_printer(printer_id)
  1860. if printer_info:
  1861. try:
  1862. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1863. except Exception as e:
  1864. logging.getLogger(__name__).warning(
  1865. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1866. )
  1867. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1868. if pending is not None and not pending.done():
  1869. logging.getLogger(__name__).info(
  1870. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1871. printer_id,
  1872. )
  1873. pending.cancel()
  1874. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1875. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1876. temps = state.temperatures or {}
  1877. nozzle_temp = round(temps.get("nozzle", 0))
  1878. bed_temp = round(temps.get("bed", 0))
  1879. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1880. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1881. # Auto-detect dual-nozzle printers from MQTT temperature data
  1882. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1883. _nozzle_count_updated.add(printer_id)
  1884. # Update nozzle_count in database
  1885. async with async_session() as db:
  1886. from backend.app.models.printer import Printer
  1887. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1888. printer = result.scalar_one_or_none()
  1889. if printer and printer.nozzle_count != 2:
  1890. printer.nozzle_count = 2
  1891. await db.commit()
  1892. logging.getLogger(__name__).info(
  1893. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1894. )
  1895. # Include target temps for heating phase detection
  1896. bed_target = round(temps.get("bed_target", 0))
  1897. nozzle_target = round(temps.get("nozzle_target", 0))
  1898. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1899. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1900. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1901. #
  1902. # dry_countdown_stalled rides along because it is the one drying signal the
  1903. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1904. # dry_time stopped moving, so on the frame that flips it every other member
  1905. # of this key is identical and the push would be deduplicated away. Mid-print
  1906. # a temperature would eventually break the tie, but a parked command on an
  1907. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1908. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1909. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1910. ams_dry_key = (
  1911. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1912. if state.raw_data
  1913. else ()
  1914. )
  1915. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1916. #
  1917. # The filament identity fields are here because Configure Slot writes
  1918. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1919. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1920. # matched, this function returned before broadcasting, and the card kept
  1921. # showing the old filament until the 30s fallback poll or a page reload —
  1922. # even though the configure route asks the printer for a fresh pushall and
  1923. # that push does carry the new values. Reset always worked, because it
  1924. # clears tray_type.
  1925. #
  1926. # These fields only change when someone configures a slot or swaps a spool,
  1927. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1928. ams_tray_key = (
  1929. tuple(
  1930. (
  1931. t.get("id"),
  1932. t.get("tray_type", ""),
  1933. t.get("state"),
  1934. t.get("tray_color", ""),
  1935. t.get("tray_info_idx", ""),
  1936. t.get("tray_sub_brands", ""),
  1937. t.get("cali_idx"),
  1938. )
  1939. for a in (state.raw_data.get("ams") or [])
  1940. for t in a.get("tray", [])
  1941. )
  1942. if state.raw_data
  1943. else ()
  1944. )
  1945. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1946. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1947. # in the AMS change-hash (tray fields only, and widening that would fire
  1948. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1949. # screen changed no key at all and the card's inlet badges sat stale until a
  1950. # reload. Like the filament-backup flag, these only move when someone
  1951. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1952. fts_key = (
  1953. state.fila_switch.installed if state.fila_switch else False,
  1954. tuple(sorted(state.ams_switch_inlet.items())),
  1955. # Which hotend holds which slot. Unlike the two above this does move
  1956. # mid-print, on every filament change — but only between discrete slots,
  1957. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1958. # it live: it decides which hotend the Load dialog may offer and whether
  1959. # Unload has anything to act on.
  1960. tuple(
  1961. sorted(
  1962. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1963. # Sort on the extruder id alone: the other members are nullable
  1964. # and comparing None with an int raises.
  1965. key=lambda entry: entry[0],
  1966. )
  1967. ),
  1968. )
  1969. status_key = (
  1970. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1971. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1972. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1973. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1974. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1975. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1976. )
  1977. # Fields that change only when the machine does (a nozzle swap, a firmware
  1978. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1979. # but on an idle printer nothing else moves the key when they change.
  1980. machine_key = (
  1981. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1982. state.firmware_version,
  1983. state.developer_mode,
  1984. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1985. # Cooling/heating, switched on the printer's screen too: on an idle
  1986. # printer nothing else moves the key (PSF-4).
  1987. state.airduct_mode,
  1988. )
  1989. status_key = f"{status_key}:{machine_key}"
  1990. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1991. if not is_active_print:
  1992. _unauthorized_print_kill_sent.discard(printer_id)
  1993. elif printer_id in _unauthorized_print_kill_sent:
  1994. # stop_print() was already sent for this print; avoid all further
  1995. # ownership and settings work until the printer leaves an active state.
  1996. pass
  1997. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1998. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1999. _unauthorized_print_kill_sent.discard(printer_id)
  2000. else:
  2001. kill_switch_enabled = False
  2002. authorization: bool | None = None
  2003. status_logger = logging.getLogger(__name__)
  2004. try:
  2005. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2006. if kill_switch_enabled:
  2007. async with async_session() as db:
  2008. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2009. except Exception as e:
  2010. # Fail safe: a database/reconciliation error must never turn into an
  2011. # irreversible stop of a print whose ownership is still unknown.
  2012. authorization = None
  2013. status_logger.warning(
  2014. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2015. )
  2016. if not kill_switch_enabled or authorization is True:
  2017. _unauthorized_print_kill_sent.discard(printer_id)
  2018. elif authorization is None:
  2019. _unauthorized_print_kill_sent.discard(printer_id)
  2020. status_logger.debug(
  2021. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2022. printer_id,
  2023. )
  2024. else:
  2025. try:
  2026. stopped = printer_manager.stop_print(printer_id)
  2027. if stopped:
  2028. _unauthorized_print_kill_sent.add(printer_id)
  2029. _kill_switch_stopped.add(printer_id)
  2030. printer_info = printer_manager.get_printer(printer_id)
  2031. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2032. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2033. notification_data = {
  2034. "status": "stopped",
  2035. "filename": state.gcode_file or state.current_print or "",
  2036. "subtask_name": state.subtask_name or "",
  2037. "progress": state.progress,
  2038. "reason": "unauthorized_print",
  2039. }
  2040. status_logger.warning(
  2041. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2042. printer_id,
  2043. state.state,
  2044. )
  2045. try:
  2046. await ws_manager.broadcast(
  2047. {
  2048. "type": "kill_switch_triggered",
  2049. "printer_id": printer_id,
  2050. "printer_name": printer_name,
  2051. "filename": filename,
  2052. "reason": "unauthorized_print",
  2053. }
  2054. )
  2055. except Exception as e:
  2056. status_logger.warning(
  2057. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2058. )
  2059. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2060. if previous_task is not None and not previous_task.done():
  2061. previous_task.cancel()
  2062. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2063. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2064. name=f"kill-switch-notification-{printer_id}",
  2065. )
  2066. else:
  2067. status_logger.warning(
  2068. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2069. printer_id,
  2070. state.state,
  2071. )
  2072. except Exception as e:
  2073. status_logger.warning(
  2074. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2075. )
  2076. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2077. try:
  2078. printer_info = printer_manager.get_printer(printer_id)
  2079. if printer_info:
  2080. await mqtt_relay.on_printer_status(
  2081. printer_id,
  2082. state,
  2083. printer_info.name,
  2084. printer_info.serial_number,
  2085. printer_manager.is_awaiting_plate_clear(printer_id),
  2086. )
  2087. except Exception:
  2088. pass # Don't fail status callback if MQTT fails
  2089. if _last_status_broadcast.get(printer_id) == status_key:
  2090. return # No change, skip WebSocket broadcast
  2091. _last_status_broadcast[printer_id] = status_key
  2092. # Check for progress milestone notifications (25%, 50%, 75%)
  2093. progress = state.progress or 0
  2094. is_printing = state.state in ("RUNNING", "PRINTING")
  2095. if is_printing and progress > 0:
  2096. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2097. if current_milestone is not None:
  2098. try:
  2099. from backend.app.models.printer import Printer
  2100. # Read the printer in a short session and release the connection
  2101. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2102. # pinned a pooled connection per milestone, per printer (issue #2572).
  2103. async with async_session() as db:
  2104. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2105. printer = result.scalar_one_or_none()
  2106. printer_name = printer.name if printer else f"Printer {printer_id}"
  2107. filename = state.subtask_name or state.gcode_file or "Unknown"
  2108. # remaining_time is in minutes, convert to seconds for notification
  2109. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2110. # Capture camera snapshot for notification image attachment (no DB held).
  2111. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2112. # Notification send needs a session (provider/template lookups).
  2113. async with async_session() as db:
  2114. await notification_service.on_print_progress(
  2115. printer_id,
  2116. printer_name,
  2117. filename,
  2118. current_milestone,
  2119. db,
  2120. remaining_time_seconds,
  2121. image_data=image_data,
  2122. )
  2123. except Exception as e:
  2124. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2125. elif progress < 5:
  2126. # Reset milestone tracking when print restarts or new print begins
  2127. _last_progress_milestone[printer_id] = 0
  2128. _first_layer_notified[printer_id] = False
  2129. # HMS error codes that should not trigger notifications even though they
  2130. # have known descriptions (e.g. user-initiated actions, not real errors).
  2131. _HMS_NOTIFICATION_SUPPRESS = {
  2132. "0500_400E", # Printing was cancelled (user action, not an error)
  2133. }
  2134. # Check for new HMS errors and send notifications
  2135. current_hms_errors = getattr(state, "hms_errors", []) or []
  2136. if current_hms_errors:
  2137. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2138. if new_errors:
  2139. try:
  2140. from backend.app.models.printer import Printer
  2141. # Read the printer in a short session and release the connection
  2142. # BEFORE the ~15s camera snapshot below (issue #2572).
  2143. async with async_session() as db:
  2144. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2145. printer = result.scalar_one_or_none()
  2146. printer_name = printer.name if printer else f"Printer {printer_id}"
  2147. # Format error details for notification
  2148. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2149. module_names = {
  2150. 0x03: "Print/Task",
  2151. 0x05: "Nozzle/Extruder",
  2152. 0x07: "AMS/Filament",
  2153. 0x0C: "Motion Controller",
  2154. 0x12: "Chamber",
  2155. }
  2156. # Capture camera snapshot once for all error notifications (no DB held).
  2157. error_image_data = await _capture_snapshot_for_notification(
  2158. printer_id, printer, logging.getLogger(__name__)
  2159. )
  2160. # Notification sends need a session (provider/template lookups).
  2161. async with async_session() as db:
  2162. sent_count = 0
  2163. for error in new_errors:
  2164. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2165. # Build short code like "0700_8010"
  2166. # Mask to 16 bits to handle printers that send larger values
  2167. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2168. error_code_masked = error_code_int & 0xFFFF
  2169. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2170. # Only notify for errors Bambu publishes text for — printers
  2171. # send undocumented codes that aren't real errors, and Bambu
  2172. # lists some with empty text. Resolved at parse time (#2926);
  2173. # short_code is still needed for the suppression set below.
  2174. description = error.description
  2175. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2176. continue
  2177. error_type = f"{module_name} Error"
  2178. error_detail = description
  2179. await notification_service.on_printer_error(
  2180. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2181. )
  2182. sent_count += 1
  2183. if sent_count:
  2184. logging.getLogger(__name__).info(
  2185. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2186. )
  2187. # Also publish to MQTT relay (no DB): every new fault that
  2188. # counts, with or without text, the same set the UI counts.
  2189. printer_info = printer_manager.get_printer(printer_id)
  2190. if printer_info:
  2191. errors_data = [
  2192. {
  2193. "code": e.code,
  2194. "attr": e.attr,
  2195. "module": e.module,
  2196. "severity": e.severity,
  2197. }
  2198. for e in new_errors
  2199. ]
  2200. await mqtt_relay.on_printer_error(
  2201. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2202. )
  2203. except Exception as e:
  2204. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2205. else:
  2206. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2207. # across a print state change) are forgotten. Some codes, e.g. chamber
  2208. # temperature regulation during PETG prints, toggle every few seconds.
  2209. _take_new_hms_faults(printer_id, [], state.state)
  2210. await ws_manager.send_printer_status(
  2211. printer_id,
  2212. printer_state_to_dict(
  2213. state,
  2214. printer_id,
  2215. printer_manager.get_model(printer_id),
  2216. printer_manager.get_drying_targets(printer_id),
  2217. ),
  2218. )
  2219. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2220. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2221. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2222. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2223. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2224. K-profiles are per-nozzle and the printer's calibration table is numbered
  2225. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2226. switch's other inlet therefore silently invalidates every configured slot in
  2227. it: the index stays put and now resolves against the other nozzle's table.
  2228. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2229. and 0.020 on the right kept the left profile after the move, and a manual
  2230. RFID re-read only re-asserted the same wrong one.
  2231. Configuring a slot is a deliberate preparation step, so this re-selects
  2232. rather than re-configures: only the calibration binding moves, and only for
  2233. slots whose spool already has a stored profile for the new nozzle. A slot
  2234. Bambuddy knows nothing about is left exactly as the operator left it.
  2235. """
  2236. logger = logging.getLogger(__name__)
  2237. target_extruder = extruder_for_inlet(inlet)
  2238. if target_extruder is None:
  2239. return
  2240. client = printer_manager.get_client(printer_id)
  2241. state = printer_manager.get_status(printer_id)
  2242. if not client or not state or not state.raw_data:
  2243. return
  2244. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2245. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2246. # the nozzle width, which changes both the K profile to select and the
  2247. # preset the slot should carry.
  2248. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2249. ams_raw = state.raw_data.get("ams")
  2250. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2251. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2252. if not unit:
  2253. return
  2254. try:
  2255. async with async_session() as db:
  2256. for tray in unit.get("tray", []):
  2257. tray_id = int(tray.get("id", -1))
  2258. if tray_id < 0 or not tray.get("tray_type"):
  2259. continue
  2260. current_idx = tray.get("cali_idx")
  2261. profile = await find_slot_kprofile_for_extruder(
  2262. db,
  2263. printer_id,
  2264. ams_id,
  2265. tray_id,
  2266. target_extruder,
  2267. nozzle_diameter,
  2268. printer_manager.get_model(printer_id),
  2269. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2270. )
  2271. if profile is None or profile.cali_idx is None:
  2272. continue
  2273. if current_idx == profile.cali_idx:
  2274. continue # Already on the right one.
  2275. logger.info(
  2276. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2277. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2278. printer_id,
  2279. ams_id,
  2280. tray_id,
  2281. inlet,
  2282. target_extruder,
  2283. profile.name,
  2284. current_idx,
  2285. profile.cali_idx,
  2286. profile.k_value,
  2287. )
  2288. client.extrusion_cali_sel(
  2289. ams_id=ams_id,
  2290. tray_id=tray_id,
  2291. cali_idx=profile.cali_idx,
  2292. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2293. nozzle_diameter=nozzle_diameter,
  2294. )
  2295. except Exception as e:
  2296. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2297. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2298. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2299. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2300. from the delayed re-check -- which is why it takes the AMS data and print
  2301. state as arguments instead of reading them from the push (#3186).
  2302. """
  2303. logger = logging.getLogger(__name__)
  2304. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2305. # Auto-unlink spool assignments with stale fingerprints. Under the
  2306. # per-printer assignment lock since #3186: the held-removal re-check runs
  2307. # this outside any MQTT push, so it can now overlap one.
  2308. try:
  2309. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2310. from sqlalchemy.orm import selectinload
  2311. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2312. from backend.app.models.spool import Spool as _Spool
  2313. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2314. from backend.app.services.ams_slot_presence import spool_present
  2315. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2316. # Built-in assignments only. Since #2812 they survive a switch to
  2317. # Spoolman mode rather than being deleted by it, and this pass ends
  2318. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2319. # time as the AMS contents changed under the other mode, undoing the
  2320. # preservation more slowly but just as completely.
  2321. assignments = []
  2322. if not await spoolman_owns_assignments(db):
  2323. result = await db.execute(
  2324. select(SA)
  2325. .where(SA.printer_id == printer_id)
  2326. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2327. )
  2328. assignments = result.scalars().all()
  2329. # ``printing_now`` (top of this function) keeps a runout from
  2330. # unlinking the spool that fed the print — the next idle-time pass
  2331. # unlinks it if the user really did take it out.
  2332. stale = []
  2333. # Removals this pass is holding rather than unlinking (#3186).
  2334. held: set[tuple] = set()
  2335. for assignment in assignments:
  2336. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2337. if assignment.ams_id == 255:
  2338. ps = printer_manager.get_status(printer_id)
  2339. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2340. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2341. current_tray = None
  2342. for vt in vt_tray_raw:
  2343. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2344. current_tray = vt
  2345. break
  2346. if not current_tray:
  2347. # vt_tray data may not have arrived yet — keep assignment
  2348. continue
  2349. else:
  2350. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2351. if not current_tray:
  2352. if printing_now:
  2353. logger.info(
  2354. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2355. assignment.spool_id,
  2356. assignment.ams_id,
  2357. assignment.tray_id,
  2358. )
  2359. continue
  2360. # A whole AMS unit can drop out of one push and come back in
  2361. # the next; only a slot that stays gone is a removal (#3186).
  2362. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2363. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2364. held.add(hold_key)
  2365. logger.info(
  2366. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2367. "unlinking if it is still gone in %ds",
  2368. assignment.spool_id,
  2369. assignment.ams_id,
  2370. assignment.tray_id,
  2371. int(slot_unlink_grace.GRACE_SECONDS),
  2372. )
  2373. continue
  2374. logger.info(
  2375. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2376. assignment.spool_id,
  2377. assignment.ams_id,
  2378. assignment.tray_id,
  2379. )
  2380. stale.append(assignment) # Slot empty
  2381. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2382. # A Bambu Lab spool is in this slot — check if it's the same spool
  2383. # that's currently assigned. If yes, keep the assignment (avoids
  2384. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2385. # the printer's filament preset on every startup).
  2386. tray_uuid = current_tray.get("tray_uuid", "")
  2387. tag_uid = current_tray.get("tag_uid", "")
  2388. spool = assignment.spool
  2389. spool_matches = False
  2390. if spool:
  2391. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2392. spool.tag_uid
  2393. and tag_uid
  2394. and tag_uid != "0000000000000000"
  2395. and spool.tag_uid.upper() == tag_uid.upper()
  2396. ):
  2397. spool_matches = True
  2398. if spool_matches:
  2399. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2400. cur_color = current_tray.get("tray_color", "")
  2401. cur_type = current_tray.get("tray_type", "")
  2402. fp_color = assignment.fingerprint_color or ""
  2403. fp_type = assignment.fingerprint_type or ""
  2404. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2405. assignment.fingerprint_color = cur_color
  2406. assignment.fingerprint_type = cur_type
  2407. logger.debug(
  2408. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2409. assignment.spool_id,
  2410. assignment.ams_id,
  2411. assignment.tray_id,
  2412. )
  2413. continue
  2414. # Different BL spool or unrecognized — unlink so auto-assign can match
  2415. logger.info(
  2416. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2417. assignment.spool_id,
  2418. assignment.ams_id,
  2419. assignment.tray_id,
  2420. tray_uuid,
  2421. )
  2422. stale.append(assignment)
  2423. else:
  2424. cur_color = current_tray.get("tray_color", "")
  2425. cur_type = current_tray.get("tray_type", "")
  2426. cur_state = current_tray.get("state")
  2427. fp_color = assignment.fingerprint_color or ""
  2428. fp_type = assignment.fingerprint_type or ""
  2429. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2430. # the slot was empty when the user pre-assigned via SpoolBuddy
  2431. # (the firmware drops ams_filament_setting on empty slots, so
  2432. # MQTT was deferred). The moment any filament gets inserted
  2433. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2434. # reconfigured spool — fire the deferred configuration.
  2435. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2436. # extruder" code) OR, on firmwares that don't use the state
  2437. # enum meaningfully, a non-empty tray_type when state is
  2438. # NOT one of the firmware's explicit empty signals (9, 10).
  2439. # state-only was wrong for firmwares that never set 11 — A1
  2440. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2441. # always report state=3 — so the replay never fired for them
  2442. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2443. # explicit "empty" signals authoritative over any stale
  2444. # tray_type that might survive the relay's auto-clearing.
  2445. #
  2446. # tray_exist_bits comes first because that guard cannot tell
  2447. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2448. # writes state=9 when the bit is 0 and leaves it there when the
  2449. # bit returns. A non-RFID spool inserted into a pre-assigned
  2450. # slot brings no tray_type with it, so the stale 9 made this
  2451. # expression false forever and the deferred config never fired
  2452. # — the deadlock #1322 removed from the assign path, still in
  2453. # place here (#3084, #3100).
  2454. loaded = spool_present(current_tray) is True or (
  2455. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2456. )
  2457. if not fp_type.strip() and loaded and assignment.spool:
  2458. # The fingerprint ends this replay. Not recorded when nothing
  2459. # could be sent (no MQTT client while the printer reconnects),
  2460. # so the next AMS change tries again. An attempt that raised is
  2461. # recorded as before: it may have sent part of the commands and
  2462. # would raise again on every change, remain% steps included.
  2463. configured: bool | None = False
  2464. try:
  2465. from backend.app.api.routes.inventory import (
  2466. apply_spool_to_slot_via_mqtt,
  2467. )
  2468. configured = await apply_spool_to_slot_via_mqtt(
  2469. db=db,
  2470. current_user=None,
  2471. spool=assignment.spool,
  2472. printer_id=printer_id,
  2473. ams_id=assignment.ams_id,
  2474. tray_id=assignment.tray_id,
  2475. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2476. current_tray_type=cur_type,
  2477. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2478. )
  2479. except Exception:
  2480. logger.exception(
  2481. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2482. assignment.spool_id,
  2483. printer_id,
  2484. assignment.ams_id,
  2485. assignment.tray_id,
  2486. )
  2487. configured = None
  2488. if configured is False:
  2489. logger.warning(
  2490. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2491. "retrying on the next AMS change",
  2492. assignment.spool_id,
  2493. printer_id,
  2494. assignment.ams_id,
  2495. assignment.tray_id,
  2496. )
  2497. else:
  2498. if configured:
  2499. logger.info(
  2500. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2501. assignment.spool_id,
  2502. printer_id,
  2503. assignment.ams_id,
  2504. assignment.tray_id,
  2505. )
  2506. assignment.fingerprint_color = cur_color
  2507. assignment.fingerprint_type = cur_type
  2508. continue
  2509. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2510. # Blank tray data mid-print is a runout, not a swap: the
  2511. # firmware clears colour and type when it unloads a spool
  2512. # it just emptied. Unlinking here would erase the record
  2513. # of which spool fed the print so far.
  2514. if printing_now and not cur_color.strip() and not cur_type.strip():
  2515. logger.info(
  2516. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2517. "(runout?)",
  2518. assignment.spool_id,
  2519. assignment.ams_id,
  2520. assignment.tray_id,
  2521. )
  2522. continue
  2523. # Same reasoning off the print, on firmware's own say-so:
  2524. # a blank tray report from a slot whose tray_exist_bits
  2525. # bit is set describes a spool the AMS cannot identify —
  2526. # a non-RFID one, or one whose slot was reset — not a
  2527. # spool that was taken out. Deleting the assignment there
  2528. # threw away the identity the user had supplied, which is
  2529. # the only place it existed (#3100). A slot the bit calls
  2530. # empty, or one that carries no bit at all, still unlinks.
  2531. #
  2532. # Unless the slot was reported empty first: a removal
  2533. # already held means a spool came out and another went
  2534. # in, so the blank report keeps the hold running below
  2535. # rather than cancelling it (#3186).
  2536. if (
  2537. spool_present(current_tray) is True
  2538. and not cur_color.strip()
  2539. and not cur_type.strip()
  2540. and not slot_unlink_grace.is_held(
  2541. printer_id,
  2542. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2543. )
  2544. ):
  2545. logger.info(
  2546. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2547. "tray reports no filament data yet",
  2548. assignment.spool_id,
  2549. assignment.ams_id,
  2550. assignment.tray_id,
  2551. )
  2552. continue
  2553. # A blank report the presence bit does not vouch for is
  2554. # still only one push. An idle X1C cleared a whole AMS
  2555. # unit's bits, colour and type for a moment and lost
  2556. # four saved assignments that way (#3186); unlink only
  2557. # if the slot is still blank after the grace period.
  2558. if not cur_color.strip() and not cur_type.strip():
  2559. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2560. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2561. held.add(hold_key)
  2562. logger.info(
  2563. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2564. "unlinking if it is still blank in %ds",
  2565. assignment.spool_id,
  2566. assignment.ams_id,
  2567. assignment.tray_id,
  2568. int(slot_unlink_grace.GRACE_SECONDS),
  2569. )
  2570. continue
  2571. # Fingerprint mismatch — but check if tray now matches the
  2572. # assigned spool (e.g. auto-configure changed the tray).
  2573. # Both sides are reduced to the type the slot can carry
  2574. # before comparing: the assign path writes that rather
  2575. # than the spool's raw material (#2902), so a spool whose
  2576. # material is a product line — "PLA+", "HTPLA" — reports
  2577. # back as "PLA" and would otherwise fail this check and
  2578. # be auto-unlinked from the slot it was just assigned to.
  2579. # Reducing the printer's side too keeps slots configured
  2580. # by an older Bambuddy, still reporting "PLA+", matching.
  2581. spool = assignment.spool
  2582. if spool:
  2583. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2584. # Two ways the assign path can have arrived at the
  2585. # slot's type, so both count as "we wrote this".
  2586. # The material column is one; the spool's preset is
  2587. # the other, and it outranks the material when the
  2588. # spool has one -- a spool whose material says PLA
  2589. # and whose preset is "Bambu PLA Aero" puts
  2590. # PLA-AERO in the slot (#2902). Read from the stored
  2591. # preset name rather than resolving the preset,
  2592. # because this runs on every AMS push and a cloud
  2593. # lookup here would be both slow and unavailable on
  2594. # the unauthenticated replay path.
  2595. spool_types = {printer_filament_type(spool.material).upper()}
  2596. if spool.slicer_filament_name:
  2597. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2598. # An imported local preset stores its type outright,
  2599. # which is what the assign path used -- and the name
  2600. # above may be unset. One keyed read, and only on a
  2601. # mismatch, which is rare.
  2602. #
  2603. # slicer_filament is free text up to fifty characters,
  2604. # so the digits have to be checked against the range
  2605. # of the integer primary key they are about to be
  2606. # compared with. Postgres raises on an out-of-range
  2607. # integer rather than simply not matching, and that
  2608. # would poison this session and abandon the rest of
  2609. # the cleanup pass.
  2610. lp_ref = (spool.slicer_filament or "").strip()
  2611. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2612. from backend.app.models.local_preset import LocalPreset as _LP
  2613. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2614. if lp_type:
  2615. spool_types.add(printer_filament_type(lp_type).upper())
  2616. if (
  2617. _colors_similar(cur_color, spool_color)
  2618. and printer_filament_type(cur_type).upper() in spool_types
  2619. ):
  2620. logger.info(
  2621. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2622. assignment.spool_id,
  2623. assignment.ams_id,
  2624. assignment.tray_id,
  2625. )
  2626. assignment.fingerprint_color = cur_color
  2627. assignment.fingerprint_type = cur_type
  2628. continue
  2629. logger.info(
  2630. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2631. assignment.spool_id,
  2632. assignment.ams_id,
  2633. assignment.tray_id,
  2634. cur_color,
  2635. cur_type,
  2636. fp_color,
  2637. fp_type,
  2638. spool.rgba if spool else "?",
  2639. spool.material if spool else "?",
  2640. )
  2641. stale.append(assignment) # Spool changed
  2642. slot_unlink_grace.settle(printer_id, "inventory", held)
  2643. # Snapshot slots before delete — ORM attribute access after the
  2644. # commit would refresh against a deleted row.
  2645. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2646. for a in stale:
  2647. await db.delete(a)
  2648. if stale:
  2649. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2650. # Commit any changes (stale deletions and/or fingerprint updates)
  2651. await db.commit()
  2652. # Tell open browsers the assignment is gone (#2575). Only the manual
  2653. # REST assign/unassign endpoints broadcast this event; without it the
  2654. # frontend's spool-assignments cache keeps rendering the unlinked
  2655. # spool on the slot until an unrelated refetch — which reads exactly
  2656. # like "the fix didn't work" (reporter verified: a browser refresh
  2657. # after the swap showed the correct state all along).
  2658. for ams_id, tray_id in unlinked_slots:
  2659. await ws_manager.broadcast(
  2660. {
  2661. "type": "spool_assignment_changed",
  2662. "printer_id": printer_id,
  2663. "ams_id": ams_id,
  2664. "tray_id": tray_id,
  2665. }
  2666. )
  2667. except Exception as e:
  2668. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2669. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2670. """Delete Spoolman slot rows whose held removal has run its grace period.
  2671. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2672. talks to Spoolman for every tray; this only needs the local rows, so it
  2673. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2674. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2675. not in a slot the presence bit calls occupied -- and nothing else.
  2676. """
  2677. logger = logging.getLogger(__name__)
  2678. try:
  2679. async with async_session() as db:
  2680. from backend.app.api.routes.settings import get_setting
  2681. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2682. from backend.app.services.ams_slot_presence import spool_present
  2683. enabled = await get_setting(db, "spoolman_enabled")
  2684. if not enabled or enabled.lower() != "true":
  2685. return
  2686. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2687. if sync_mode and sync_mode != "auto":
  2688. return
  2689. trays: dict[tuple[int, int], dict] = {}
  2690. for ams_unit in ams_data or []:
  2691. if not isinstance(ams_unit, dict):
  2692. continue
  2693. for tray in ams_unit.get("tray", []):
  2694. if isinstance(tray, dict):
  2695. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2696. rows = (
  2697. (
  2698. await db.execute(
  2699. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2700. )
  2701. )
  2702. .scalars()
  2703. .all()
  2704. )
  2705. held: set[tuple] = set()
  2706. expired: list[tuple[int, int]] = []
  2707. for row in rows:
  2708. tray = trays.get((row.ams_id, row.tray_id))
  2709. if tray is None or printing_now:
  2710. continue
  2711. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2712. continue
  2713. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2714. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2715. continue
  2716. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2717. expired.append((row.ams_id, row.tray_id))
  2718. else:
  2719. held.add(hold_key)
  2720. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2721. if not expired:
  2722. return
  2723. # A statement rather than ORM deletes, like the sync pass: the two
  2724. # can overlap, and a row the other already removed must not fail
  2725. # this commit.
  2726. for ams_id, tray_id in expired:
  2727. await db.execute(
  2728. delete(SpoolmanSlotAssignment).where(
  2729. SpoolmanSlotAssignment.printer_id == printer_id,
  2730. SpoolmanSlotAssignment.ams_id == ams_id,
  2731. SpoolmanSlotAssignment.tray_id == tray_id,
  2732. )
  2733. )
  2734. await db.commit()
  2735. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2736. for ams_id, tray_id in expired:
  2737. await ws_manager.broadcast(
  2738. {
  2739. "type": "spool_assignment_changed",
  2740. "printer_id": printer_id,
  2741. "ams_id": ams_id,
  2742. "tray_id": tray_id,
  2743. }
  2744. )
  2745. except Exception as e:
  2746. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2747. async def _recheck_held_unlinks(printer_id: int) -> None:
  2748. """Re-run just the slot cleanup against the printer's current AMS state.
  2749. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2750. passes otherwise run only when the AMS hash changes, and a slot that went
  2751. empty and stayed empty may never change it again.
  2752. """
  2753. status = printer_manager.get_status(printer_id)
  2754. # A disconnected printer's state is its last report, not a new one: acting
  2755. # on it would "confirm" a removal nobody has seen for the whole grace
  2756. # period. Leave the holds; the first push after reconnecting decides.
  2757. if status is None or not status.connected:
  2758. return
  2759. ams_raw = status.raw_data.get("ams")
  2760. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2761. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2762. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2763. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2764. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2765. async def on_ams_change(printer_id: int, ams_data: list):
  2766. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2767. logger = logging.getLogger(__name__)
  2768. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2769. # still being charged, skip weight sync later. on_print_complete may pop
  2770. # _active_sessions during our awaits (#880).
  2771. from backend.app.services.usage_tracker import printer_is_charging
  2772. _print_active = printer_is_charging(printer_id)
  2773. # A slot that reports empty while a print is running is a filament runout,
  2774. # not a spool swap: the spool is still physically in the AMS, just
  2775. # consumed. Dropping either inventory backend's slot link there loses the
  2776. # only record of which spool fed the print, so the completion path can't
  2777. # charge the runout segment to anything. Both cleanup passes below consult
  2778. # this; computed once, up front, so neither depends on the other having run.
  2779. _unlink_state = printer_manager.get_status(printer_id)
  2780. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2781. # The session alone is not enough: a restart that finds a stale persisted
  2782. # session registers none for the print that is running.
  2783. _print_active = _print_active or printing_now
  2784. # MQTT relay - publish AMS change
  2785. try:
  2786. printer_info = printer_manager.get_printer(printer_id)
  2787. if printer_info:
  2788. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2789. except Exception:
  2790. pass # Don't fail AMS callback if MQTT fails
  2791. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2792. # This ensures frontend gets immediate updates when AMS slots are configured
  2793. try:
  2794. state = printer_manager.get_status(printer_id)
  2795. if state:
  2796. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2797. await ws_manager.send_printer_status(
  2798. printer_id,
  2799. printer_state_to_dict(
  2800. state,
  2801. printer_id,
  2802. printer_manager.get_model(printer_id),
  2803. printer_manager.get_drying_targets(printer_id),
  2804. ),
  2805. )
  2806. except Exception as e:
  2807. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2808. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2809. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2810. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2811. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2812. # "no existing assignment" for the same (printer, ams, tray) and race to
  2813. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2814. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2815. # bug stayed latent there. See services/ams_assignment_lock for details.
  2816. try:
  2817. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2818. from sqlalchemy.orm import selectinload
  2819. from backend.app.api.routes.settings import get_setting
  2820. from backend.app.models.spool import Spool
  2821. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2822. from backend.app.services.spool_tag_matcher import (
  2823. auto_assign_spool,
  2824. create_spool_from_tray,
  2825. find_matching_untagged_spool,
  2826. get_spool_by_tag,
  2827. is_bambu_tag,
  2828. is_valid_tag,
  2829. link_tag_to_inventory_spool,
  2830. tag_belongs_to_archived_spool,
  2831. )
  2832. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2833. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2834. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2835. if not _spoolman_on or _spoolman_on.lower() != "true":
  2836. for ams_unit in ams_data:
  2837. if not isinstance(ams_unit, dict):
  2838. continue
  2839. ams_id = int(ams_unit.get("id", 0))
  2840. for tray in ams_unit.get("tray", []):
  2841. if not isinstance(tray, dict):
  2842. continue
  2843. tray_id = int(tray.get("id", 0))
  2844. tag_uid = tray.get("tag_uid", "")
  2845. tray_uuid = tray.get("tray_uuid", "")
  2846. tray_info_idx = tray.get("tray_info_idx", "")
  2847. if not tray.get("tray_type"):
  2848. # Slot reported empty — drop any cached unknown-tag
  2849. # broadcast so reinserting the same spool re-prompts.
  2850. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2851. continue # Empty slot
  2852. # Check if assignment already exists for this slot
  2853. existing = await db.execute(
  2854. select(SA)
  2855. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2856. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2857. )
  2858. existing_assignment = existing.scalar_one_or_none()
  2859. if existing_assignment:
  2860. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2861. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2862. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2863. # Skip during active prints: the usage tracker handles deduction
  2864. # precisely via 3MF data on print completion. Without this guard the
  2865. # AMS remain% SET and the usage tracker ADD both fire from the same
  2866. # MQTT message, doubling the deduction (#880).
  2867. if _print_active:
  2868. continue
  2869. remain_raw = tray.get("remain")
  2870. if (
  2871. remain_raw is not None
  2872. and existing_assignment.spool
  2873. and not existing_assignment.spool.weight_locked
  2874. ):
  2875. try:
  2876. remain_val = int(remain_raw)
  2877. except (TypeError, ValueError):
  2878. remain_val = -1
  2879. if 1 <= remain_val <= 100:
  2880. lw = existing_assignment.spool.label_weight or 1000
  2881. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2882. current_used = existing_assignment.spool.weight_used or 0
  2883. if new_used > current_used + 1:
  2884. # Rechecked in the statement: the spool was loaded
  2885. # before this, and a weight set by hand (or weighed)
  2886. # and locked since then must stay (WL-6).
  2887. result = cast(
  2888. CursorResult,
  2889. await db.execute(
  2890. update(Spool)
  2891. .where(
  2892. Spool.id == existing_assignment.spool_id,
  2893. Spool.weight_locked.is_not(True),
  2894. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2895. )
  2896. .values(weight_used=new_used)
  2897. ),
  2898. )
  2899. await db.commit()
  2900. if result.rowcount:
  2901. logger.info(
  2902. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2903. existing_assignment.spool_id,
  2904. current_used,
  2905. new_used,
  2906. remain_val,
  2907. )
  2908. await ws_manager.broadcast({"type": "inventory_changed"})
  2909. # A K-profile the slot lost (the default K after a reset or
  2910. # power cycle) is put back by kprofile_drift on the next idle
  2911. # push; a different real profile was picked on purpose and
  2912. # stays (#3219, item 44).
  2913. continue
  2914. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2915. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2916. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2917. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2918. # An archived spool still in the AMS: the slot
  2919. # stays free rather than adopting its tag.
  2920. continue
  2921. if not spool:
  2922. # Try matching an untagged inventory spool (same material/color)
  2923. spool = await find_matching_untagged_spool(db, tray)
  2924. if spool:
  2925. await link_tag_to_inventory_spool(db, spool, tray)
  2926. elif _auto_add_unknown:
  2927. spool = await create_spool_from_tray(db, tray)
  2928. else:
  2929. # Auto-add disabled: surface the slot so the
  2930. # user can add it manually via the UI.
  2931. await _broadcast_unknown_tag(
  2932. printer_id=printer_id,
  2933. ams_id=ams_id,
  2934. tray_id=tray_id,
  2935. tag_uid=tag_uid,
  2936. tray_uuid=tray_uuid,
  2937. tray_type=tray.get("tray_type"),
  2938. tray_color=tray.get("tray_color"),
  2939. tray_sub_brands=tray.get("tray_sub_brands"),
  2940. tray_count=len(ams_unit.get("tray", [])),
  2941. )
  2942. continue
  2943. # Slot matched (existing tag, untagged inventory
  2944. # match, or freshly auto-created spool) — drop any
  2945. # stale dedup so a future tag swap re-prompts.
  2946. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2947. await auto_assign_spool(
  2948. printer_id,
  2949. ams_id,
  2950. tray_id,
  2951. spool,
  2952. printer_manager,
  2953. db,
  2954. tray_info_idx=tray_info_idx,
  2955. )
  2956. await db.commit()
  2957. await ws_manager.broadcast(
  2958. {
  2959. "type": "spool_auto_assigned",
  2960. "printer_id": printer_id,
  2961. "ams_id": ams_id,
  2962. "tray_id": tray_id,
  2963. "spool_id": spool.id,
  2964. }
  2965. )
  2966. logger.info(
  2967. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2968. spool.id,
  2969. printer_id,
  2970. ams_id,
  2971. tray_id,
  2972. )
  2973. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2974. db, tag_uid, tray_uuid
  2975. ):
  2976. # Non-BL spool with some tag — let user choose (not
  2977. # an archived one's, whose slot stays free)
  2978. await _broadcast_unknown_tag(
  2979. printer_id=printer_id,
  2980. ams_id=ams_id,
  2981. tray_id=tray_id,
  2982. tag_uid=tag_uid,
  2983. tray_uuid=tray_uuid,
  2984. tray_type=tray.get("tray_type"),
  2985. tray_color=tray.get("tray_color"),
  2986. tray_sub_brands=tray.get("tray_sub_brands"),
  2987. tray_count=len(ams_unit.get("tray", [])),
  2988. )
  2989. # No-tag slots (generic non-RFID filament) are left alone:
  2990. # nothing to identify, prompting "+ Add" would just create
  2991. # ghost spools with empty tags on every confirm.
  2992. except Exception as e:
  2993. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2994. try:
  2995. async with async_session() as db:
  2996. from backend.app.api.routes.settings import get_setting
  2997. from backend.app.models.printer import Printer
  2998. # Check if Spoolman is enabled
  2999. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3000. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3001. return
  3002. # Check sync mode
  3003. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3004. if sync_mode and sync_mode != "auto":
  3005. return # Only sync on auto mode
  3006. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3007. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3008. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3009. # always owned by per-print tracking, never by AMS auto-sync. The
  3010. # setting is still read by the settings UI for backwards compat but
  3011. # has no effect on the sync path here.
  3012. # Get Spoolman URL
  3013. spoolman_url = await get_setting(db, "spoolman_url")
  3014. if not spoolman_url:
  3015. return
  3016. # Get or create Spoolman client
  3017. client = await get_spoolman_client()
  3018. if not client:
  3019. try:
  3020. client = await init_spoolman_client(spoolman_url)
  3021. except ValueError as exc:
  3022. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3023. return
  3024. # Check if Spoolman is reachable
  3025. if not await client.health_check():
  3026. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3027. return
  3028. # Get printer name for location
  3029. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3030. printer = result.scalar_one_or_none()
  3031. printer_name = printer.name if printer else f"Printer {printer_id}"
  3032. # OPTIMIZATION: Fetch all spools once before processing trays
  3033. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3034. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3035. try:
  3036. cached_spools = await client.get_spools()
  3037. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3038. except Exception as e:
  3039. logger.error(
  3040. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3041. printer_id,
  3042. e,
  3043. )
  3044. return
  3045. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3046. from sqlalchemy.orm import selectinload
  3047. from backend.app.models.spool_assignment import SpoolAssignment
  3048. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3049. from backend.app.services.ams_slot_presence import spool_present
  3050. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3051. # Built-in remaining weight, used by sync_ams_tray only when the
  3052. # firmware reports an unusable remain%/tray_weight for a slot.
  3053. #
  3054. # Left empty since #2812. This block runs in Spoolman mode only,
  3055. # and until then the built-in table was emptied on the switch, so
  3056. # there was never anything here to read and the fallback was inert.
  3057. # Preserving those rows makes it live again, and it is keyed by slot
  3058. # rather than by spool: after a mode switch the tray may well hold
  3059. # different filament, and ``create_spool`` writes ``remaining_weight``
  3060. # unconditionally, so a stale figure would be seeded into a brand new
  3061. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3062. # intent survives for whoever revisits the cross-mode fallback.
  3063. inventory_weights: dict[tuple[int, int], float] = {}
  3064. if not await spoolman_owns_assignments(db):
  3065. try:
  3066. assign_result = await db.execute(
  3067. select(SpoolAssignment)
  3068. .options(selectinload(SpoolAssignment.spool))
  3069. .where(SpoolAssignment.printer_id == printer_id)
  3070. )
  3071. for assignment in assign_result.scalars().all():
  3072. spool = assignment.spool
  3073. if spool and spool.label_weight > 0:
  3074. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3075. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3076. except Exception as e:
  3077. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3078. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3079. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3080. slot_map_read = False
  3081. try:
  3082. slot_result = await db.execute(
  3083. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3084. )
  3085. for slot in slot_result.scalars().all():
  3086. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3087. slot_map_read = True
  3088. except Exception as e:
  3089. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3090. # Sync each AMS tray and collect slot changes for DB persistence
  3091. synced = 0
  3092. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3093. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3094. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3095. for ams_unit in ams_data:
  3096. if not isinstance(ams_unit, dict):
  3097. continue
  3098. ams_id = int(ams_unit.get("id", 0))
  3099. trays = ams_unit.get("tray", [])
  3100. for tray_data in trays:
  3101. if not isinstance(tray_data, dict):
  3102. continue
  3103. tray_id_raw = int(tray_data.get("id", 0))
  3104. tray = client.parse_ams_tray(ams_id, tray_data)
  3105. if not tray:
  3106. # Empty tray slot — record for local assignment cleanup
  3107. # and drop any cached unknown-tag broadcast so a
  3108. # reinserted spool re-prompts.
  3109. #
  3110. # Not during a running print: a slot that empties there
  3111. # is a filament runout, and the spool is still in the
  3112. # AMS. `spoolman_slot_assignments` is how a tag-less
  3113. # spool assigned through the Bambuddy UI is resolved at
  3114. # completion (#1459), so deleting the row mid-print
  3115. # loses the runout segment's usage — the same failure
  3116. # the internal inventory's auto-unlink had.
  3117. #
  3118. # Nor when firmware's presence bit says the slot is
  3119. # occupied. parse_ams_tray calls a tray with no type or
  3120. # no colour empty, and a spool the AMS cannot read has
  3121. # neither until something configures it — so a tag-less
  3122. # spool assigned through the UI had its row deleted by
  3123. # the first idle push after it was inserted. Same
  3124. # deletion as the internal inventory's in #3100, same
  3125. # answer, so the two modes stay in step.
  3126. #
  3127. # And only once the slot has stayed empty for the grace
  3128. # period -- the internal inventory's #3186 answer, for
  3129. # the same one-push blank.
  3130. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3131. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3132. if not printing_now and (
  3133. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3134. ):
  3135. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3136. empty_slots.append((ams_id, tray_id_raw))
  3137. else:
  3138. spoolman_held.add(hold_key)
  3139. logger.info(
  3140. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3141. "unlinking if it is still empty in %ds",
  3142. ams_id,
  3143. tray_id_raw,
  3144. linked_spool,
  3145. int(slot_unlink_grace.GRACE_SECONDS),
  3146. )
  3147. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3148. continue
  3149. spool_tag = (
  3150. tray.tray_uuid
  3151. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3152. else tray.tag_uid
  3153. )
  3154. # Provide the hint only when no RFID is available
  3155. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3156. try:
  3157. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3158. result = await client.sync_ams_tray(
  3159. tray,
  3160. printer_name,
  3161. db,
  3162. # Per-print tracking is the only weight writer (#1119).
  3163. # AMS auto-sync still maintains spool metadata / slot
  3164. # assignments but no longer touches remaining_weight.
  3165. disable_weight_sync=True,
  3166. cached_spools=cached_spools,
  3167. inventory_remaining=inv_remaining,
  3168. spoolman_spool_id_hint=hint,
  3169. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3170. )
  3171. if result is None and spool_tag and not auto_add_unknown_rfid:
  3172. # Spoolman skipped auto-create per user setting — surface
  3173. # the slot so the UI can offer "+ Add to inventory".
  3174. await _broadcast_unknown_tag(
  3175. printer_id=printer_id,
  3176. ams_id=ams_id,
  3177. tray_id=tray.tray_id,
  3178. tag_uid=tray.tag_uid or "",
  3179. tray_uuid=tray.tray_uuid or "",
  3180. tray_type=tray.tray_type,
  3181. tray_color=tray.tray_color,
  3182. tray_sub_brands=tray.tray_sub_brands,
  3183. tray_count=len(trays),
  3184. )
  3185. elif result:
  3186. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3187. if result:
  3188. synced += 1
  3189. if result.get("id"):
  3190. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3191. # If a new spool was created, add it to the cache
  3192. # so subsequent trays can find it if they reference the same tag
  3193. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3194. if not spool_exists:
  3195. cached_spools.append(result)
  3196. logger.debug(
  3197. "[Printer %s] Added newly created spool %s to cache",
  3198. printer_id,
  3199. result["id"],
  3200. )
  3201. # Reconcile slot_preset_mappings (the same row internal
  3202. # mode keeps in sync via inventory + spool_tag_matcher).
  3203. # Without this the slot card surfaces the previous spool's
  3204. # preset name — same bug shape, different inventory mode.
  3205. from backend.app.services.slot_preset_writer import (
  3206. upsert_slot_preset_for_spoolman_spool,
  3207. )
  3208. await upsert_slot_preset_for_spoolman_spool(
  3209. db=db,
  3210. spoolman_spool=result,
  3211. tray_info_idx=tray.tray_info_idx or "",
  3212. tray_sub_brands=tray.tray_sub_brands or "",
  3213. tray_type=tray.tray_type or "",
  3214. printer_id=printer_id,
  3215. ams_id=ams_id,
  3216. tray_id=tray.tray_id,
  3217. )
  3218. except Exception as e:
  3219. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3220. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3221. if synced > 0:
  3222. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3223. # Persist slot assignment changes to the local table: only slots
  3224. # whose spool this pass changed, and only while they still hold what
  3225. # it read before awaiting Spoolman, so a spool assigned by hand in
  3226. # between stays (SSA-3). The changed slots are announced: the slot
  3227. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3228. # tray, so with no event it kept the previous spool's preset name.
  3229. if slot_changes or empty_slots:
  3230. from backend.app.services.spoolman_slot_sync import write_slot_results
  3231. try:
  3232. await write_slot_results(
  3233. db,
  3234. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3235. if slot_map_read
  3236. else None,
  3237. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3238. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3239. )
  3240. except Exception as e:
  3241. await db.rollback()
  3242. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3243. except Exception as e:
  3244. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3245. # Largest finish photo attached to a notification; a bigger one is still linked.
  3246. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3247. async def _finish_photo_for_notification(
  3248. db, archive, archive_id: int, filename: str
  3249. ) -> tuple[str | None, bytes | None]:
  3250. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3251. With authentication off the link is the archive's own photo route, as it
  3252. always was: it opens without a login and doesn't expire. With
  3253. authentication on that route needs a media token, which nothing tapping a
  3254. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3255. link only ever answered 401. The photo is then saved as a notification
  3256. photo as well (utils/notification_photos.py) and the link points there: an
  3257. unguessable name that opens this one photo and nothing else, for 3 days.
  3258. The link is relative when no External URL is set. Bytes over
  3259. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3260. ``(None, None)`` when the photo can't be found.
  3261. """
  3262. from backend.app.api.routes.settings import get_setting
  3263. from backend.app.core.auth import is_auth_enabled
  3264. from backend.app.utils.archive_paths import find_archive_photo
  3265. from backend.app.utils.notification_photos import save_notification_photo
  3266. log = logging.getLogger(__name__)
  3267. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3268. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3269. photo_bytes: bytes | None = None
  3270. try:
  3271. photo_path = find_archive_photo(archive, filename)
  3272. if photo_path is not None:
  3273. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3274. except Exception as e:
  3275. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3276. try:
  3277. auth_on = await is_auth_enabled(db)
  3278. except Exception:
  3279. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3280. if auth_on:
  3281. url = None
  3282. if photo_bytes:
  3283. try:
  3284. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3285. url = f"{base}/api/v1/notifications/photos/{name}"
  3286. except Exception as e:
  3287. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3288. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3289. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3290. return url, None
  3291. if photo_bytes:
  3292. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3293. return url, photo_bytes
  3294. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3295. """Capture a camera snapshot for notification image attachment.
  3296. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3297. Uses: external camera > buffered frame > fresh capture.
  3298. Turns the chamber light on for the picture when the printer asks for it
  3299. (#1655). ``light=False`` is for callers that capture all through a print,
  3300. where the light would flash with every frame.
  3301. """
  3302. if not printer:
  3303. return None
  3304. async with camera_light(printer if light else None):
  3305. return await _capture_snapshot_frame(printer_id, printer, logger)
  3306. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3307. """The capture behind ``_capture_snapshot_for_notification``."""
  3308. try:
  3309. from backend.app.api.routes.settings import get_setting
  3310. async with async_session() as db:
  3311. capture_enabled = await get_setting(db, "capture_finish_photo")
  3312. if capture_enabled is not None and capture_enabled.lower() != "true":
  3313. return None
  3314. # Try external camera first
  3315. if printer.external_camera_enabled and printer.external_camera_url:
  3316. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3317. from backend.app.api.routes.camera import live_frame_for_capture
  3318. from backend.app.services.external_camera import capture_frame
  3319. # An external camera allows one reader, so capturing while a viewer
  3320. # is attached fails (#2707). A None here falls through to the paths
  3321. # below exactly as a failed capture did.
  3322. defer, buffered = live_frame_for_capture(printer_id)
  3323. if defer:
  3324. frame_data = buffered
  3325. else:
  3326. frame_data = await capture_frame(
  3327. printer.external_camera_url,
  3328. printer.external_camera_type or "mjpeg",
  3329. snapshot_url=printer.external_camera_snapshot_url,
  3330. )
  3331. if frame_data and len(frame_data) <= 2_500_000:
  3332. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3333. return _apply_camera_rotation(frame_data, printer, logger)
  3334. # Try buffered frame from active stream
  3335. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3336. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3337. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3338. buffered_frame = get_buffered_frame(printer_id)
  3339. if (active_for_printer or active_chamber) and buffered_frame:
  3340. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3341. if len(buffered_frame) <= 2_500_000:
  3342. return _apply_camera_rotation(buffered_frame, printer, logger)
  3343. # Fresh capture from printer camera
  3344. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3345. from backend.app.services.camera import capture_camera_frame_bytes
  3346. frame_data = await capture_camera_frame_bytes(
  3347. printer.ip_address, printer.access_code, printer.model, timeout=15
  3348. )
  3349. if frame_data and len(frame_data) <= 2_500_000:
  3350. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3351. return _apply_camera_rotation(frame_data, printer, logger)
  3352. except Exception as e:
  3353. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3354. return None
  3355. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3356. """#1867: bank a recent in-print camera frame for the finish photo.
  3357. Called on every layer change and (#2547) on every print-progress advance.
  3358. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3359. path has a pre-End-G-code image for prints that end with a plate swap.
  3360. Both drivers are print telemetry that stops the instant printing ends: no
  3361. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3362. plate swap) executes. So the last banked frame is always the finished print,
  3363. never the swapped plate — that property is what the #1867 path relies on and
  3364. it must survive any change to the throttle below.
  3365. Layer changes alone were not enough: they stop when the *final* layer
  3366. begins, which on a three-minute last layer left the bank stale by the whole
  3367. length of that layer (#2547). Progress keeps ticking through it.
  3368. Best-effort: any failure just leaves the previous banked frame.
  3369. """
  3370. logger = logging.getLogger(__name__)
  3371. client = printer_manager.get_client(printer_id)
  3372. state = client.state if client else None
  3373. if not state or state.state != "RUNNING":
  3374. return
  3375. # Only during actual extrusion — firmware ticks layer_num during the
  3376. # pre-print calibration sequence, whose sub-stages are non-zero.
  3377. if state.mc_print_sub_stage not in (None, 0):
  3378. return
  3379. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3380. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3381. # now that progress advances also drive banking, that exemption would fire a
  3382. # camera grab on every percent tick of the last layer. Bambu printers accept
  3383. # one RTSP client at a time, so each grab contends with the live view.
  3384. now = time.monotonic()
  3385. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3386. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3387. return
  3388. total = state.total_layers or 0
  3389. try:
  3390. async with async_session() as db:
  3391. from backend.app.models.printer import Printer
  3392. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3393. printer = result.scalar_one_or_none()
  3394. if not printer:
  3395. return
  3396. # Reuses the notification snapshot path, which honours the
  3397. # `capture_finish_photo` setting (returns None when disabled) so we
  3398. # don't bank frames the user never asked for. Without the chamber light
  3399. # (#1655): this runs every 25 seconds for the whole print.
  3400. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3401. if frame:
  3402. _inprint_frame_bank[printer_id] = frame
  3403. _inprint_frame_bank_ts[printer_id] = now
  3404. logger.debug(
  3405. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3406. printer_id,
  3407. layer_num,
  3408. total,
  3409. len(frame),
  3410. )
  3411. except Exception as e:
  3412. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3413. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3414. """Apply camera rotation to snapshot image if configured."""
  3415. from backend.app.services.camera import apply_camera_rotation
  3416. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3417. async def _send_print_start_notification(
  3418. printer_id: int,
  3419. data: dict,
  3420. archive_data: dict | None = None,
  3421. logger=None,
  3422. ):
  3423. """Helper to send print start notification with optional archive data."""
  3424. if logger is None:
  3425. logger = logging.getLogger(__name__)
  3426. try:
  3427. async with async_session() as db:
  3428. from backend.app.models.printer import Printer
  3429. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3430. printer = result.scalar_one_or_none()
  3431. printer_name = printer.name if printer else f"Printer {printer_id}"
  3432. # Capture camera snapshot for notification image attachment
  3433. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3434. if image_data:
  3435. if archive_data is None:
  3436. archive_data = {}
  3437. archive_data["image_data"] = image_data
  3438. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3439. # Send user-specific email notification for print start
  3440. if archive_data and archive_data.get("created_by_id"):
  3441. await notification_service.send_user_print_email(
  3442. event_type="user_print_start",
  3443. created_by_id=archive_data["created_by_id"],
  3444. printer_name=printer_name,
  3445. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3446. db=db,
  3447. )
  3448. except Exception as e:
  3449. logger.warning("Notification on_print_start failed: %s", e)
  3450. async def _dispatch_user_print_email(
  3451. status: str,
  3452. created_by_id: int | None,
  3453. printer_name: str,
  3454. filename: str,
  3455. db,
  3456. image_data: bytes | None = None,
  3457. finish_photo_url: str | None = None,
  3458. ) -> None:
  3459. """Send a user-specific print-completion email based on print status.
  3460. Maps the normalised print status to the correct event type and delegates
  3461. to :meth:`NotificationService.send_user_print_email`. A single helper
  3462. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3463. "stopped"`` dispatch block at every call site.
  3464. Does nothing if *created_by_id* is ``None``.
  3465. """
  3466. if created_by_id is None:
  3467. return
  3468. if status == "completed":
  3469. event_type = "user_print_complete"
  3470. elif status == "failed":
  3471. event_type = "user_print_failed"
  3472. elif status in ("stopped", "aborted", "cancelled"):
  3473. event_type = "user_print_stopped"
  3474. else:
  3475. return
  3476. await notification_service.send_user_print_email(
  3477. event_type=event_type,
  3478. created_by_id=created_by_id,
  3479. printer_name=printer_name,
  3480. filename=filename,
  3481. db=db,
  3482. image_data=image_data,
  3483. finish_photo_url=finish_photo_url,
  3484. )
  3485. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3486. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3487. try:
  3488. from backend.app.services.archive import extract_printable_objects_from_archive
  3489. client = printer_manager.get_client(printer_id)
  3490. if not client:
  3491. return
  3492. # Extract with positions for UI overlay, scoped to the plate that
  3493. # is printing — resolve_plate_id is the same resolver /cover uses,
  3494. # so the object list can't disagree with the thumbnail it is drawn
  3495. # over (#2522).
  3496. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3497. app_settings.base_dir / archive.file_path,
  3498. plate_number=resolve_plate_id(client.state),
  3499. )
  3500. if printable_objects:
  3501. client.state.printable_objects = printable_objects
  3502. client.state.printable_objects_bbox_all = bbox_all
  3503. client.state.skipped_objects = []
  3504. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3505. except Exception as e:
  3506. logger.debug("Failed to extract printable objects from archive: %s", e)
  3507. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3508. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3509. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3510. handler must not wait for it. Kept only while the printer is still on
  3511. the print they were read for: a new print replaces the list.
  3512. ``warned_layers``: pauses this print was already warned about, kept on its
  3513. archive, so a restart does not send the heads-up again.
  3514. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3515. is on. Its pauses up to there are behind it, though the printer's layer
  3516. reads 0 until it reports the next one.
  3517. """
  3518. client = printer_manager.get_client(printer_id)
  3519. if not client:
  3520. return
  3521. state = client.state
  3522. read_for = state.pause_points
  3523. try:
  3524. plate_id = resolve_plate_id(state)
  3525. except Exception:
  3526. # Never at the cost of the print-start handler this runs inside.
  3527. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3528. return
  3529. async def _load() -> None:
  3530. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3531. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3532. if state.pause_points is not read_for:
  3533. return
  3534. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3535. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3536. if points:
  3537. logging.getLogger(__name__).info(
  3538. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3539. len(points),
  3540. printer_id,
  3541. [p.layer for p in points],
  3542. )
  3543. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3544. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3545. """Pauses for a print start taken as the resumption of a running print.
  3546. A restart while the print was paused makes its resume look like a new
  3547. print (#2984): the pauses warned about and passed are kept from before.
  3548. """
  3549. client = printer_manager.get_client(printer_id)
  3550. state = client.state if client else None
  3551. _load_pauses_from_3mf(
  3552. app_settings.base_dir / archive.file_path,
  3553. printer_id,
  3554. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3555. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3556. )
  3557. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3558. """Put the skip-objects list back after a restart mid-print.
  3559. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3560. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3561. which the #1304 guard suppresses on the first RUNNING push after startup.
  3562. Everything else this hook restores (the archive, the usage-tracking session,
  3563. the timelapse baseline) was already handled; the object list was not, so a
  3564. restart mid-print took skip-objects away for the rest of that print.
  3565. Nothing recovered it either: the printer card gates its Skip button on the
  3566. object count, and the one endpoint that can rebuild the list is reachable
  3567. only from the modal that button opens.
  3568. The archive is the running print's as ``running_print_archive`` finds it:
  3569. by subtask_id, or for a print that reports none by the archive bound to it
  3570. (#3327), never by name: a leftover ``status="printing"`` row from a
  3571. completion we never saw must not hand this print someone else's objects.
  3572. After a restart that binding exists only for Bambuddy's own prints, so a
  3573. print that reports no subtask_id loads nothing rather than a guess; the
  3574. reload path on ``GET /print/objects`` covers that case on demand.
  3575. """
  3576. client = printer_manager.get_client(printer_id)
  3577. if client is None or (client.state.printable_objects and client.state.pause_points):
  3578. return
  3579. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3580. if archive is not None and archive.file_path:
  3581. if not client.state.printable_objects:
  3582. _load_objects_from_archive(archive, printer_id, logger)
  3583. # The slicer's pauses are in-memory only as well (#2984).
  3584. if not client.state.pause_points:
  3585. _load_pauses_from_3mf(
  3586. app_settings.base_dir / archive.file_path,
  3587. printer_id,
  3588. warned_layers=pause_eta.warned_layers_of(archive, state),
  3589. )
  3590. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3591. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3592. # past it; the second covers a handshake that failed again on the way back and
  3593. # armed a fresh one. Module-level so tests can shrink them.
  3594. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3595. # Retry ladder for the other temporary give-up: the file service answered and
  3596. # the transfer still did not finish, which at print start is usually the printer
  3597. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3598. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3599. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3600. # two cover a printer that stays busy well into the print.
  3601. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3602. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3603. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3604. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3605. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3606. # by view, so two views race), the cool-off retry task, and print completion.
  3607. # Without this they each read file_path == "" and each run a full copy, so the row
  3608. # ends up pointing at one timestamped directory while the others sit orphaned.
  3609. #
  3610. # Keyed by printer rather than archive because a printer runs one print at a time,
  3611. # which makes the two equally strong here — and it bounds the dict by printer
  3612. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3613. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3614. # resuming, so "no waiters" is not a question this API can answer.
  3615. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3616. # How many of a printer's newest archives a touchscreen reprint is compared
  3617. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3618. # print start from reading a long history's extra_data.
  3619. _REPEAT_LOOKBACK = 200
  3620. async def _archived_3mf_for_repeat(
  3621. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3622. ):
  3623. """The newest archive of the job this printer is running again, with its 3MF.
  3624. A "Print again" on the printer's screen never names the file on the card:
  3625. it reports its own history copy under a generic name
  3626. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3627. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3628. not the card file's name, so every lookup built from it misses (#3307).
  3629. An earlier run that was archived recorded that same title and plate in its
  3630. ``_print_data``, and holds the 3MF.
  3631. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3632. known on both sides must agree: the same title and plate re-sliced is
  3633. another job. None when nothing matches.
  3634. """
  3635. from backend.app.models.archive import PrintArchive
  3636. if not subtask_name or not gcode_file:
  3637. return None
  3638. rows = (
  3639. (
  3640. await db.execute(
  3641. select(PrintArchive)
  3642. .where(
  3643. PrintArchive.printer_id == printer_id,
  3644. PrintArchive.deleted_at.is_(None),
  3645. PrintArchive.file_path.isnot(None),
  3646. PrintArchive.file_path != "",
  3647. )
  3648. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3649. .limit(_REPEAT_LOOKBACK)
  3650. )
  3651. )
  3652. .scalars()
  3653. .all()
  3654. )
  3655. for archive in rows:
  3656. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3657. run = extra.get("_print_data")
  3658. if not isinstance(run, dict):
  3659. continue
  3660. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3661. continue
  3662. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3663. continue
  3664. if not (app_settings.base_dir / archive.file_path).is_file():
  3665. continue
  3666. return archive
  3667. return None
  3668. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3669. """Fill in a no-3MF archive from a 3MF that turned up later.
  3670. Returns True when the row was upgraded. Safe to call speculatively: it
  3671. verifies the archive still exists, is still a fallback, and that the file
  3672. is a readable 3MF before touching anything.
  3673. Serialised per printer — see ``_fallback_recovery_locks``.
  3674. """
  3675. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3676. async with lock:
  3677. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3678. async def _recover_fallback_archive_locked(
  3679. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3680. ) -> bool:
  3681. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3682. ``price`` is False when the print's end is being handled: the archive
  3683. still reads "printing" then, and its end prices it.
  3684. """
  3685. import zipfile
  3686. from backend.app.models.archive import PrintArchive
  3687. from backend.app.services.archive import ArchiveService
  3688. logger = logging.getLogger(__name__)
  3689. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3690. return False
  3691. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3692. # A truncated or half-written download is worse than no download: it
  3693. # would replace an honest empty archive with wrong metadata.
  3694. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3695. return False
  3696. async with async_session() as db:
  3697. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3698. if archive is None or archive.deleted_at is not None:
  3699. return False
  3700. if archive.file_path:
  3701. # Already recovered, or never was a fallback. Either way there is a
  3702. # real 3MF attached and overwriting it is not this function's job.
  3703. return False
  3704. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3705. service = ArchiveService(db)
  3706. recovered = await service.archive_print(
  3707. printer_id=printer_id,
  3708. source_file=source_3mf,
  3709. print_data={**print_data, "status": archive.status or "printing"},
  3710. subtask_id=archive.subtask_id,
  3711. update_archive_id=archive.id,
  3712. )
  3713. if recovered is None:
  3714. return False
  3715. logger.info(
  3716. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3717. archive_id,
  3718. source_3mf,
  3719. recovered.file_size,
  3720. )
  3721. # Spoolman's tracking stored no 3MF usage at print start and would
  3722. # charge the AMS remain% change; the built-in tracker reads the archive
  3723. # at completion and needs nothing. Also at the print's end (``price``
  3724. # False): that recovery runs inside the close-out, before the charge.
  3725. try:
  3726. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3727. from backend.app.services.usage_tracker import is_completing
  3728. await attach_recovered_3mf(
  3729. printer_id,
  3730. recovered.id,
  3731. recovered.file_path,
  3732. db,
  3733. printer_manager,
  3734. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3735. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3736. )
  3737. except Exception:
  3738. logger.warning(
  3739. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3740. )
  3741. if price and recovered.status == "printing" and recovered.file_path:
  3742. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3743. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3744. if price and recovered.status == "printing":
  3745. # Print start priced it from the default rate, having no 3MF to
  3746. # estimate from; now it has one. An ended print is left alone: its
  3747. # end prices it. A print Bambuddy didn't dispatch has no start
  3748. # plate; the one the archive just read from the 3MF stands in.
  3749. _schedule_archive_cost_estimate(
  3750. printer_id,
  3751. recovered.id,
  3752. printer_manager,
  3753. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3754. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3755. session_factory=async_session,
  3756. )
  3757. # `archive_updated`, not `archive_created` — the row was already on the
  3758. # Archives page as an empty card and is now filled in, not new.
  3759. await ws_manager.send_archive_updated(
  3760. {
  3761. "id": recovered.id,
  3762. "printer_id": recovered.printer_id,
  3763. "filename": recovered.filename,
  3764. "print_name": recovered.print_name,
  3765. "status": recovered.status,
  3766. }
  3767. )
  3768. return True
  3769. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3770. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3771. Called from the paths that pull a 3MF for a print that is already under way
  3772. — chiefly the cover endpoint, which downloads the very file the archive flow
  3773. could not get and, before #2957, used it for a thumbnail and nothing else.
  3774. The bytes are already local, so this costs a parse and a row update.
  3775. No-op when the running print has a real archive, which is the common case.
  3776. """
  3777. from backend.app.models.archive import PrintArchive
  3778. logger = logging.getLogger(__name__)
  3779. # `_active_prints` is keyed on the raw names seen at print start — the
  3780. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3781. # Callers here arrive with whichever variant their own path produced, so
  3782. # match on the same normalization the download cache uses rather than on an
  3783. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3784. # endpoint find an archive registered under "Desktop_Goose".
  3785. wanted = normalize_3mf_name(name)
  3786. archive_id = None
  3787. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3788. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3789. archive_id = value
  3790. break
  3791. if archive_id is None:
  3792. return False
  3793. async with async_session() as db:
  3794. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3795. # Cheap pre-check so the common case (a normal archive) does no work.
  3796. if archive is None or archive.file_path or archive.deleted_at is not None:
  3797. return False
  3798. try:
  3799. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3800. except Exception as e:
  3801. # Recovery is opportunistic. A failure here must never take down the
  3802. # caller, which is usually just trying to render a thumbnail.
  3803. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3804. return False
  3805. def _schedule_fallback_3mf_retry(
  3806. printer_id: int,
  3807. archive_id: int,
  3808. filenames: list[str],
  3809. delays: tuple[float, ...] | None = None,
  3810. reason: str = REASON_FTPS_COOLOFF,
  3811. ) -> None:
  3812. """Re-attempt the 3MF download after a temporary give-up.
  3813. ``reason`` says which give-up this is, and picks the default ladder: an
  3814. FTPS cool-off has to be waited out, while a transfer that timed out under
  3815. contention is worth asking about again straight away (#3063). It is only
  3816. read for the ladder and the log line -- the retry itself is identical, since
  3817. in both cases the file is on the printer and the last attempt at it failed
  3818. for a reason that does not last.
  3819. """
  3820. logger = logging.getLogger(__name__)
  3821. if delays is None:
  3822. delays = (
  3823. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3824. if reason == REASON_FTP_TRANSFER_FAILED
  3825. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3826. )
  3827. async def _retry() -> None:
  3828. from backend.app.models.archive import PrintArchive
  3829. from backend.app.models.printer import Printer
  3830. for delay in delays:
  3831. await asyncio.sleep(delay)
  3832. async with async_session() as db:
  3833. archive = (
  3834. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3835. ).scalar_one_or_none()
  3836. if archive is None or archive.deleted_at is not None or archive.file_path:
  3837. return
  3838. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3839. if printer is None:
  3840. return
  3841. # Read the fields while the session is open rather than touching
  3842. # a detached instance minutes later, mid-download.
  3843. printer_ip = printer.ip_address
  3844. printer_code = printer.access_code
  3845. printer_model = printer.model
  3846. # Someone else may have fetched it in the meantime — the cover
  3847. # endpoint routinely does, and its copy is the same bytes.
  3848. for name in filenames:
  3849. cached = get_cached_3mf(printer_id, name)
  3850. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3851. return
  3852. if ftps_handshake_blocked(printer_ip):
  3853. logger.info(
  3854. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3855. printer_id,
  3856. archive_id,
  3857. )
  3858. continue
  3859. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3860. for candidate in filenames:
  3861. # Bare name only. These come from the print-start flow, which
  3862. # already strips the path, but the local temp write must not
  3863. # depend on that holding for every future caller — a name that
  3864. # is absolute or contains ".." would otherwise escape the data
  3865. # volume via the `/` operator.
  3866. name = Path(candidate).name
  3867. if not name or name in (".", ".."):
  3868. continue
  3869. if not name.endswith(".3mf"):
  3870. name = f"{name}.3mf"
  3871. temp_path = app_settings.archive_dir / "temp" / name
  3872. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3873. try:
  3874. hit = await download_file_try_paths_async(
  3875. printer_ip,
  3876. printer_code,
  3877. ftp_probe_paths(name),
  3878. temp_path,
  3879. socket_timeout=ftp_timeout,
  3880. printer_model=printer_model,
  3881. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3882. )
  3883. except Exception as e:
  3884. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3885. continue
  3886. if not hit:
  3887. continue
  3888. cache_3mf_download(printer_id, name, temp_path)
  3889. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3890. return
  3891. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3892. async def _guarded() -> None:
  3893. try:
  3894. await _retry()
  3895. except asyncio.CancelledError:
  3896. raise
  3897. except Exception as e:
  3898. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3899. finally:
  3900. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3901. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3902. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3903. if existing and not existing.done():
  3904. existing.cancel()
  3905. task = asyncio.create_task(_guarded())
  3906. _fallback_3mf_retry_tasks[printer_id] = task
  3907. logger.info(
  3908. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3909. archive_id,
  3910. reason,
  3911. printer_id,
  3912. ", ".join(f"{d:g}s" for d in delays),
  3913. )
  3914. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3915. """Whether an archive created here should ask for the print's outcome (#1898).
  3916. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3917. branches below: a queued job already has its archive and takes the
  3918. expected-print branch, where the queue item's own ``confirm_outcome``
  3919. decides. The queue is still consulted, because a restart mid-print empties
  3920. ``_expected_prints`` — without the check the setting could override a queue
  3921. item that deliberately has the flag off. Any failure answers "don't ask":
  3922. an unwanted prompt is worse than a missing one, and this must never be the
  3923. reason a print goes unarchived.
  3924. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3925. leaves one behind when a completion cannot be matched to it
  3926. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3927. only takes it back once the printer has sat connected and terminal for
  3928. minutes. Until then every screen-started print on that printer would
  3929. silently lose its prompt, so the row is held against ``observed_name`` by
  3930. the same comparison a completion uses: a positive disagreement means the row
  3931. is about some other run and this print is external after all.
  3932. """
  3933. logger = logging.getLogger(__name__)
  3934. try:
  3935. # A savepoint rather than a rollback of the caller's transaction on
  3936. # failure: a failed statement leaves the transaction unusable, but a
  3937. # full rollback also expires every object the caller has loaded (the
  3938. # printer, the archive it just created), and on an async session the
  3939. # next attribute read then raises instead of reloading. Everything here
  3940. # is a read, so undoing the savepoint loses nothing.
  3941. async with db.begin_nested():
  3942. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3943. except Exception as e:
  3944. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3945. return False
  3946. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3947. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3948. from backend.app.api.routes.settings import get_setting, setting_is_true
  3949. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3950. return False
  3951. from backend.app.models.print_queue import PrintQueueItem
  3952. dispatched_here = await db.scalar(
  3953. select(PrintQueueItem)
  3954. .where(
  3955. PrintQueueItem.printer_id == printer_id,
  3956. PrintQueueItem.status == "printing",
  3957. )
  3958. .limit(1)
  3959. )
  3960. if dispatched_here is None:
  3961. return True
  3962. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3963. observed = (observed_name or "").strip()
  3964. if not expected or not observed or _subtask_names_match(expected, observed):
  3965. logger.info(
  3966. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3967. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3968. printer_id,
  3969. dispatched_here.id,
  3970. )
  3971. return False
  3972. logger.info(
  3973. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3974. "%r; treating this as an externally started print.",
  3975. dispatched_here.id,
  3976. printer_id,
  3977. expected,
  3978. observed,
  3979. )
  3980. return True
  3981. async def _dispatch_outcome_confirmation_safely(
  3982. db,
  3983. printer_id: int,
  3984. printer_name: str,
  3985. data: dict,
  3986. archive_id: int,
  3987. archive_data: dict | None = None,
  3988. ) -> None:
  3989. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3990. The completion task sends the per-user print email on the same session
  3991. right after the prompt. A failed statement in the prompt leaves that
  3992. session needing a rollback, and without one the email step fails with
  3993. PendingRollbackError; the prompt is the optional part, so it must not be
  3994. the reason the email never goes out.
  3995. """
  3996. try:
  3997. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3998. except Exception as e:
  3999. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4000. try:
  4001. await db.rollback()
  4002. except Exception:
  4003. pass
  4004. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4005. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4006. who may change everyone's archives. None (everyone on the printer) with auth
  4007. off, or for a print nobody owns."""
  4008. from sqlalchemy.orm import selectinload
  4009. from backend.app.core.auth import is_auth_enabled
  4010. from backend.app.core.permissions import Permission
  4011. from backend.app.models.user import User
  4012. if owner_id is None or not await is_auth_enabled(db):
  4013. return None
  4014. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4015. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4016. async def dispatch_outcome_confirmation(
  4017. db,
  4018. printer_id: int,
  4019. printer_name: str,
  4020. data: dict,
  4021. archive_id: int,
  4022. archive_data: dict | None = None,
  4023. ) -> bool:
  4024. """Emit the post-print outcome prompt for a completed archive (#1898).
  4025. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  4026. queue item, or from ``confirm_outcome_external_prints`` for a print
  4027. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  4028. question still open. Mints the per-archive capability token the one-tap
  4029. verdict links carry.
  4030. Lives here rather than inline in ``on_print_complete``'s notification task
  4031. because that task swallows every exception: extracted, the gate and the two
  4032. emissions can be driven by a test, which is the only thing standing between
  4033. a regression here and a farm that quietly stops asking.
  4034. Returns whether a prompt was sent.
  4035. """
  4036. logger = logging.getLogger(__name__)
  4037. from backend.app.models.archive import PrintArchive
  4038. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4039. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  4040. return False
  4041. import secrets as _secrets
  4042. # A spent token stays on the row so the one-tap route can recognise it, so
  4043. # "has a token" no longer means "answerable". A prompt going out now needs a
  4044. # live one: mint a new token whenever the stored one is already spent, or
  4045. # every button in the new message would land on the already-answered page.
  4046. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  4047. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  4048. confirm_archive.confirm_token_used_at = None
  4049. await db.commit()
  4050. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4051. base = await get_external_base_url(db)
  4052. if not await get_setting(db, "external_url"):
  4053. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4054. # absolute URL, so an unconfigured install used to get a message body
  4055. # with two unusable relative paths and no buttons at all. The shared
  4056. # fallback at least produces tappable links; say which setting makes
  4057. # them resolve from a phone.
  4058. logger.warning(
  4059. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4060. "Set Settings → External URL so they resolve away from this host.",
  4061. base,
  4062. )
  4063. token = confirm_archive.confirm_token
  4064. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4065. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4066. confirm_url = f"{base}/archives?confirm={archive_id}"
  4067. await ws_manager.send_print_confirm_request(
  4068. printer_id,
  4069. {
  4070. "archive_id": archive_id,
  4071. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4072. },
  4073. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4074. )
  4075. await notification_service.on_print_confirm_request(
  4076. printer_id,
  4077. printer_name,
  4078. data,
  4079. db,
  4080. archive_data=archive_data,
  4081. good_url=good_url,
  4082. reject_url=reject_url,
  4083. confirm_url=confirm_url,
  4084. archive_id=archive_id,
  4085. )
  4086. return True
  4087. async def _printer_gone(db, printer_id: int) -> bool:
  4088. """Whether the printer was deleted. A column read: the session's loaded
  4089. Printer would otherwise answer for the database."""
  4090. from backend.app.models.printer import Printer
  4091. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4092. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4093. """Remove the archive just written if its printer was deleted meanwhile.
  4094. The delete route sweeps the printer's archives before it commits, so a row
  4095. committed after that sweep (the check before writing passed while the
  4096. delete was still uncommitted) is left for a printer that will never report
  4097. the print's end. A row the sweep reached is the route's: deleted with the
  4098. printer's archives, or detached (printer_id NULL) when the user kept them,
  4099. and then left as it is. Either way nothing is registered for it. Run after
  4100. the archive's commit, before anything is registered for it.
  4101. """
  4102. from backend.app.models.archive import PrintArchive
  4103. if not await _printer_gone(db, printer_id):
  4104. return False
  4105. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4106. if owner == printer_id:
  4107. logging.getLogger(__name__).info(
  4108. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4109. )
  4110. await ArchiveService(db).delete_archive(archive_id)
  4111. await forget_printer(printer_id)
  4112. return True
  4113. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4114. """After an IntegrityError on a print start's archive write: whether it was
  4115. the printer being deleted, forgotten then (the caller returns).
  4116. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4117. commit, so an archive written or adopted for it meanwhile (one that sets
  4118. printer_id) waits and the printer's foreign key then refuses it. That is
  4119. the printer being deleted, not an error; anything else is re-raised by the
  4120. caller.
  4121. """
  4122. await db.rollback()
  4123. if not await _printer_gone(db, printer_id):
  4124. return False
  4125. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4126. await forget_printer(printer_id)
  4127. return True
  4128. async def _forget_if_printer_gone(printer_id: int) -> None:
  4129. """At the end of a print start: the slow steps after the last check (smart
  4130. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4131. printer's delete and its forget_printer, and then wrote state back.
  4132. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4133. SQLite; PostgreSQL refuses it.)
  4134. Its own session: those steps can leave the handler's needing a rollback (a
  4135. write to the archive the delete removed). Never raises: it runs inside the
  4136. fallback branch's try, whose except reports the archive as failed.
  4137. """
  4138. try:
  4139. async with async_session() as db:
  4140. gone = await _printer_gone(db, printer_id)
  4141. if gone:
  4142. await forget_printer(printer_id)
  4143. except Exception:
  4144. logging.getLogger(__name__).warning(
  4145. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4146. )
  4147. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4148. """Tell the UI a plate check could not run. It does not block the print,
  4149. but an unchecked plate is not an empty one."""
  4150. try:
  4151. await ws_manager.broadcast(
  4152. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4153. )
  4154. except Exception as e:
  4155. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4156. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4157. """The ``_expected_prints`` keys a print start may be registered under."""
  4158. keys: list[tuple[int, str]] = []
  4159. if subtask_name:
  4160. keys.append((printer_id, subtask_name))
  4161. keys.append((printer_id, f"{subtask_name}.3mf"))
  4162. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4163. if filename:
  4164. fname = filename.split("/")[-1] if "/" in filename else filename
  4165. keys.append((printer_id, fname))
  4166. # Strip extensions to match
  4167. base = fname.replace(".gcode", "").replace(".3mf", "")
  4168. keys.append((printer_id, base))
  4169. keys.append((printer_id, f"{base}.3mf"))
  4170. return keys
  4171. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4172. """Whether this print start is one Bambuddy sent to the printer."""
  4173. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4174. return True
  4175. from backend.app.models.archive import PrintArchive
  4176. from backend.app.models.print_queue import PrintQueueItem
  4177. # The queue row the scheduler sets to printing before it sends -- but only
  4178. # when it was sent as this print: a row left printing by a run whose end
  4179. # was missed names another file.
  4180. dispatched_names = (
  4181. await db.execute(
  4182. select(PrintArchive.filename)
  4183. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4184. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4185. )
  4186. ).scalars()
  4187. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4188. return any(
  4189. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4190. for dispatched in dispatched_names
  4191. if dispatched
  4192. for seen in observed
  4193. )
  4194. async def on_print_start(printer_id: int, data: dict):
  4195. """Handle print start - archive the 3MF file immediately."""
  4196. logger = logging.getLogger(__name__)
  4197. # The print's start, before the 3MF download that the archive waits for
  4198. # (#3327): a minute of it would otherwise be missing from the print time.
  4199. detected_at = datetime.now(timezone.utc)
  4200. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4201. try:
  4202. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4203. except Exception:
  4204. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4205. # Clear any stale user-stopped flag from previous print cycles
  4206. _user_stopped_printers.discard(printer_id)
  4207. _kill_switch_stopped.discard(printer_id)
  4208. # A new print starts its milestones from zero (#3211). The status path only
  4209. # resets on progress below 5 while not printing, which a printer that goes
  4210. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4211. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4212. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4213. _last_progress_milestone[printer_id] = 0
  4214. _kill_switch_notification_tasks.pop(printer_id, None)
  4215. # #1721: drop any leftover pre-captured finish frame from a prior print
  4216. # so a never-consumed cache entry can't bleed into the new print's photo.
  4217. _stage22_finish_frames.pop(printer_id, None)
  4218. # #1867: same for the in-print frame bank — a queued print must not reuse
  4219. # the previous job's banked frame.
  4220. _inprint_frame_bank.pop(printer_id, None)
  4221. _inprint_frame_bank_ts.pop(printer_id, None)
  4222. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4223. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4224. # print's flag instead of inheriting it.
  4225. print_dispatch_context.adopt(printer_id)
  4226. # Cancel any active bed cooldown waiter for this printer
  4227. if _bed_cool_waiters.pop(printer_id, None):
  4228. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4229. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4230. from backend.app.api.routes.printers import clear_cover_cache
  4231. clear_cover_cache(printer_id)
  4232. await ws_manager.send_print_start(printer_id, data)
  4233. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4234. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4235. # MQTT relay - publish print start
  4236. try:
  4237. printer_info = printer_manager.get_printer(printer_id)
  4238. if printer_info:
  4239. await mqtt_relay.on_print_start(
  4240. printer_id,
  4241. printer_info.name,
  4242. printer_info.serial_number,
  4243. data.get("filename", ""),
  4244. data.get("subtask_name", ""),
  4245. )
  4246. except Exception:
  4247. pass # Don't fail print start callback if MQTT fails
  4248. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4249. # and mapping, and the seeded tray-change log.
  4250. #
  4251. # Unconditional, for both inventory backends. This only *captures* — the
  4252. # writing is still split, with the internal tracker skipped at completion
  4253. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4254. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4255. # tray-change log, and that log is the only record of which spool fed
  4256. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4257. # it on one side only would leave Spoolman users with the mid-print
  4258. # restart bug this fixes for everyone else.
  4259. try:
  4260. async with async_session() as db:
  4261. from backend.app.api.routes.settings import get_setting
  4262. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4263. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4264. await usage_on_print_start(
  4265. printer_id,
  4266. data,
  4267. printer_manager,
  4268. db=db,
  4269. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4270. )
  4271. except Exception as e:
  4272. logger.warning("Usage tracker on_print_start failed: %s", e)
  4273. # Track if notification was sent (to avoid sending twice)
  4274. notification_sent = False
  4275. # Smart plug automation: turn on plug when print starts
  4276. try:
  4277. async with async_session() as db:
  4278. await smart_plug_manager.on_print_start(printer_id, db)
  4279. except Exception as e:
  4280. logger.warning("Smart plug on_print_start failed: %s", e)
  4281. async with async_session() as db:
  4282. from backend.app.models.printer import Printer
  4283. from backend.app.services.bambu_ftp import list_files_async
  4284. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4285. printer = result.scalar_one_or_none()
  4286. # Plate detection check - pause if objects detected on build plate
  4287. logger.info(
  4288. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4289. )
  4290. if printer and printer.plate_detection_enabled:
  4291. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4292. # Release the pooled DB connection before the plate-detection camera
  4293. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4294. # printer SELECT has run so far — nothing to persist — so this commit
  4295. # is a data-noop that ends the read transaction and returns the
  4296. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4297. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4298. # archive lookups below re-acquire a fresh connection on next execute.
  4299. await db.commit()
  4300. try:
  4301. from backend.app.services.plate_detection import check_plate_empty
  4302. # Build ROI tuple from printer settings if available
  4303. roi = None
  4304. if all(
  4305. [
  4306. printer.plate_detection_roi_x is not None,
  4307. printer.plate_detection_roi_y is not None,
  4308. printer.plate_detection_roi_w is not None,
  4309. printer.plate_detection_roi_h is not None,
  4310. ]
  4311. ):
  4312. roi = (
  4313. printer.plate_detection_roi_x,
  4314. printer.plate_detection_roi_y,
  4315. printer.plate_detection_roi_w,
  4316. printer.plate_detection_roi_h,
  4317. )
  4318. # The light is held, not switched, so a live view opened
  4319. # meanwhile keeps it when the check lets go (SP-C11). Every
  4320. # printer, whatever the camera light mode: detection needs it.
  4321. plate_photo_data = None
  4322. objects_detected = False
  4323. check_failure: str | None = None
  4324. async with camera_light(printer, any_mode=True, settle=2.5):
  4325. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4326. plate_result = await check_plate_empty(
  4327. printer_id=printer_id,
  4328. ip_address=printer.ip_address,
  4329. access_code=printer.access_code,
  4330. model=printer.model,
  4331. include_debug_image=False,
  4332. external_camera_url=printer.external_camera_url,
  4333. external_camera_type=printer.external_camera_type,
  4334. use_external=printer.external_camera_enabled,
  4335. roi=roi,
  4336. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4337. )
  4338. # No reference to compare against is a check that did not
  4339. # run either: say so rather than call the plate empty.
  4340. check_failure = getattr(plate_result, "failure_reason", None) or (
  4341. "not_calibrated" if plate_result.needs_calibration else None
  4342. )
  4343. objects_detected = not check_failure and not plate_result.is_empty
  4344. if objects_detected:
  4345. # Objects detected - pause the print!
  4346. logger.warning(
  4347. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4348. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4349. )
  4350. pause_client = printer_manager.get_client(printer_id)
  4351. if pause_client:
  4352. pause_client.pause_print()
  4353. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4354. # Snapshot while the light's still on — restoring it first
  4355. # would leave the notification with a dark photo.
  4356. try:
  4357. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4358. except Exception as snap_err:
  4359. logger.warning(
  4360. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4361. )
  4362. if objects_detected:
  4363. # Send notification about plate not empty
  4364. await ws_manager.broadcast(
  4365. {
  4366. "type": "plate_not_empty",
  4367. "printer_id": printer_id,
  4368. "printer_name": printer.name,
  4369. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4370. }
  4371. )
  4372. # Also send push notification
  4373. try:
  4374. await notification_service.on_plate_not_empty(
  4375. printer_id=printer_id,
  4376. printer_name=printer.name,
  4377. db=db,
  4378. difference_percent=plate_result.difference_percent,
  4379. image_data=plate_photo_data,
  4380. )
  4381. except Exception as notif_err:
  4382. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4383. elif check_failure:
  4384. logger.warning(
  4385. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4386. printer_id,
  4387. check_failure,
  4388. plate_result.message,
  4389. )
  4390. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4391. else:
  4392. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4393. except Exception as plate_err:
  4394. # Don't block print on plate detection errors
  4395. logger.warning(
  4396. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4397. printer_id,
  4398. plate_err,
  4399. )
  4400. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4401. if not printer:
  4402. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4403. if not notification_sent:
  4404. await _send_print_start_notification(printer_id, data, logger=logger)
  4405. return
  4406. # Skip the printer's own jobs — a calibration run is not a user's print.
  4407. # See is_internal_printer_job for what counts and why both fields are
  4408. # tested; the pressure-advance line reports as a subtask name with no
  4409. # /usr/ path, which the old prefix-only test here missed entirely.
  4410. #
  4411. # No notification either. The event describes the printer calibrating
  4412. # itself, so "Print started" is as wrong as the archive was, and the
  4413. # matching completion is suppressed in on_print_complete for the same
  4414. # reason. Checked before the auto-archive switches, whose "off" path
  4415. # still notifies.
  4416. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4417. # print Bambuddy dispatched is never one, whatever it is called.
  4418. # Dispatched = an expected print, or, after a restart that lost those,
  4419. # a queue job printing on the printer.
  4420. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4421. (data.get("filename") or "").startswith("/usr/")
  4422. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4423. ):
  4424. logger.info(
  4425. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4426. data.get("filename", ""),
  4427. data.get("subtask_name", ""),
  4428. )
  4429. return
  4430. # The global switch is the master: off, no printer archives prints
  4431. # started outside Bambuddy; on, each printer's own switch decides.
  4432. from backend.app.api.routes.settings import get_setting
  4433. _global_auto_archive = await get_setting(db, "auto_archive")
  4434. archives_prints = printer.auto_archive and (
  4435. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4436. )
  4437. if not archives_prints:
  4438. # auto-archive disabled — check if there's an expected print (dispatched
  4439. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4440. # If so, fall through to the expected-print handling below so the archive
  4441. # is tracked in _active_prints and usage tracking works at completion.
  4442. _fn = data.get("filename", "")
  4443. _sn = data.get("subtask_name", "")
  4444. _check_keys: list[tuple[int, str]] = []
  4445. if _sn:
  4446. _check_keys += [
  4447. (printer_id, _sn),
  4448. (printer_id, f"{_sn}.3mf"),
  4449. (printer_id, f"{_sn}.gcode.3mf"),
  4450. ]
  4451. if _fn:
  4452. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4453. _check_keys.append((printer_id, _base_fn))
  4454. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4455. _check_keys += [
  4456. (printer_id, _no_archive_base),
  4457. (printer_id, f"{_no_archive_base}.3mf"),
  4458. ]
  4459. _has_expected = any(k in _expected_prints for k in _check_keys)
  4460. if not _has_expected:
  4461. # No expected print — truly external print (started from slicer/touchscreen)
  4462. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4463. if not notification_sent:
  4464. _no_archive_creator: int | None = None
  4465. for _key in _check_keys:
  4466. _expected_prints.pop(_key, None)
  4467. _expected_print_registered_at.pop(_key, None)
  4468. popped_creator = _expected_print_creators.pop(_key, None)
  4469. if _no_archive_creator is None:
  4470. _no_archive_creator = popped_creator
  4471. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4472. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4473. return
  4474. else:
  4475. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4476. # Get the filename and subtask_name
  4477. filename = data.get("filename", "")
  4478. subtask_name = data.get("subtask_name", "")
  4479. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4480. # present, it lets us match an archive across a backend restart (#972):
  4481. # same id → same print → resume the existing row instead of cancelling
  4482. # it and recreating from scratch (which loses started_at). Treat "0"
  4483. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4484. raw_mqtt = data.get("raw_data") or {}
  4485. subtask_id = raw_mqtt.get("subtask_id")
  4486. if subtask_id is not None:
  4487. subtask_id = str(subtask_id).strip()
  4488. if subtask_id in ("", "0"):
  4489. subtask_id = None
  4490. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4491. if not filename and not subtask_name:
  4492. # Send notification without archive data (no filename)
  4493. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4494. if not notification_sent:
  4495. await _send_print_start_notification(printer_id, data, logger=logger)
  4496. return
  4497. # Check if this is an expected print from reprint/scheduled
  4498. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4499. expected_archive_id = None
  4500. # Who queued it, taken with the entries it was registered beside: left
  4501. # behind once those are gone (the archive deleted mid-dispatch, or the
  4502. # start notification already sent), the expiry never saw it, and an
  4503. # unrelated later print of that name was attributed to that user (EP-2).
  4504. fallback_creator = None
  4505. for key in expected_keys:
  4506. expected_archive_id = _expected_prints.pop(key, None)
  4507. _expected_print_registered_at.pop(key, None)
  4508. if expected_archive_id:
  4509. # Clean up other possible keys for this print
  4510. for other_key in expected_keys:
  4511. _expected_prints.pop(other_key, None)
  4512. _expected_print_registered_at.pop(other_key, None)
  4513. creator = _expected_print_creators.pop(other_key, None)
  4514. if fallback_creator is None:
  4515. fallback_creator = creator
  4516. break
  4517. if expected_archive_id:
  4518. # This is a reprint/scheduled print - use existing archive, don't create new one
  4519. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4520. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4521. # Bambuddy's once the expected entry is consumed here.
  4522. _owned_print_archive_ids.add(expected_archive_id)
  4523. from backend.app.models.archive import PrintArchive
  4524. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4525. archive = result.scalar_one_or_none()
  4526. # Deleted after this handler loaded it (the plate check waits
  4527. # seconds) but before the route forgot the expected print: the
  4528. # archive the route kept or deleted is left as the route left it.
  4529. if archive and await _printer_gone(db, printer_id):
  4530. logger.info(
  4531. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4532. )
  4533. await forget_printer(printer_id)
  4534. return
  4535. if archive:
  4536. # As it was before this adoption: put back if the printer turns
  4537. # out to have been deleted while it was adopted (below).
  4538. before_adoption = {
  4539. attr.columns[0].name: getattr(archive, attr.key)
  4540. for attr in sa_inspect(PrintArchive).column_attrs
  4541. if attr.key != "id"
  4542. }
  4543. # Update archive status to printing
  4544. archive.status = "printing"
  4545. archive.started_at = datetime.now(timezone.utc)
  4546. # The previous run's outcome is not this one's: a reprint that
  4547. # completes must not keep showing why the last one failed.
  4548. archive.failure_reason = None
  4549. archive.completed_at = None
  4550. # The previous run's answer is still on this row and the
  4551. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4552. # so without a reset the second run inherits the first run's
  4553. # verdict: no prompt at all, and a green "good" badge on a run
  4554. # nobody ever judged.
  4555. if archive.confirm_requested:
  4556. archive.user_verdict = None
  4557. archive.user_verdict_source = None
  4558. archive.user_verdict_at = None
  4559. archive.confirm_token = None
  4560. archive.confirm_token_used_at = None
  4561. # Reprint of an archive reuses the source row. Without resetting
  4562. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4563. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4564. # extracts the *original* print's last frame, which then ships in
  4565. # the completion notification (#1707). Clear the path so the
  4566. # scanner runs fresh; also unlink the old video file so reprints
  4567. # don't accumulate orphans in the archive directory. Photos list
  4568. # is left alone — accumulating one finish photo per run is fine.
  4569. # The print-start baseline (#2704) is stale for the same reason:
  4570. # it describes the printer before the previous run. The capture
  4571. # below overwrites it, but clear it here too so an early failure
  4572. # can't leave the scan diffing against the wrong snapshot.
  4573. #
  4574. # Unlinked only when it is the same plate printing again. Every
  4575. # plate of a Send All shares this archive, and the video on it
  4576. # can be the only copy of another plate's run -- the printer's
  4577. # was deleted once it attached (#3275). That one is left in the
  4578. # archive directory, which goes with the archive. A video whose
  4579. # plate is not on record (attached by hand, or before the
  4580. # column existed) is kept too where the 3MF has other plates,
  4581. # or cannot be read: nothing tells it apart from another plate's,
  4582. # and keeping costs one file where deleting can cost the only
  4583. # copy. On an archive with exactly one plate it is that plate's.
  4584. archive.timelapse_baseline = None
  4585. stale_timelapse_relpath = archive.timelapse_path
  4586. stale_timelapse_plate_id = archive.timelapse_plate_id
  4587. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4588. if stale_timelapse_relpath:
  4589. archive.timelapse_path = None
  4590. archive.timelapse_plate_id = None
  4591. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4592. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4593. from backend.app.services.archive import plate_indexes_in_3mf
  4594. plates = await asyncio.to_thread(
  4595. plate_indexes_in_3mf,
  4596. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4597. )
  4598. stale_is_this_plates = len(plates) == 1
  4599. if stale_timelapse_relpath and not stale_is_this_plates:
  4600. logger.info(
  4601. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4602. stale_timelapse_relpath,
  4603. stale_timelapse_plate_id,
  4604. expected_archive_id,
  4605. starting_plate_id,
  4606. )
  4607. # The video is deleted once the adoption stands (below).
  4608. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4609. # Persist a restart-stable id so a later restart resumes this
  4610. # archive by subtask_id instead of name-matching + duplicating
  4611. # it (#1485). The printer often hasn't echoed subtask_id back
  4612. # this soon after dispatch, so fall back to the id Bambuddy
  4613. # minted when it sent the print command. Scoped to this
  4614. # expected-print branch on purpose: an expected match means
  4615. # Bambuddy dispatched this exact print in this process, so the
  4616. # client's last-dispatch id genuinely belongs to it — using it
  4617. # for an externally-started print could mis-tag the archive.
  4618. effective_subtask_id = subtask_id
  4619. if not effective_subtask_id:
  4620. _client = printer_manager.get_client(printer_id)
  4621. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4622. if _dispatched:
  4623. effective_subtask_id = str(_dispatched).strip() or None
  4624. # Update on first-set OR on reprint (the queue dispatcher mints
  4625. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4626. # the rewrite for reprints leaves the archive holding the FIRST
  4627. # run's id; if MQTT then reconnects mid-print, the reconciler
  4628. # (#1542) compares the stale stored id against the printer's
  4629. # live id, sees a mismatch, and synthesises a bogus PRINT
  4630. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4631. # in #1807. Inequality check preserves the noop-on-stable-push
  4632. # behaviour the earlier `not archive.subtask_id` guard provided.
  4633. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4634. archive.subtask_id = effective_subtask_id
  4635. # #1403 follow-up: VP-queue archives are created with
  4636. # printer_id=None at queue-add time (we don't know which
  4637. # printer will run the job yet). When the print actually
  4638. # starts on a specific printer the expected-archive lookup
  4639. # used to skip this assignment, leaving printer_id=None
  4640. # forever — which then disables the "Scan for timelapse"
  4641. # button in ArchivesPage (gated on !archive.printer_id).
  4642. if archive.printer_id != printer_id:
  4643. archive.printer_id = printer_id
  4644. adopting_id = archive.id # a rollback expires the object
  4645. try:
  4646. await db.commit()
  4647. except (IntegrityError, StaleDataError):
  4648. # The archive stays unchanged, or is gone: "delete archives"
  4649. # removed the row under the adoption, which then matched no
  4650. # row (StaleDataError) rather than being refused.
  4651. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4652. return
  4653. raise
  4654. # The printer can be deleted between the check above and this
  4655. # commit (the route's transaction lasts seconds), and the commit
  4656. # then adopted the archive anyway: status, verdict and timelapse
  4657. # changed, and the deleted printer's id written on a row the
  4658. # route had detached or never touched. Undo the adoption.
  4659. if await _printer_gone(db, printer_id):
  4660. logger.info(
  4661. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4662. printer_id,
  4663. archive.id,
  4664. )
  4665. # Everything as before this adoption. The printer it had
  4666. # then stays, unless it was the deleted one: the route
  4667. # detached that row (kept) or deleted it (no row matches).
  4668. previous_printer = before_adoption["printer_id"]
  4669. await db.execute(
  4670. update(PrintArchive)
  4671. .where(PrintArchive.id == archive.id)
  4672. .values(
  4673. {
  4674. **before_adoption,
  4675. "printer_id": None if previous_printer == printer_id else previous_printer,
  4676. }
  4677. )
  4678. )
  4679. await db.commit()
  4680. await forget_printer(printer_id)
  4681. return
  4682. if delete_stale_video and stale_timelapse_relpath:
  4683. try:
  4684. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4685. if stale_path.is_file():
  4686. stale_path.unlink()
  4687. logger.info(
  4688. "Deleted stale timelapse %s on reprint of archive %s",
  4689. stale_timelapse_relpath,
  4690. expected_archive_id,
  4691. )
  4692. except OSError as e:
  4693. logger.warning(
  4694. "Failed to delete stale timelapse %s on reprint: %s",
  4695. stale_timelapse_relpath,
  4696. e,
  4697. )
  4698. # Track as active print
  4699. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4700. await _open_run_for(archive.id, printer_id)
  4701. # Start timelapse session if external camera is enabled (#1353).
  4702. # Queue / VP-dispatched prints land here in the expected-archive
  4703. # branch and used to skip start_session entirely — frames were
  4704. # never captured and the post-print stitch silently returned None.
  4705. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4706. # Inject ams_mapping into usage tracker session — the session was created
  4707. # before expected-print promotion, so it may have ams_mapping=None when
  4708. # the MQTT request topic subscription failed (common on P1S/A1).
  4709. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4710. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4711. if _stored_map or _stored_plate_id is not None:
  4712. try:
  4713. from backend.app.services.usage_tracker import _active_sessions
  4714. _ut_session = _active_sessions.get(printer_id)
  4715. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4716. _ut_session.ams_mapping = _stored_map
  4717. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4718. # plate_id injection covers direct-Print of plate N of a multi-plate
  4719. # 3MF — queue prints already capture it via the on_print_start queue
  4720. # lookup, but direct-Print never goes through the queue (#1697).
  4721. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4722. _ut_session.plate_id = _stored_plate_id
  4723. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4724. except Exception:
  4725. pass
  4726. # Set up energy tracking (#941: persist start on archive row)
  4727. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4728. await ws_manager.send_archive_updated(
  4729. {
  4730. "id": archive.id,
  4731. "status": "printing",
  4732. }
  4733. )
  4734. # Send notification with archive data (reprint/scheduled)
  4735. if not notification_sent:
  4736. # Use archive's created_by_id; fall back to the creator registered via
  4737. # register_expected_print (handles library-file-based queue items where
  4738. # the freshly-created archive has no created_by_id yet), taken above.
  4739. archive_data = {
  4740. "print_time_seconds": archive.print_time_seconds,
  4741. "created_by_id": archive.created_by_id or fallback_creator,
  4742. }
  4743. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4744. # Extract printable objects from the archived 3MF file
  4745. _load_objects_from_archive(archive, printer_id, logger)
  4746. if archive.file_path:
  4747. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4748. # Store Spoolman tracking data for per-filament usage reporting
  4749. try:
  4750. await _store_spoolman_print_data(
  4751. printer_id,
  4752. archive.id,
  4753. archive.file_path,
  4754. db,
  4755. printer_manager,
  4756. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4757. plate_id=_get_start_plate_id(printer_id, archive.id),
  4758. )
  4759. except Exception as e:
  4760. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4761. # Price the print from its spools now rather than only at completion (#3261)
  4762. _schedule_archive_cost_estimate(
  4763. printer_id,
  4764. archive.id,
  4765. printer_manager,
  4766. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4767. plate_id=_get_start_plate_id(printer_id, archive.id),
  4768. session_factory=async_session,
  4769. )
  4770. # Capture timelapse file baseline for snapshot-diff on completion
  4771. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4772. # hit this branch — without the baseline the completion-time scan
  4773. # falls into its "take baseline now" fallback, which snapshots
  4774. # AFTER the new MP4 already exists and never matches a diff
  4775. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4776. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4777. await _forget_if_printer_gone(printer_id)
  4778. return # Skip creating a new archive
  4779. # The archive was deleted after the job was queued.
  4780. if not archives_prints:
  4781. # Only the expected print brought a printer that does not
  4782. # archive this far; with it gone, nothing is archived.
  4783. return
  4784. # Otherwise archive the print anew rather than drop it, so it still
  4785. # gets its notification, usage tracking and history.
  4786. logger.warning(
  4787. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4788. expected_archive_id,
  4789. printer_id,
  4790. )
  4791. # Check if there's already a "printing" archive for this printer/file
  4792. # This prevents duplicates when backend restarts during an active print
  4793. from backend.app.models.archive import PrintArchive
  4794. existing_archive: PrintArchive | None = None
  4795. resumed_by_run = False
  4796. # Best match: this job's run, open on the printer since the print
  4797. # started. The archive row is shared by every plate of it, and its
  4798. # printer, job id and status are the latest start's, which may be
  4799. # another printer's.
  4800. if subtask_id:
  4801. from backend.app.services.print_log import open_run_on_printer
  4802. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4803. if run is not None and run.archive_id is not None:
  4804. existing_archive = await db.scalar(
  4805. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4806. )
  4807. resumed_by_run = existing_archive is not None
  4808. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4809. # across a backend restart for the same print, so this is the most
  4810. # reliable way to reattach. Only a row still printing: a cancelled one
  4811. # has been through completion (usage, history, notifications) already,
  4812. # and reopening it would count the print twice.
  4813. if subtask_id and existing_archive is None:
  4814. by_id = await db.execute(
  4815. select(PrintArchive)
  4816. .where(PrintArchive.printer_id == printer_id)
  4817. .where(PrintArchive.subtask_id == subtask_id)
  4818. .where(PrintArchive.status == "printing")
  4819. .order_by(PrintArchive.created_at.desc())
  4820. .limit(1)
  4821. )
  4822. existing_archive = by_id.scalar_one_or_none()
  4823. # Fallback match: name-based lookup. Kept as-is for prints whose
  4824. # subtask_id is missing ("0" / local / non-cloud prints).
  4825. if existing_archive is None:
  4826. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4827. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4828. # A print started from the printer's screen names its file in full,
  4829. # so the forms above double its extension. The file itself is the
  4830. # one exact match, and nothing looser is added (#3009).
  4831. if _subtask_is_the_file(subtask_name, filename):
  4832. archive_filenames.append(subtask_name)
  4833. existing = await db.execute(
  4834. select(PrintArchive)
  4835. .where(PrintArchive.printer_id == printer_id)
  4836. .where(PrintArchive.status == "printing")
  4837. .where(
  4838. or_(
  4839. PrintArchive.print_name == check_name,
  4840. PrintArchive.filename.in_(archive_filenames),
  4841. )
  4842. )
  4843. .order_by(PrintArchive.created_at.desc())
  4844. .limit(1)
  4845. )
  4846. existing_archive = existing.scalar_one_or_none()
  4847. if existing_archive:
  4848. # subtask_id match → always resume, regardless of age. Same print,
  4849. # just a backend restart.
  4850. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4851. if subtask_match:
  4852. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4853. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4854. await _open_run_for(existing_archive.id, printer_id)
  4855. _mark_owned_if_dispatched(existing_archive)
  4856. if existing_archive.energy_start_kwh is None:
  4857. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4858. if not notification_sent:
  4859. archive_data = {
  4860. "print_time_seconds": existing_archive.print_time_seconds,
  4861. "created_by_id": existing_archive.created_by_id,
  4862. }
  4863. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4864. _load_objects_from_archive(existing_archive, printer_id, logger)
  4865. if existing_archive.file_path:
  4866. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4867. return
  4868. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4869. # stale from the printer's *current* progress, not wall-clock age.
  4870. # A genuinely long print used to trip a blind 4h cutoff and have its
  4871. # live archive cancelled + duplicated on every backend restart
  4872. # (#1485). If the printer reports real progress, this name-matched
  4873. # 'printing' archive IS that ongoing print — resume it whatever its
  4874. # age. Only treat it as a stale leftover when the printer clearly
  4875. # shows a different, freshly-started print: near-0% progress on an
  4876. # archive far too old to still be at 0%. Unknown progress (printer
  4877. # not connected) never cancels — resuming is the safe default.
  4878. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4879. live_status = printer_manager.get_status(printer_id)
  4880. live_progress = getattr(live_status, "progress", None) if live_status else None
  4881. looks_stale = (
  4882. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4883. )
  4884. # Two subtask ids are two prints, however young the archive: one
  4885. # whose completion was missed must not swallow the next print of
  4886. # the same file. Except Bambuddy's own reprint, which reuses the
  4887. # row and mints a fresh id (#1807): the id it last sent says so,
  4888. # and after a restart, which forgets it, this printer's queue job
  4889. # running the archive.
  4890. if (
  4891. not looks_stale
  4892. and subtask_id
  4893. and existing_archive.subtask_id
  4894. and existing_archive.subtask_id != subtask_id
  4895. ):
  4896. _client = printer_manager.get_client(printer_id)
  4897. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4898. if _dispatched:
  4899. looks_stale = _dispatched != subtask_id
  4900. else:
  4901. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4902. queue_run = await db.scalar(
  4903. select(_PQI.id)
  4904. .where(_PQI.archive_id == existing_archive.id)
  4905. .where(_PQI.printer_id == printer_id)
  4906. .where(_PQI.status == "printing")
  4907. .limit(1)
  4908. )
  4909. looks_stale = queue_run is None
  4910. if looks_stale:
  4911. logger.warning(
  4912. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4913. " — marking cancelled and creating new archive",
  4914. existing_archive.id,
  4915. archive_age,
  4916. live_progress,
  4917. existing_archive.subtask_id,
  4918. subtask_id,
  4919. )
  4920. existing_archive.status = "cancelled"
  4921. # Canonical key, not a sentence (issue #2974). "No status update
  4922. # received" is what both stale paths actually observed; which of
  4923. # the two it was is already carried by ``status`` -- cancelled
  4924. # here, the reconciled outcome at the reconnect site -- so one
  4925. # key loses no information and gives the Statistics breakdown a
  4926. # single bucket instead of two untranslatable prose strings.
  4927. existing_archive.failure_reason = "noStatusUpdate"
  4928. await db.commit()
  4929. # Its print keys go with it; the new archive registers its own.
  4930. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4931. del _active_prints[_key]
  4932. # Fall through to create new archive (don't return)
  4933. else:
  4934. logger.info(
  4935. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4936. )
  4937. # Track this as the active print
  4938. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4939. _mark_owned_if_dispatched(existing_archive)
  4940. # Attach subtask_id retroactively so future restarts can resume.
  4941. # Compare for inequality (not "is empty") to also pick up reprint
  4942. # dispatches that mint a fresh id — see #1807 for the bogus
  4943. # "Print Stopped" the strict-empty guard caused on reconnect.
  4944. if subtask_id and existing_archive.subtask_id != subtask_id:
  4945. existing_archive.subtask_id = subtask_id
  4946. await db.commit()
  4947. await _open_run_for(existing_archive.id, printer_id)
  4948. # Also set up energy tracking if not already tracked (#941: persisted column)
  4949. if existing_archive.energy_start_kwh is None:
  4950. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4951. # Send notification with archive data (existing archive)
  4952. if not notification_sent:
  4953. archive_data = {
  4954. "print_time_seconds": existing_archive.print_time_seconds,
  4955. "created_by_id": existing_archive.created_by_id,
  4956. }
  4957. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4958. # Extract printable objects from the archived 3MF file
  4959. _load_objects_from_archive(existing_archive, printer_id, logger)
  4960. if existing_archive.file_path:
  4961. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4962. return
  4963. # Build list of possible 3MF filenames to try
  4964. possible_names = []
  4965. # Bambu printers typically store files as "Name.gcode.3mf"
  4966. # The subtask_name is usually the best source for the filename
  4967. if subtask_name:
  4968. if _subtask_is_the_file(subtask_name, filename):
  4969. # A print started from the printer's own screen reports the
  4970. # file's full name, extension included. That is the file, so
  4971. # no extension is appended to it (#3009).
  4972. possible_names.append(subtask_name)
  4973. else:
  4974. # Try common Bambu naming patterns
  4975. possible_names.append(f"{subtask_name}.gcode.3mf")
  4976. possible_names.append(f"{subtask_name}.3mf")
  4977. # Try original filename with .3mf extension
  4978. if filename:
  4979. # Extract just the filename part, not the full path
  4980. fname = filename.split("/")[-1] if "/" in filename else filename
  4981. if fname.endswith(".3mf"):
  4982. possible_names.append(fname)
  4983. elif fname.endswith(".gcode"):
  4984. base = fname.rsplit(".", 1)[0]
  4985. possible_names.append(f"{base}.gcode.3mf")
  4986. possible_names.append(f"{base}.3mf")
  4987. else:
  4988. possible_names.append(f"{fname}.gcode.3mf")
  4989. possible_names.append(f"{fname}.3mf")
  4990. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4991. space_variants = []
  4992. for name in possible_names:
  4993. if " " in name:
  4994. space_variants.append(name.replace(" ", "_"))
  4995. possible_names.extend(space_variants)
  4996. # Remove duplicates while preserving order
  4997. seen = set()
  4998. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4999. logger.info("Trying filenames: %s", possible_names)
  5000. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5001. # here means none of the expected-/existing-archive write branches ran
  5002. # (they all return earlier) — only SELECTs have executed on this path, so
  5003. # this commit persists nothing; it ends the read transaction so the
  5004. # connection returns to the pool during the download. That download tries
  5005. # up to five remote paths per candidate filename with retry/backoff and
  5006. # can run for minutes under FTP contention; holding the session across it
  5007. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5008. # work runs during the download — the new-archive writes below re-acquire
  5009. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5010. await db.commit()
  5011. # Try to find and download the 3MF file
  5012. temp_path = None
  5013. downloaded_filename = None
  5014. # Cache check: cover endpoint may have already pulled this 3MF during
  5015. # the print (frontend opens the card and shows the thumbnail) — reuse
  5016. # that file instead of re-downloading 36MB over the same FTP link that
  5017. # just served it (#972). The cache keys on a normalized filename so
  5018. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5019. for try_filename in possible_names:
  5020. if not try_filename.endswith(".3mf"):
  5021. continue
  5022. cached = get_cached_3mf(printer_id, try_filename)
  5023. if cached:
  5024. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5025. temp_path = cached
  5026. downloaded_filename = try_filename
  5027. break
  5028. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5029. # H2-series and P2S the answer is routinely no — the file stays on
  5030. # internal eMMC and port 990 only ever serves external storage — and
  5031. # then the whole sweep below (six filenames x five directories x four
  5032. # retries, then the directory walk) is ~110 connections that cannot
  5033. # succeed. Skip it and say why (#2780).
  5034. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5035. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5036. # running rather than because the file is somewhere unreachable. The
  5037. # distinction is the whole of #2957: one is permanent, the other clears
  5038. # in minutes with the file still sitting on the printer.
  5039. blocked_by_ftps_cooloff = False
  5040. # Set when a probe reached the printer and still came back without the
  5041. # file -- a timeout mid-transfer, a refused connection, anything that is
  5042. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5043. # caught by name below, so a file that genuinely is not on the card
  5044. # leaves this False and schedules nothing. Anything else means the
  5045. # transfer, not the file, is what failed, and that does not last (#3063).
  5046. ftp_transfer_failed = False
  5047. # The narrower case of the above: the directory walk *listed* a file
  5048. # for this print and could not fetch it, so the file is on the card
  5049. # under a name that matches. The only failure that rules out an
  5050. # earlier run's 3MF standing in for it (#3307).
  5051. walk_transfer_failed = False
  5052. # Paths the sweep reached and could not transfer -- a timeout, not a
  5053. # 550. The directory walk lists the same folders and would download
  5054. # the same file again: on a slow A1 that was a second 300 s on the
  5055. # printer's one FTPS slot, at print start, for a file the recovery
  5056. # retry fetches with a deadline twice as long (#3308).
  5057. sweep_failed_paths: set[str] = set()
  5058. # The print's name, for a fallback archive whose `subtask_name` the
  5059. # plate guard below had to disown. Display only, and deliberately kept
  5060. # apart from `subtask_name`: that variable is what every file lookup
  5061. # here is built from, and once a name has been shown to fetch another
  5062. # plate's 3MF it must not key `_active_prints` either, or the cover
  5063. # endpoint hands the same contradicted file to
  5064. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5065. display_name_after_plate_reject: str | None = None
  5066. # Get FTP retry settings
  5067. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5068. # ...but "the printer put it on eMMC" is where it went, not whether we
  5069. # can read it. An H2D with a card in mirrors the job to /cache and
  5070. # serves it happily, and skipping on the URL alone cost that reporter
  5071. # every archive for two days (#2856). So ask the printer instead of
  5072. # guessing: the dispatch named the exact file, which is one connection
  5073. # walking five paths rather than the sweep's ~110. Only when the probe
  5074. # comes back empty does the verdict's reason stand.
  5075. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5076. if ftps_handshake_blocked(printer.ip_address):
  5077. # Deliberately NOT recorded as a cool-off give-up. This branch
  5078. # only runs on an unreachable verdict, and that verdict is the
  5079. # honest, permanent reason the archive is empty — the probe was
  5080. # a long shot on top of it. Blaming the cool-off here would
  5081. # schedule a retry for a file sitting on internal eMMC, which is
  5082. # the sweep #2780 removed (#2957).
  5083. logger.debug(
  5084. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5085. storage.probe_filename,
  5086. printer_id,
  5087. )
  5088. else:
  5089. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5090. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5091. try:
  5092. probe_hit = await download_file_try_paths_async(
  5093. printer.ip_address,
  5094. printer.access_code,
  5095. ftp_probe_paths(storage.probe_filename),
  5096. probe_path,
  5097. socket_timeout=ftp_timeout,
  5098. printer_model=printer.model,
  5099. )
  5100. except Exception as e:
  5101. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5102. probe_hit = False
  5103. if probe_hit:
  5104. downloaded_filename = storage.probe_filename
  5105. temp_path = probe_path
  5106. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5107. # Naming the path, not just the file: a printer that keeps
  5108. # uploads around for weeks can serve a same-named copy of an
  5109. # earlier slice, and without the directory in the log that
  5110. # mismatch is invisible rather than merely rare (#1820).
  5111. logger.info(
  5112. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5113. downloaded_filename,
  5114. probe_hit,
  5115. printer_id,
  5116. storage.reason,
  5117. )
  5118. if not storage.reachable and not downloaded_filename:
  5119. # Same opening words whether or not a probe ran, because that is
  5120. # the phrase support asks people to grep for — only the tail says
  5121. # which of the two happened.
  5122. logger.info(
  5123. "Skipping the 3MF lookup for printer %s: %s — %s",
  5124. printer_id,
  5125. storage.reason,
  5126. "no copy of it on external storage either"
  5127. if storage.probe_filename
  5128. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5129. )
  5130. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5131. if not try_filename.endswith(".3mf"):
  5132. continue
  5133. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5134. # printers, so try it first — deferring it to last cost #972's reporter
  5135. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5136. # landing on the path that actually had the file.
  5137. remote_paths = [
  5138. f"/{try_filename}",
  5139. f"/cache/{try_filename}",
  5140. f"/model/{try_filename}",
  5141. f"/data/{try_filename}",
  5142. f"/data/Metadata/{try_filename}",
  5143. ]
  5144. temp_path = app_settings.archive_dir / "temp" / try_filename
  5145. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5146. for remote_path in remote_paths:
  5147. if ftps_handshake_blocked(printer.ip_address):
  5148. # The printer's FTPS service is not completing a TLS
  5149. # handshake, so it has no path we could reach — walking the
  5150. # remaining candidates only re-runs the same failure
  5151. # (#2780). Fall through to the no-3MF archive now.
  5152. #
  5153. # Remember *why*, though. This is the one give-up that is
  5154. # temporary: the cool-off clears in minutes and the file was
  5155. # on the printer the whole time. The fallback archive is
  5156. # stamped with it so a retry can be scheduled, and so the
  5157. # Archives banner stops blaming storage (#2957).
  5158. blocked_by_ftps_cooloff = True
  5159. logger.warning(
  5160. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5161. printer_id,
  5162. )
  5163. break
  5164. logger.debug("Trying FTP download: %s", remote_path)
  5165. try:
  5166. if ftp_retry_enabled:
  5167. downloaded = await with_ftp_retry(
  5168. download_file_async,
  5169. printer.ip_address,
  5170. printer.access_code,
  5171. remote_path,
  5172. temp_path,
  5173. timeout=ftp_timeout,
  5174. socket_timeout=ftp_timeout,
  5175. printer_model=printer.model,
  5176. max_retries=ftp_retry_count,
  5177. retry_delay=ftp_retry_delay,
  5178. operation_name=f"Download 3MF from {remote_path}",
  5179. cooloff_ip=printer.ip_address,
  5180. non_retry_exceptions=(FileNotOnPrinterError,),
  5181. )
  5182. else:
  5183. downloaded = await download_file_async(
  5184. printer.ip_address,
  5185. printer.access_code,
  5186. remote_path,
  5187. temp_path,
  5188. timeout=ftp_timeout,
  5189. socket_timeout=ftp_timeout,
  5190. printer_model=printer.model,
  5191. )
  5192. if downloaded:
  5193. downloaded_filename = try_filename
  5194. logger.info("Downloaded: %s", remote_path)
  5195. # Populate shared cache so the cover endpoint (if it
  5196. # runs next) doesn't refetch the same 36MB over FTP.
  5197. cache_3mf_download(printer_id, try_filename, temp_path)
  5198. break
  5199. # with_ftp_retry returns None once it has spent its budget,
  5200. # and download_file_async returns False on a timeout, so an
  5201. # exhausted transfer arrives here rather than as an
  5202. # exception (#3063).
  5203. ftp_transfer_failed = True
  5204. sweep_failed_paths.add(remote_path)
  5205. except FileNotOnPrinterError:
  5206. # 550 — file isn't at this path. Advance to next candidate
  5207. # without burning the retry budget.
  5208. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5209. except Exception as e:
  5210. ftp_transfer_failed = True
  5211. sweep_failed_paths.add(remote_path)
  5212. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5213. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5214. break
  5215. # If still not found, try listing directories to find matching file
  5216. # Different printer models use different directory structures. Skipped
  5217. # when the printer's FTPS handshake is failing — the directory walk is
  5218. # five more connections that cannot get further than the download did.
  5219. if (
  5220. not downloaded_filename
  5221. and storage.reachable
  5222. and (filename or subtask_name)
  5223. and not ftps_handshake_blocked(printer.ip_address)
  5224. ):
  5225. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5226. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5227. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5228. # Every folder is listed before one file is picked, so a file named
  5229. # for the print in a later folder wins over one that merely
  5230. # contains the name in an earlier folder.
  5231. listed_paths: list[str] = []
  5232. for search_dir in search_dirs:
  5233. try:
  5234. dir_files = await list_files_async(
  5235. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5236. )
  5237. except Exception as e:
  5238. logger.debug("Failed to list %s: %s", search_dir, e)
  5239. continue
  5240. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5241. if threemf_files:
  5242. logger.info(
  5243. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5244. )
  5245. listed_paths += [
  5246. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5247. ]
  5248. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5249. if remote_full_path in sweep_failed_paths:
  5250. # Listed for this print, and its transfer already failed:
  5251. # the same as a failed walk download, without spending a
  5252. # second deadline on it. Skipping it cannot hand the walk a
  5253. # look-alike: while a file of the print's own name is
  5254. # listed, files that merely contain the name are not.
  5255. logger.info(
  5256. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5257. remote_full_path,
  5258. )
  5259. walk_transfer_failed = True
  5260. continue
  5261. fname = posixpath.basename(remote_full_path)
  5262. logger.info("Found matching file: %s", remote_full_path)
  5263. temp_path = app_settings.archive_dir / "temp" / fname
  5264. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5265. try:
  5266. if ftp_retry_enabled:
  5267. downloaded = await with_ftp_retry(
  5268. download_file_async,
  5269. printer.ip_address,
  5270. printer.access_code,
  5271. remote_full_path,
  5272. temp_path,
  5273. timeout=ftp_timeout,
  5274. socket_timeout=ftp_timeout,
  5275. printer_model=printer.model,
  5276. max_retries=ftp_retry_count,
  5277. retry_delay=ftp_retry_delay,
  5278. operation_name=f"Download 3MF from {remote_full_path}",
  5279. cooloff_ip=printer.ip_address,
  5280. )
  5281. else:
  5282. downloaded = await download_file_async(
  5283. printer.ip_address,
  5284. printer.access_code,
  5285. remote_full_path,
  5286. temp_path,
  5287. timeout=ftp_timeout,
  5288. socket_timeout=ftp_timeout,
  5289. printer_model=printer.model,
  5290. )
  5291. except Exception as e:
  5292. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5293. continue
  5294. if downloaded:
  5295. downloaded_filename = fname
  5296. logger.info("Found and downloaded: %s", remote_full_path)
  5297. cache_3mf_download(printer_id, fname, temp_path)
  5298. break
  5299. # The listing named the file, so it is on the card;
  5300. # only the transfer failed (#3063).
  5301. ftp_transfer_failed = True
  5302. walk_transfer_failed = True
  5303. # A "Print again" on the printer's screen names no file Bambuddy can
  5304. # find: only its history copy under a generic name, and the 3MF's
  5305. # internal title (#3307). When an earlier run of the same job was
  5306. # archived, its 3MF is the one being printed again. Not when the
  5307. # directory walk listed a file for this print and only its transfer
  5308. # failed: that file is on the card, and the retry fetches it. A
  5309. # cool-off or a failed sweep path is no such evidence -- the retry
  5310. # tries the same names, which this print's file never had.
  5311. reused_3mf_from: int | None = None
  5312. if not downloaded_filename and not walk_transfer_failed:
  5313. reported_layers = raw_mqtt.get("total_layer_num")
  5314. earlier = await _archived_3mf_for_repeat(
  5315. db,
  5316. printer_id,
  5317. subtask_name,
  5318. filename,
  5319. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5320. )
  5321. if earlier is not None:
  5322. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5323. # Per printer: two printers reprinting the same job at once
  5324. # must not write one temp file (archive_print names the
  5325. # archive after original_filename, not this path).
  5326. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5327. try:
  5328. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5329. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5330. except OSError as e:
  5331. # A copy that fails leaves the print the fallback archive
  5332. # it would have had, not no archive at all.
  5333. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5334. else:
  5335. temp_path = reuse_path
  5336. downloaded_filename = reuse_name
  5337. reused_3mf_from = earlier.id
  5338. cache_3mf_download(printer_id, reuse_name, temp_path)
  5339. logger.info(
  5340. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5341. printer_id,
  5342. subtask_name,
  5343. filename,
  5344. earlier.id,
  5345. )
  5346. # Validate the downloaded 3MF actually matches the plate that's running
  5347. # (#1204): subtask_name lags across consecutive plates of the same model,
  5348. # so the first FTP candidate (built from subtask_name) can land on the
  5349. # previous plate's still-resident upload. Cross-check the slice_info
  5350. # plate index against the plate parsed from gcode_file (always fresh —
  5351. # it's the field whose change triggered this callback).
  5352. if downloaded_filename and temp_path:
  5353. expected_plate = parse_plate_id(filename)
  5354. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5355. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5356. logger.warning(
  5357. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5358. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5359. downloaded_filename,
  5360. actual_plate,
  5361. expected_plate,
  5362. subtask_name,
  5363. )
  5364. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5365. retry_succeeded = False
  5366. if corrected_subtask and corrected_subtask != subtask_name:
  5367. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5368. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5369. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5370. for remote_path in (
  5371. f"/{try_filename}",
  5372. f"/cache/{try_filename}",
  5373. f"/model/{try_filename}",
  5374. f"/data/{try_filename}",
  5375. f"/data/Metadata/{try_filename}",
  5376. ):
  5377. try:
  5378. if ftp_retry_enabled:
  5379. downloaded = await with_ftp_retry(
  5380. download_file_async,
  5381. printer.ip_address,
  5382. printer.access_code,
  5383. remote_path,
  5384. retry_temp_path,
  5385. timeout=ftp_timeout,
  5386. socket_timeout=ftp_timeout,
  5387. printer_model=printer.model,
  5388. max_retries=ftp_retry_count,
  5389. retry_delay=ftp_retry_delay,
  5390. operation_name=f"Re-download 3MF from {remote_path}",
  5391. cooloff_ip=printer.ip_address,
  5392. non_retry_exceptions=(FileNotOnPrinterError,),
  5393. )
  5394. else:
  5395. downloaded = await download_file_async(
  5396. printer.ip_address,
  5397. printer.access_code,
  5398. remote_path,
  5399. retry_temp_path,
  5400. timeout=ftp_timeout,
  5401. socket_timeout=ftp_timeout,
  5402. printer_model=printer.model,
  5403. )
  5404. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5405. logger.info(
  5406. "[CALLBACK] Re-download succeeded with corrected name %s "
  5407. "(plate %s) — replacing wrong file",
  5408. try_filename,
  5409. expected_plate,
  5410. )
  5411. try:
  5412. temp_path.unlink(missing_ok=True)
  5413. except OSError:
  5414. pass
  5415. temp_path = retry_temp_path
  5416. downloaded_filename = try_filename
  5417. subtask_name = corrected_subtask
  5418. cache_3mf_download(printer_id, try_filename, temp_path)
  5419. retry_succeeded = True
  5420. break
  5421. elif downloaded:
  5422. # Wrong plate again — discard and keep trying
  5423. try:
  5424. retry_temp_path.unlink(missing_ok=True)
  5425. except OSError:
  5426. pass
  5427. except FileNotOnPrinterError:
  5428. continue
  5429. except Exception as e:
  5430. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5431. if retry_succeeded:
  5432. break
  5433. # If the retry didn't find a matching file, drop the wrong 3MF
  5434. # so the no-3MF fallback below creates an archive whose name
  5435. # at least reflects the right plate.
  5436. if not retry_succeeded:
  5437. logger.warning(
  5438. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5439. expected_plate,
  5440. )
  5441. try:
  5442. temp_path.unlink(missing_ok=True)
  5443. except OSError:
  5444. pass
  5445. temp_path = None
  5446. downloaded_filename = None
  5447. # Whatever the sweep's transport did earlier, it is not why
  5448. # this archive ends up empty: a 3MF downloaded fine, it was
  5449. # just the wrong plate. Retrying would re-fetch that same
  5450. # contradicted file under the same stale names and hand it
  5451. # to _recover_fallback_archive, which checks that a
  5452. # candidate is a readable 3MF but not which plate it is --
  5453. # so the row would be filled in with another plate's
  5454. # filament and cost, the exact swap #2957 removed (#3063).
  5455. ftp_transfer_failed = False
  5456. # Disown the name for *lookups*: it has just been shown to
  5457. # fetch another plate's 3MF, and it keys `_active_prints`
  5458. # below, where the cover endpoint's own download of that
  5459. # same name would find this archive and fill it in with the
  5460. # file we are discarding here.
  5461. #
  5462. # Keep it for the *title*, which is a separate question.
  5463. # ``swap_plate_suffix`` returns None both for a name that
  5464. # carries no "- Plate N" / "_plate_N" suffix and for no
  5465. # name at all, and those are not the same situation: a name
  5466. # without a suffix holds no stale plate number to be wrong
  5467. # about. Blanking both uses at once dropped the project
  5468. # name too, and the row fell through to the gcode_file path
  5469. # titled "plate_1" though the real name was in hand.
  5470. # #1204's own premise is consecutive plates *of the same
  5471. # model*, so the project part is right either way (#3126).
  5472. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5473. subtask_name = corrected_subtask or ""
  5474. # Deleted while the 3MF was being fetched (that can take minutes): no
  5475. # archive, timelapse or tracking for a printer that will never report
  5476. # the print's end. forget_printer again: the download registered its
  5477. # 3MF cache entry after the delete cleared the id. (A delete committing
  5478. # while the archive is written is caught after its commit.)
  5479. if await _printer_gone(db, printer_id):
  5480. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5481. await forget_printer(printer_id)
  5482. return
  5483. if not downloaded_filename or not temp_path:
  5484. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5485. # Create a fallback archive without 3MF data so the print is still tracked
  5486. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5487. try:
  5488. from backend.app.models.archive import PrintArchive
  5489. # Why the card is empty. The two temporary causes outrank the
  5490. # storage verdict because they say the sweep never got a fair
  5491. # answer: a cool-off skipped it at the transport, and a failed
  5492. # transfer reached the printer but never finished. Either way
  5493. # the file is still on the card, so reporting where the printer
  5494. # files its jobs would describe a setting that is not the
  5495. # problem (#2957, #3063).
  5496. if blocked_by_ftps_cooloff:
  5497. no_3mf_reason = REASON_FTPS_COOLOFF
  5498. elif storage.reachable and ftp_transfer_failed:
  5499. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5500. else:
  5501. no_3mf_reason = storage.reason
  5502. # Derive print name from subtask_name or filename. The
  5503. # plate guard's disowned name comes second: it is a real name
  5504. # for a real print, and only the gcode_file path is left
  5505. # otherwise -- which titles the row "plate_1" (#3126).
  5506. print_name = subtask_name or display_name_after_plate_reject or filename
  5507. if print_name:
  5508. # Clean up the name (remove extensions, path parts)
  5509. print_name = print_name.split("/")[-1]
  5510. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5511. else:
  5512. print_name = "Unknown Print"
  5513. # Recover estimated print time from MQTT (best-effort for notifications)
  5514. fallback_print_time = None
  5515. mqtt_remaining = data.get("remaining_time")
  5516. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5517. fallback_print_time = int(mqtt_remaining)
  5518. if fallback_print_time is None:
  5519. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5520. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5521. fallback_print_time = int(mc_remaining * 60)
  5522. # Best-effort filament metadata from MQTT — see
  5523. # _extract_filament_data_from_mqtt. Without this the fallback
  5524. # archive's filament fields stayed NULL even though the AMS
  5525. # state at print start was sitting right there in `data`.
  5526. # The slicer's ams_mapping (when present) narrows the result
  5527. # to slots actually used by the print (#1533).
  5528. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5529. data, _get_start_ams_mapping(data, printer_id, None)
  5530. )
  5531. # Create minimal archive entry
  5532. fallback_archive = PrintArchive(
  5533. printer_id=printer_id,
  5534. filename=filename or f"{print_name}.3mf",
  5535. file_path="", # Empty - no 3MF file available
  5536. file_size=0,
  5537. print_name=print_name,
  5538. print_time_seconds=fallback_print_time,
  5539. status="printing",
  5540. started_at=detected_at,
  5541. subtask_id=subtask_id,
  5542. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5543. filament_type=mqtt_filament_meta.get("filament_type"),
  5544. filament_color=mqtt_filament_meta.get("filament_color"),
  5545. extra_data={
  5546. "no_3mf_available": True,
  5547. # Why the card is empty, when we know -- see above. The
  5548. # banner reads this to stop telling H2/P2 owners to
  5549. # switch on a setting that is already on and would not
  5550. # have helped (#2780).
  5551. "no_3mf_reason": no_3mf_reason,
  5552. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5553. "_print_data": data,
  5554. },
  5555. )
  5556. db.add(fallback_archive)
  5557. try:
  5558. await db.commit()
  5559. except IntegrityError:
  5560. # Not "Failed to create fallback archive" below, and no
  5561. # start notification for a printer that is gone.
  5562. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5563. return
  5564. raise
  5565. await db.refresh(fallback_archive)
  5566. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5567. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5568. return
  5569. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5570. # Track as active print
  5571. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5572. await _open_run_for(fallback_archive.id, printer_id)
  5573. # Record starting energy if smart plug available (#941: persisted column)
  5574. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5575. # Send WebSocket notification
  5576. await ws_manager.send_archive_created(
  5577. {
  5578. "id": fallback_archive.id,
  5579. "printer_id": fallback_archive.printer_id,
  5580. "filename": fallback_archive.filename,
  5581. "print_name": fallback_archive.print_name,
  5582. "status": fallback_archive.status,
  5583. }
  5584. )
  5585. # MQTT relay - publish archive created
  5586. try:
  5587. await mqtt_relay.on_archive_created(
  5588. archive_id=fallback_archive.id,
  5589. print_name=fallback_archive.print_name,
  5590. printer_name=printer.name,
  5591. status=fallback_archive.status,
  5592. )
  5593. except Exception:
  5594. pass # Don't fail if MQTT fails
  5595. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5596. try:
  5597. await _store_spoolman_print_data(
  5598. printer_id,
  5599. fallback_archive.id,
  5600. fallback_archive.file_path,
  5601. db,
  5602. printer_manager,
  5603. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5604. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5605. )
  5606. except Exception as e:
  5607. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5608. # Both temporary give-ups are worth coming back for, and for
  5609. # the same reason: the file is on the printer and the last look
  5610. # failed at the transport rather than finding nothing. One waits
  5611. # out the handshake block (#2957), the other waits for the
  5612. # printer to stop being busy (#3063). Deliberately not scheduled
  5613. # for a storage verdict: a file on internal eMMC will not appear
  5614. # at any FTPS path however long we wait, and retrying it is
  5615. # exactly the sweep #2780 removed.
  5616. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5617. # `possible_names`, not the raw MQTT strings: it is the exact
  5618. # list this flow just tried, already stripped of any path
  5619. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5620. # some firmware) and deduped.
  5621. _schedule_fallback_3mf_retry(
  5622. printer_id=printer_id,
  5623. archive_id=fallback_archive.id,
  5624. filenames=list(possible_names),
  5625. reason=no_3mf_reason,
  5626. )
  5627. # Send notification without archive data (file not found)
  5628. if not notification_sent:
  5629. await _send_print_start_notification(printer_id, data, logger=logger)
  5630. # The same baseline the other two on_print_start branches take
  5631. # (#2704), and last for the same reason they are: it lists the
  5632. # printer's timelapse directory, so a slow card must not delay
  5633. # the _active_prints registration, the energy reading, the
  5634. # archive-created event or the start notification above it.
  5635. #
  5636. # This branch never took one, so every no-3MF archive reached
  5637. # completion with no baseline in memory and none on the row, and
  5638. # the completion scan fell into its "snapshot now" fallback --
  5639. # which runs after the printer has written the video, so the new
  5640. # file landed inside the baseline and no diff ever matched
  5641. # (#2957 follow-up).
  5642. #
  5643. # Skipped when the FTPS cool-off is what produced this fallback:
  5644. # the listing needs the same connection that just failed, so it
  5645. # could only record that the card was unreadable. The scan
  5646. # handles that case by refusing to choose between candidates.
  5647. if not blocked_by_ftps_cooloff:
  5648. await _capture_timelapse_baseline_at_start(
  5649. printer, printer_id, logger, archive_id=fallback_archive.id
  5650. )
  5651. await _forget_if_printer_gone(printer_id)
  5652. return
  5653. except Exception as e:
  5654. logger.error("Failed to create fallback archive: %s", e)
  5655. # Send notification without archive data (file not found)
  5656. if not notification_sent:
  5657. await _send_print_start_notification(printer_id, data, logger=logger)
  5658. return
  5659. try:
  5660. # Archive the file with status "printing"
  5661. service = ArchiveService(db)
  5662. try:
  5663. archive = await service.archive_print(
  5664. printer_id=printer_id,
  5665. source_file=temp_path,
  5666. print_data={
  5667. **data,
  5668. "status": "printing",
  5669. # Where the 3MF came from when the printer had none to
  5670. # give (#3307), for whoever reads this archive later.
  5671. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5672. },
  5673. subtask_id=subtask_id,
  5674. started_at=detected_at,
  5675. # The reused copy's temp name carries the printer id; a
  5676. # download's is the file's own name, as before.
  5677. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5678. )
  5679. except IntegrityError:
  5680. # archive_print removed the folder it had copied the 3MF into.
  5681. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5682. return
  5683. raise
  5684. if archive:
  5685. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5686. # Set on the row rather than passed to archive_print, which also
  5687. # serves the queue dispatcher — there the queue item decides.
  5688. # Guarded because this branch has no ``except``: an unhandled
  5689. # write error would take the _active_prints registration, the
  5690. # start notification, the energy reading and the timelapse
  5691. # baseline below it with it, and a missing prompt is by far the
  5692. # cheaper failure.
  5693. archive_id = archive.id
  5694. try:
  5695. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5696. archive.confirm_requested = True
  5697. await db.commit()
  5698. except Exception as e:
  5699. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5700. # The rollback expires every loaded object, and on an async
  5701. # session reading one afterwards raises instead of
  5702. # reloading, so the two this branch goes on to use are
  5703. # fetched again. The archive itself was committed by
  5704. # archive_print; only the flag is lost.
  5705. try:
  5706. await db.rollback()
  5707. archive = await db.get(PrintArchive, archive_id)
  5708. printer = await db.get(Printer, printer_id)
  5709. except Exception as reload_error:
  5710. logger.warning(
  5711. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5712. )
  5713. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5714. return
  5715. # Track this active print (use both original filename and downloaded filename)
  5716. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5717. await _open_run_for(archive_id, printer_id)
  5718. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5719. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5720. # Record starting energy from smart plug if available (#941: persisted column)
  5721. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5722. await ws_manager.send_archive_created(
  5723. {
  5724. "id": archive.id,
  5725. "printer_id": archive.printer_id,
  5726. "filename": archive.filename,
  5727. "print_name": archive.print_name,
  5728. "status": archive.status,
  5729. }
  5730. )
  5731. # MQTT relay - publish archive created
  5732. try:
  5733. await mqtt_relay.on_archive_created(
  5734. archive_id=archive.id,
  5735. print_name=archive.print_name,
  5736. printer_name=printer.name,
  5737. status=archive.status,
  5738. )
  5739. except Exception:
  5740. pass # Don't fail if MQTT fails
  5741. # Send notification with archive data (new archive created)
  5742. if not notification_sent:
  5743. archive_data = {
  5744. "print_time_seconds": archive.print_time_seconds,
  5745. "created_by_id": archive.created_by_id,
  5746. }
  5747. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5748. # Extract printable objects for skip object functionality
  5749. try:
  5750. from backend.app.services.archive import extract_printable_objects_from_3mf
  5751. client = printer_manager.get_client(printer_id)
  5752. if client:
  5753. with open(temp_path, "rb") as f:
  5754. threemf_data = f.read()
  5755. # Extract with positions for UI overlay, scoped to the
  5756. # plate that is printing — an all-plates 3MF carries
  5757. # every plate's objects (#2522).
  5758. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5759. threemf_data,
  5760. plate_number=resolve_plate_id(client.state),
  5761. include_positions=True,
  5762. )
  5763. if printable_objects:
  5764. # Store objects in printer state
  5765. client.state.printable_objects = printable_objects
  5766. client.state.printable_objects_bbox_all = bbox_all
  5767. client.state.skipped_objects = [] # Reset skipped objects for new print
  5768. logger.info(
  5769. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5770. )
  5771. except Exception as e:
  5772. logger.debug("Failed to extract printable objects: %s", e)
  5773. # From the archived copy: the downloaded one may be removed
  5774. # below while the pauses are still being read.
  5775. if archive is not None and archive.file_path:
  5776. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5777. # Store Spoolman tracking data for per-filament usage reporting
  5778. try:
  5779. await _store_spoolman_print_data(
  5780. printer_id,
  5781. archive.id,
  5782. archive.file_path,
  5783. db,
  5784. printer_manager,
  5785. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5786. plate_id=_get_start_plate_id(printer_id, archive_id),
  5787. )
  5788. except Exception as e:
  5789. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5790. # Price the print from its spools now rather than only at completion (#3261)
  5791. _schedule_archive_cost_estimate(
  5792. printer_id,
  5793. archive.id,
  5794. printer_manager,
  5795. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5796. plate_id=_get_start_plate_id(printer_id, archive_id),
  5797. session_factory=async_session,
  5798. )
  5799. # Capture timelapse file baseline for snapshot-diff on completion
  5800. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5801. await _forget_if_printer_gone(printer_id)
  5802. finally:
  5803. # Keep temp_path around until print completes so the cover endpoint
  5804. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5805. # the file. If the cache entry was evicted early (file vanished),
  5806. # clean up any stragglers here to avoid leaking disk on retries.
  5807. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5808. if temp_path and temp_path.exists() and cached_now != temp_path:
  5809. temp_path.unlink()
  5810. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5811. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5812. # A baseline that could not be read at print start is read again on this
  5813. # schedule while the print runs (#3412). The printer writes the video only once
  5814. # the print has ended, so a reading taken mid-print is as good as one taken at
  5815. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5816. # which is what usually makes the card unreadable, so the first reading after
  5817. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5818. # no connection is opened. The cap bounds a print that never reports an end.
  5819. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5820. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5821. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5822. # tests can shrink them without waiting out real delays.
  5823. #
  5824. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5825. # looking. Across 247 support bundles the attempt that found the video was #1
  5826. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5827. # decaying one, which is the signature of a budget that expires while files are
  5828. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5829. # prints make big videos and the printer writes them after the print ends, so
  5830. # the poll now runs for minutes and costs one FTP LIST per round.
  5831. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5832. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5833. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5834. def _timelapse_scan_max_attempts() -> int:
  5835. """Round cap for the poll, derived from the wall-clock budget.
  5836. The deadline alone is not a sufficient bound: it assumes each round really
  5837. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5838. and an FTP list that fails immediately would otherwise spin against the
  5839. printer at full speed for the whole window. Whichever bound is reached
  5840. first ends the poll.
  5841. """
  5842. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5843. # A zero interval makes the wall-clock budget meaningless; fall back to
  5844. # the round count the production interval would have given.
  5845. return 32
  5846. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5847. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5848. """Video filenames already attached to some other archive of this printer.
  5849. Used to disambiguate when more than one file is new since the baseline —
  5850. which happens when a previous print's video landed after this print's
  5851. baseline was taken. Ordering the candidates would be the obvious fix and is
  5852. the wrong one: it can only be done on mtime or on the filename timestamp,
  5853. both of which come from the printer's own clock, and a LAN-only printer
  5854. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5855. ``attach_timelapse`` saves the video into the archive directory under the
  5856. printer's original filename, and the later MP4 conversion keeps the stem,
  5857. so the stem of ``timelapse_path`` recovers what was claimed.
  5858. """
  5859. from backend.app.models.archive import PrintArchive
  5860. rows = await db.execute(
  5861. select(PrintArchive.timelapse_path).where(
  5862. PrintArchive.printer_id == printer_id,
  5863. PrintArchive.id != exclude_archive_id,
  5864. PrintArchive.timelapse_path.is_not(None),
  5865. )
  5866. )
  5867. return {Path(p).stem for p in rows.scalars().all() if p}
  5868. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5869. """The video names on *printer*'s card, and whether the card was read.
  5870. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5871. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5872. listing timed out, is indistinguishable from one holding no videos.
  5873. Everywhere that only wants to know "is there a video yet" the difference
  5874. does not matter -- both mean "not yet, retry".
  5875. It matters where an empty listing is recorded as a *baseline*. Recording
  5876. "the card held nothing" for a card that was never read means every video on
  5877. it counts as new, and the completion scan then attaches a stale video to
  5878. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5879. empty listing is asked again here in a way that tells the two apart: the
  5880. card counts as read only when every directory walked answered, with a
  5881. listing or with "no such directory". One that failed may be the one
  5882. holding the videos.
  5883. """
  5884. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  5885. files, _ = await _list_timelapse_videos(printer)
  5886. if files:
  5887. return {f.get("name", "") for f in files}, True
  5888. ip_address = getattr(printer, "ip_address", None)
  5889. printer_id = getattr(printer, "id", None)
  5890. if not ip_address:
  5891. return set(), True
  5892. # No card in the slot: nothing to read, and nothing a video could land on.
  5893. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5894. return set(), True
  5895. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5896. if ftps_handshake_blocked(ip_address):
  5897. # Below any path: every remaining one would fail the same way.
  5898. return set(), False
  5899. listing = await list_files_result_async(
  5900. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5901. )
  5902. if not (listing.available or listing.missing):
  5903. return set(), False
  5904. videos = [
  5905. f
  5906. for f in listing.files
  5907. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5908. ]
  5909. if videos:
  5910. return {f.get("name", "") for f in videos}, True
  5911. return set(), True
  5912. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5913. """List video files from printer's timelapse directory.
  5914. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5915. Returns (video_files, found_path) where video_files is a list of file dicts
  5916. and found_path is the directory where they were found, or ([], None).
  5917. An empty return does not distinguish "no videos" from "could not read the
  5918. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  5919. callers use instead.
  5920. """
  5921. from backend.app.services.bambu_ftp import list_files_async
  5922. logger = logging.getLogger(__name__)
  5923. # No card in the slot means no /timelapse to walk — four connections that
  5924. # can only fail, on a path whose failures are swallowed and so would go on
  5925. # costing time silently forever (#2780).
  5926. #
  5927. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5928. # inside the loop's own try/except, so a caller that passed something
  5929. # unexpected used to get an empty listing rather than an exception. Keep
  5930. # that, instead of making this gate the first thing that can raise here.
  5931. printer_id = getattr(printer, "id", None)
  5932. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5933. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5934. return [], None
  5935. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5936. try:
  5937. found_files = await list_files_async(
  5938. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5939. )
  5940. if found_files:
  5941. video_files = [
  5942. f
  5943. for f in found_files
  5944. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5945. ]
  5946. if video_files:
  5947. return video_files, timelapse_path
  5948. except Exception as e:
  5949. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5950. continue
  5951. return [], None
  5952. async def _capture_timelapse_baseline_at_start(
  5953. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5954. ) -> None:
  5955. """Snapshot the printer's timelapse directory at print start so the
  5956. completion-time scan can pick the new file by set-difference.
  5957. Must be called from every on_print_start path that proceeds to a real
  5958. print — both the new-archive branch and the expected-archive branch (which
  5959. queue / VP-dispatched prints take). Without a baseline,
  5960. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5961. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5962. so the new file ends up in the "baseline" set and no diff ever matches.
  5963. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5964. unreliable — the snapshot-diff approach sidesteps that entirely.
  5965. When ``archive_id`` is known the baseline is also written to the archive
  5966. row, so it survives a restart and the manual "Scan for Timelapse" button
  5967. can run the same diff instead of falling back to clock-based matching
  5968. (#2704). Only baselines taken at print start are persisted — one taken at
  5969. completion already contains the new video and would poison a later scan.
  5970. """
  5971. names: set[str] | None = None
  5972. unread = False
  5973. _timelapse_baselines_unread.discard(printer_id)
  5974. try:
  5975. names, read = await _read_timelapse_baseline(printer)
  5976. unread = not read
  5977. _timelapse_baselines[printer_id] = names
  5978. if unread:
  5979. # Recorded anyway, deliberately, and marked. An empty baseline taken
  5980. # off a card we could not read is not evidence, but it is still the
  5981. # right *default*: Bambuddy deletes each video from the printer once
  5982. # it is attached, so the usual card holds exactly one video at
  5983. # completion and an empty baseline resolves it. Persisting NULL
  5984. # instead would send completion to take its own snapshot, by which
  5985. # point this print's video is on the card and would be swallowed by
  5986. # it. The mark keeps the scan from choosing between several videos
  5987. # (#3412), and the card is read again while the print runs.
  5988. _timelapse_baselines_unread.add(printer_id)
  5989. logger.warning(
  5990. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  5991. "treating it as empty for now and reading it again during the print",
  5992. printer_id,
  5993. )
  5994. logger.info(
  5995. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5996. len(names),
  5997. printer_id,
  5998. )
  5999. except Exception as e:
  6000. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6001. run_started_at: datetime | None = None
  6002. if archive_id is not None:
  6003. try:
  6004. async with async_session() as db:
  6005. from backend.app.models.archive import PrintArchive
  6006. archive = await db.get(PrintArchive, archive_id)
  6007. if archive is not None:
  6008. # Written even when the listing failed, and then as NULL. A
  6009. # reprint reuses the archive row, so leaving the previous
  6010. # run's baseline in place would have the scan diff this print
  6011. # against the state of the printer before the *last* one —
  6012. # and a stale baseline reads as authoritative, where NULL
  6013. # correctly falls back to a fresh snapshot.
  6014. archive.timelapse_baseline = sorted(names) if names is not None else None
  6015. archive.timelapse_baseline_unread = unread
  6016. run_started_at = archive.started_at
  6017. await db.commit()
  6018. except Exception as e:
  6019. # In-memory baseline still covers the normal completion path.
  6020. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6021. if unread and names is not None:
  6022. spawn_background_task(
  6023. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at),
  6024. name=f"reread-timelapse-baseline-{printer_id}",
  6025. )
  6026. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6027. # levelling) counts as much as the print itself.
  6028. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6029. def _schedule_timelapse_scan(archive_id: int, printer_id: int, *, plate_id: int | None) -> None:
  6030. """Start the completion scan with the print-start baseline: the names, and
  6031. whether they were taken off a card that could not be read. Taking them
  6032. ends any re-read still running for it."""
  6033. unread = printer_id in _timelapse_baselines_unread
  6034. _timelapse_baselines_unread.discard(printer_id)
  6035. baseline = _timelapse_baselines.pop(printer_id, None)
  6036. spawn_background_task(
  6037. _mark_run_finishing(
  6038. archive_id,
  6039. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=plate_id, baseline_unread=unread),
  6040. ),
  6041. name=f"scan-timelapse-{archive_id}",
  6042. )
  6043. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6044. """Whether to read an unread baseline again now: True to read, None to
  6045. skip this round, False once it is over -- the print it was taken for is
  6046. no longer the one on the printer, has stopped printing, or the baseline
  6047. has been read.
  6048. ``names`` is the very set object recorded at print start: completion pops
  6049. it and the next print records a new one, so identity marks the run. A
  6050. printer that is momentarily disconnected says nothing about its print, so
  6051. that only skips the round.
  6052. """
  6053. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6054. return False
  6055. state = printer_manager.get_status(printer_id)
  6056. if state is None or not state.connected:
  6057. return None
  6058. return state.state in _BASELINE_REREAD_STATES
  6059. async def _reread_unread_timelapse_baseline(
  6060. printer_id: int, names: set[str], archive_id: int | None, run_started_at: datetime | None
  6061. ) -> None:
  6062. """Read again a print-start baseline the card could not give (#3412).
  6063. The printer writes the video only once the print has ended, so the card
  6064. read at any point during the print holds exactly what it held at the
  6065. start. Each round stops once the print is no longer the one the baseline
  6066. was taken for or has stopped printing, and checks that again after the
  6067. listing returns, before anything is recorded.
  6068. """
  6069. from backend.app.models.archive import PrintArchive
  6070. from backend.app.models.printer import Printer
  6071. logger = logging.getLogger(__name__)
  6072. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6073. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6074. now = _unread_baseline_round(printer_id, names)
  6075. if now is False:
  6076. return
  6077. if now is None:
  6078. continue
  6079. try:
  6080. async with async_session() as db:
  6081. printer = await db.get(Printer, printer_id)
  6082. if printer is None:
  6083. return
  6084. fresh, read = await _read_timelapse_baseline(printer)
  6085. except Exception as e:
  6086. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6087. continue
  6088. if not read:
  6089. continue
  6090. now = _unread_baseline_round(printer_id, names)
  6091. if now is False:
  6092. return
  6093. if now is None:
  6094. # The printer dropped off while the listing was out, so nothing
  6095. # says it did not end meanwhile: keep the reading for a round that
  6096. # can vouch for it.
  6097. continue
  6098. names.update(fresh)
  6099. _timelapse_baselines_unread.discard(printer_id)
  6100. logger.info(
  6101. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6102. printer_id,
  6103. len(fresh),
  6104. )
  6105. if archive_id is None:
  6106. return
  6107. try:
  6108. async with async_session() as db:
  6109. archive = await db.get(PrintArchive, archive_id)
  6110. # Only the run it was taken for: by now the row can belong to a
  6111. # reprint, whose baseline is its own.
  6112. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6113. archive.timelapse_baseline = sorted(names)
  6114. archive.timelapse_baseline_unread = False
  6115. await db.commit()
  6116. except Exception as e:
  6117. # The in-memory baseline is read now, which covers completion
  6118. # unless Bambuddy restarts first.
  6119. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6120. return
  6121. async def _scan_for_timelapse_with_retries(
  6122. archive_id: int,
  6123. baseline_names: set[str] | None = None,
  6124. *,
  6125. plate_id: int | None = None,
  6126. baseline_unread: bool = False,
  6127. ):
  6128. """Poll the printer for this print's timelapse and attach it.
  6129. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6130. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6131. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6132. (#2704). Comparing the current listing against the set of filenames that
  6133. existed when the print started needs no clock at all, because the printer
  6134. writes the video only once the print has ended.
  6135. Baseline precedence: the caller's in-memory set, then the one persisted on
  6136. the archive at print start, then a snapshot taken now. The last of those is
  6137. a poor substitute — by completion the new video may already be on the card,
  6138. in which case it lands in the "baseline" and no diff can ever match — but it
  6139. is all that is available for a print that began before Bambuddy started.
  6140. On success the video is deleted from the printer, which keeps ``/timelapse``
  6141. down to the unclaimed files and makes the next diff unambiguous.
  6142. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6143. could not be read; a stored one carries the same mark on the archive.
  6144. """
  6145. logger = logging.getLogger(__name__)
  6146. # Cleared when the baseline was taken off a card we could not read, so the
  6147. # attach step refuses to choose between several candidates (#2957, #3412).
  6148. baseline_trusted = True
  6149. # --- Phase 1: establish the baseline -------------------------------------
  6150. try:
  6151. async with async_session() as db:
  6152. from backend.app.models.printer import Printer
  6153. service = ArchiveService(db)
  6154. archive = await service.get_archive(archive_id)
  6155. if not archive:
  6156. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6157. return
  6158. if archive.timelapse_path:
  6159. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6160. return
  6161. if not archive.printer_id:
  6162. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6163. return
  6164. # The run this scan is for. The archive row passes to a newer run
  6165. # when it prints again (the next plate, a reprint), and that run's
  6166. # video is its own.
  6167. run_started_at = archive.started_at
  6168. if (
  6169. baseline_names is not None
  6170. and baseline_unread
  6171. and archive.timelapse_baseline is not None
  6172. and not archive.timelapse_baseline_unread
  6173. ):
  6174. # The card was read at print start, and the in-memory copy is
  6175. # one Bambuddy took after a restart off a card it could not
  6176. # read: the stored one is this run's and is evidence.
  6177. baseline_names = set(archive.timelapse_baseline)
  6178. logger.info(
  6179. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6180. len(baseline_names),
  6181. archive_id,
  6182. )
  6183. elif baseline_names is not None:
  6184. baseline_trusted = not baseline_unread
  6185. logger.info(
  6186. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6187. len(baseline_names),
  6188. archive_id,
  6189. )
  6190. elif archive.timelapse_baseline is not None:
  6191. # Persisted at print start — survives a restart mid-print.
  6192. baseline_names = set(archive.timelapse_baseline)
  6193. baseline_trusted = not archive.timelapse_baseline_unread
  6194. logger.info(
  6195. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6196. len(baseline_names),
  6197. archive_id,
  6198. )
  6199. else:
  6200. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6201. printer = result.scalar_one_or_none()
  6202. if not printer:
  6203. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6204. return
  6205. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6206. if not baseline_trusted:
  6207. # The card is unreadable at the one moment a baseline has to
  6208. # be taken, so the empty listing means "we never looked",
  6209. # not "these are all new". Carry on with it anyway — the
  6210. # usual card holds exactly one video, which resolves
  6211. # correctly — but stop the poll from *choosing* between
  6212. # several, which is how a stale video got attached to this
  6213. # print and then deleted off the printer (#2957 follow-up).
  6214. logger.warning(
  6215. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6216. "read. A single new video still resolves; several will not be guessed between — "
  6217. "use Scan for Timelapse to pick one by hand",
  6218. archive_id,
  6219. archive.printer_id,
  6220. )
  6221. logger.info(
  6222. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6223. len(baseline_names),
  6224. archive_id,
  6225. )
  6226. except Exception as e:
  6227. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6228. return
  6229. # --- Phase 2: poll for a file that was not there when the print began -----
  6230. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6231. max_attempts = _timelapse_scan_max_attempts()
  6232. seen_names: set[str] = set()
  6233. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6234. attempt = 0
  6235. while True:
  6236. await asyncio.sleep(delay)
  6237. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6238. attempt += 1
  6239. try:
  6240. from backend.app.models.printer import Printer
  6241. # Read phase: fetch archive + printer in a short session and release
  6242. # the pooled connection BEFORE the FTP list/download below. Holding it
  6243. # across the FTP round-trips left one connection idle-in-transaction per
  6244. # in-flight scan (issue #2572).
  6245. async with async_session() as db:
  6246. service = ArchiveService(db)
  6247. archive = await service.get_archive(archive_id)
  6248. if not archive:
  6249. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6250. return
  6251. if archive.timelapse_path:
  6252. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  6253. return
  6254. if archive.started_at != run_started_at:
  6255. logger.info(
  6256. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  6257. )
  6258. return
  6259. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6260. printer = result.scalar_one_or_none()
  6261. if not printer:
  6262. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6263. return
  6264. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  6265. # I/O phase (no DB connection held): FTP list + download.
  6266. video_files, found_path = await _list_timelapse_videos(printer)
  6267. # The poll can run for dozens of rounds, so only narrate a round
  6268. # that saw something change. Repeating the whole listing every 30 s
  6269. # would bury the one interesting line in the support bundle.
  6270. names_now = {f.get("name", "") for f in video_files}
  6271. changed = attempt == 1 or names_now != seen_names
  6272. seen_names = names_now
  6273. speak = logger.info if changed else logger.debug
  6274. if video_files:
  6275. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6276. if changed:
  6277. for f in video_files[:5]:
  6278. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6279. attached = await _attach_first_unclaimed_timelapse(
  6280. archive_id,
  6281. printer,
  6282. video_files,
  6283. baseline_names,
  6284. claimed,
  6285. attempt,
  6286. logger,
  6287. quiet=not changed,
  6288. require_unambiguous=not baseline_trusted,
  6289. plate_id=plate_id,
  6290. run_started_at=run_started_at,
  6291. )
  6292. if attached:
  6293. return
  6294. else:
  6295. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6296. except Exception as e:
  6297. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6298. if attempt >= max_attempts or time.monotonic() >= deadline:
  6299. break
  6300. # No name-match fallback: it compared the print name against the filename,
  6301. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6302. # bundles it fired 159 times and matched zero times, so all it added was a
  6303. # misleading log line before giving up.
  6304. logger.warning(
  6305. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6306. archive_id,
  6307. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6308. )
  6309. async def _attach_layer_timelapse(
  6310. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  6311. ) -> None:
  6312. """Attach the external camera's stitched timelapse to the archive.
  6313. The camera's video is the one the user set up in Bambuddy, so it wins
  6314. over the printer's own when both are on: it replaces the printer's video
  6315. (usually there first; stitching takes minutes) and that file is deleted,
  6316. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6317. the run the frames were taken for: when the archive is printing again by
  6318. the time the stitch is done, the video is not the new run's and is
  6319. dropped. The stitched file is a temporary either way.
  6320. """
  6321. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6322. logger = logging.getLogger(__name__)
  6323. try:
  6324. async with async_session() as db:
  6325. service = ArchiveService(db)
  6326. archive = await service.get_archive(archive_id)
  6327. if archive is None:
  6328. return
  6329. if archive.started_at != run_started_at:
  6330. logger.info(
  6331. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6332. )
  6333. return
  6334. replaced = archive.timelapse_path
  6335. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6336. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6337. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  6338. return
  6339. attached = archive.timelapse_path
  6340. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6341. if replaced and replaced != attached:
  6342. try:
  6343. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6344. except PathTraversalError:
  6345. return
  6346. await asyncio.to_thread(old.unlink, missing_ok=True)
  6347. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6348. finally:
  6349. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6350. # ``run_started_at`` not given: attach whichever run the archive is on.
  6351. _ANY_RUN = object()
  6352. async def _attach_first_unclaimed_timelapse(
  6353. archive_id: int,
  6354. printer,
  6355. video_files: list[dict],
  6356. baseline_names: set[str],
  6357. claimed: set[str],
  6358. attempt: int,
  6359. logger: logging.Logger,
  6360. *,
  6361. quiet: bool = False,
  6362. require_unambiguous: bool = False,
  6363. plate_id: int | None = None,
  6364. run_started_at: datetime | None | object = _ANY_RUN,
  6365. ) -> bool:
  6366. """Download and attach the one video that belongs to this print.
  6367. A candidate is any file absent from the print-start baseline. More than one
  6368. can qualify when a previous print's video landed late, after this print's
  6369. baseline was taken — those are filtered out by name, because they are
  6370. already attached to another archive. Sorting the candidates instead would
  6371. mean sorting on mtime or on the filename timestamp, both of which come from
  6372. the printer's unsynced clock.
  6373. Returns True once a video is attached. The printer's copy is deleted only
  6374. after the attach succeeds on bytes whose length matched the listing.
  6375. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6376. already seen this exact listing — the poll runs for many rounds and only the
  6377. rounds where something changed are worth an INFO line.
  6378. """
  6379. from backend.app.services.bambu_ftp import (
  6380. DownloadDeadlineExceeded,
  6381. delete_archived_timelapse,
  6382. download_file_bytes_async,
  6383. remote_file_settled,
  6384. )
  6385. speak = logger.debug if quiet else logger.info
  6386. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6387. if not new_files:
  6388. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6389. return False
  6390. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6391. if not candidates:
  6392. speak(
  6393. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6394. attempt,
  6395. len(new_files),
  6396. )
  6397. return False
  6398. if len(candidates) > 1:
  6399. if require_unambiguous:
  6400. # The baseline is not evidence -- it was taken off a card that could
  6401. # not be read -- so "new since the baseline" does not narrow these
  6402. # down at all. Taking the first would attach an arbitrary video to
  6403. # this print and then delete it from the printer.
  6404. logger.warning(
  6405. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6406. "leaving all of them on the printer for manual selection",
  6407. attempt,
  6408. len(candidates),
  6409. ", ".join(str(f.get("name")) for f in candidates),
  6410. )
  6411. return False
  6412. logger.warning(
  6413. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6414. "the rest stay on the printer for manual selection",
  6415. attempt,
  6416. len(candidates),
  6417. ", ".join(str(f.get("name")) for f in candidates),
  6418. )
  6419. target = candidates[0]
  6420. file_name = str(target.get("name") or "") # every listed entry has one
  6421. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6422. logger.info(
  6423. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6424. attempt,
  6425. file_name,
  6426. archive_id,
  6427. )
  6428. # The listing always carries a size (`list_files` skips entries it can't
  6429. # parse), but read it explicitly: the delete below is destructive and must
  6430. # depend on a size we actually had, not on one we hoped was there.
  6431. expected_size = target.get("size")
  6432. try:
  6433. timelapse_data = await download_file_bytes_async(
  6434. printer.ip_address,
  6435. printer.access_code,
  6436. remote_path,
  6437. printer_model=printer.model,
  6438. expected_size=expected_size,
  6439. )
  6440. except DownloadDeadlineExceeded:
  6441. # Too slow for its size this round; the printer keeps its copy.
  6442. timelapse_data = None
  6443. if not timelapse_data:
  6444. # Short or failed transfer. The printer keeps its copy, so the next
  6445. # round can try again — which is exactly why the delete below is
  6446. # gated on a verified download.
  6447. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6448. return False
  6449. # The length check above proves we got what the listing said, not that the
  6450. # printer had finished writing. A video still being written can be listed
  6451. # short, served short, and pass — so confirm it has stopped growing before
  6452. # committing to it and deleting the original (#2704).
  6453. if not await remote_file_settled(
  6454. printer.ip_address,
  6455. printer.access_code,
  6456. remote_path,
  6457. len(timelapse_data),
  6458. printer_model=printer.model,
  6459. ):
  6460. return False
  6461. # Write phase: attach in a fresh short-lived session. The download took a
  6462. # while: by now the archive may have its video, or be printing again for a
  6463. # newer run, whose video this is not. Then nothing is attached or deleted,
  6464. # and the poll ends (True).
  6465. async with async_session() as db:
  6466. service = ArchiveService(db)
  6467. if run_started_at is not _ANY_RUN:
  6468. current = await service.get_archive(archive_id)
  6469. if current is None or current.timelapse_path or current.started_at != run_started_at:
  6470. logger.info(
  6471. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6472. "%s stays on the printer",
  6473. archive_id,
  6474. file_name,
  6475. )
  6476. return True
  6477. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  6478. if not success:
  6479. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6480. return False
  6481. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6482. await delete_archived_timelapse(
  6483. printer.ip_address,
  6484. printer.access_code,
  6485. remote_path,
  6486. verified=expected_size is not None,
  6487. printer_model=printer.model,
  6488. printer_name=printer.name,
  6489. )
  6490. return True
  6491. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6492. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6493. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6494. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6495. # How long the *background* upgrade keeps waiting after the notification has
  6496. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6497. # printer can't hold up the print-complete notification; this one exists so the
  6498. # archive still ends up with the better frame afterwards.
  6499. #
  6500. # Measured across 261 attaches in the support bundles, the video lands a median
  6501. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6502. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6503. # was 546s. Every other model was inside 26s. The long budget is therefore
  6504. # almost entirely for P1-series users; on everything else the short wait already
  6505. # wins and this task never runs.
  6506. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6507. async def _capture_finish_photo_from_timelapse(
  6508. archive_id: int,
  6509. archive_dir: Path,
  6510. timeout: float | None = None,
  6511. rotation: int = 0,
  6512. ) -> tuple[str | None, bool]:
  6513. """Wait for the per-print timelapse to land on the archive and extract its
  6514. last frame as the finish photo (#1397).
  6515. Bambu firmware stops timelapse recording after the toolhead parks but
  6516. before the bed-drop end-gcode runs, so the last frame frames the finished
  6517. print correctly. A live camera grab at gcode_state=FINISH captures the
  6518. bed already lowered.
  6519. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6520. ``archive.timelapse_path`` when the file lands. This function polls for
  6521. that field.
  6522. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6523. the wait ran out with no video on the archive yet — i.e. the video may
  6524. still be coming and a later attempt could succeed. It is False when the
  6525. video landed (whether or not extraction worked), because in that case
  6526. waiting longer changes nothing. The caller uses that to decide between
  6527. falling back permanently and scheduling a background upgrade.
  6528. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6529. still (#2708) so this source agrees with every other finish-photo source.
  6530. The archived video itself is the printer's own file and is left alone —
  6531. rotating it would mean re-encoding it.
  6532. """
  6533. import uuid
  6534. from backend.app.models.archive import PrintArchive
  6535. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6536. logger = logging.getLogger(__name__)
  6537. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6538. deadline = asyncio.get_event_loop().time() + budget
  6539. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6540. while True:
  6541. async with async_session() as db:
  6542. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6543. archive = result.scalar_one_or_none()
  6544. timelapse_relpath = archive.timelapse_path if archive else None
  6545. if timelapse_relpath:
  6546. video_path = app_settings.base_dir / timelapse_relpath
  6547. if video_path.exists() and video_path.stat().st_size > 0:
  6548. photos_dir = archive_dir / "photos"
  6549. photos_dir.mkdir(parents=True, exist_ok=True)
  6550. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6551. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6552. output_path = photos_dir / filename
  6553. if await extract_video_last_frame(video_path, output_path):
  6554. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6555. logger.info(
  6556. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6557. video_path.name,
  6558. archive_id,
  6559. )
  6560. return filename, False
  6561. logger.warning(
  6562. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6563. video_path.name,
  6564. archive_id,
  6565. )
  6566. return None, False
  6567. if asyncio.get_event_loop().time() >= deadline:
  6568. logger.info(
  6569. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6570. archive_id,
  6571. budget,
  6572. )
  6573. return None, True
  6574. await asyncio.sleep(poll_interval)
  6575. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6576. """Add the timelapse's last frame to an archive after the fact (#2704).
  6577. The print-complete notification waits only ~60s for the video, because
  6578. holding a notification for minutes is worse than sending it with a live
  6579. camera grab. On a P1-series printer the video often lands well after that,
  6580. so the archive used to be stuck with the live grab — which is taken at
  6581. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6582. the worse photo of the two.
  6583. This keeps waiting in the background and, when the video arrives, extracts
  6584. the frame and puts it *first* in the archive's photo list, so opening the
  6585. gallery shows it. The live grab is deliberately kept: the notification that
  6586. already went out links to that exact file, and deleting it would leave a
  6587. broken image in Discord or Telegram.
  6588. """
  6589. logger = logging.getLogger(__name__)
  6590. filename, _ = await _capture_finish_photo_from_timelapse(
  6591. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6592. )
  6593. if not filename:
  6594. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6595. return
  6596. try:
  6597. async with async_session() as db:
  6598. from backend.app.models.archive import PrintArchive
  6599. archive = await db.get(PrintArchive, archive_id)
  6600. if archive is None:
  6601. return
  6602. photos = list(archive.photos or [])
  6603. if filename in photos:
  6604. return
  6605. # Front of the list: PhotoGalleryModal opens at index 0.
  6606. archive.photos = [filename, *photos]
  6607. await db.commit()
  6608. except Exception as e:
  6609. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6610. return
  6611. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6612. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6613. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6614. """Put the filament-attribution context back after a restart mid-print.
  6615. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6616. both die with the process. The print keeps running, so at completion the
  6617. tracker would fall back to whatever the printer reports *now* — and AMS
  6618. filament backup makes "now" the substitute tray, charging the whole print
  6619. to the spool that only finished it.
  6620. The persisted row is only trusted when its print name still matches what
  6621. the printer says it is running: a row left behind by a completion we never
  6622. saw must not attach itself to the next print.
  6623. """
  6624. try:
  6625. from backend.app.api.routes.settings import get_setting
  6626. from backend.app.services.usage_tracker import (
  6627. clear_persisted_session,
  6628. get_persisted_ams_mapping,
  6629. get_persisted_print_name,
  6630. get_persisted_spool_change_log,
  6631. restore_session,
  6632. )
  6633. persisted_name = await get_persisted_print_name(db, printer_id)
  6634. current_name = (state.subtask_name or "").strip()
  6635. if persisted_name and current_name and persisted_name.strip() != current_name:
  6636. logger.info(
  6637. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6638. printer_id,
  6639. persisted_name,
  6640. current_name,
  6641. )
  6642. await clear_persisted_session(db, printer_id)
  6643. # Fall through to seeding: the print on the printer is real, it just
  6644. # isn't the one the row described.
  6645. persisted_log = None
  6646. else:
  6647. # Spoolman users get the tray-change log back but no in-memory
  6648. # session — see ``on_print_start`` on why that dict is load-bearing
  6649. # for the remain%-sync guard.
  6650. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6651. persisted_log = await restore_session(
  6652. db,
  6653. printer_id,
  6654. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6655. )
  6656. # The slot pills (#1762) read the mapping captured from the print
  6657. # command, which dies with the process as well. One this process
  6658. # has captured since is newer.
  6659. if state.print_ams_mapping is None:
  6660. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6661. # Spools swapped on a tray before the restart (#3325); anything this
  6662. # process has recorded since goes after them.
  6663. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6664. if persisted_swaps:
  6665. seen = getattr(state, "spool_change_log", None) or []
  6666. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6667. if persisted_log:
  6668. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6669. # Anything this process already observed goes after the persisted
  6670. # history — the log is ordered by layer, and a fresh process can
  6671. # only have seen changes from later in the print.
  6672. for entry in state.tray_change_log or []:
  6673. if tuple(entry) not in restored:
  6674. restored.append(tuple(entry))
  6675. state.tray_change_log = restored
  6676. tray_now = state.tray_now
  6677. if 0 <= tray_now <= 254:
  6678. if not state.tray_change_log:
  6679. # No persisted history — a print that started before this build,
  6680. # or before the row existed. Seed with the tray feeding right
  6681. # now so the remainder of the print is at least attributable to
  6682. # the right spool.
  6683. state.tray_change_log = [(tray_now, state.layer_num)]
  6684. logger.info(
  6685. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6686. printer_id,
  6687. tray_now,
  6688. state.layer_num,
  6689. )
  6690. # The tray handler updates ``last_loaded_tray`` on every push
  6691. # regardless of whether it logged a change, so re-align it to avoid
  6692. # a duplicate entry on the next push. Only ever with a real tray:
  6693. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6694. # 255" fallback, and writing 255 into it would defeat that.
  6695. state.last_loaded_tray = tray_now
  6696. except Exception:
  6697. # Never let attribution recovery cost the caller its timelapse
  6698. # baseline — that capture has to happen before the printer uploads
  6699. # the in-flight MP4 and there is no second chance at it.
  6700. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6701. async def on_print_running_observed(printer_id: int, data: dict):
  6702. """Restart-recovery for a print that started before Bambuddy came up.
  6703. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6704. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6705. creation). This hook restores the persisted archive into ``_active_prints``
  6706. and captures the timelapse baseline that normally hangs off print start.
  6707. Fires once per session, in lieu of on_print_start when restart-recovery
  6708. kicks in. The printer doesn't upload the timelapse until after PRINT
  6709. COMPLETE, so a baseline captured any time during the print is still
  6710. pre-upload.
  6711. """
  6712. logger = logging.getLogger(__name__)
  6713. async with async_session() as db:
  6714. from backend.app.models.printer import Printer
  6715. state = printer_manager.get_status(printer_id)
  6716. if state is not None:
  6717. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6718. if authorization is True:
  6719. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6720. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6721. await _restore_printable_objects(printer_id, state, db, logger)
  6722. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6723. printer = result.scalar_one_or_none()
  6724. if not printer:
  6725. logger.warning(
  6726. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6727. printer_id,
  6728. )
  6729. return
  6730. # Avoid double-capture: ownership reconciliation above must still run when
  6731. # a baseline already exists, but the camera work itself is one-shot.
  6732. if printer_id in _timelapse_baselines:
  6733. logger.debug(
  6734. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6735. printer_id,
  6736. )
  6737. return
  6738. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6739. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6740. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6741. against the printer's current MQTT state.
  6742. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6743. COMPLETE events, typically a print finishing during an MQTT disconnect
  6744. window followed by a smart-plug power cycle):
  6745. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6746. provably not running anymore — only branch that should fire under
  6747. normal disconnect-then-reconnect timing.
  6748. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6749. firmware mints a fresh ``subtask_id`` for each print, including the
  6750. ghost replay it runs after a power cycle from a leftover SD file —
  6751. so a mismatch unambiguously means the in-DB archive is no longer
  6752. the print on the printer.
  6753. 3. Printer is running but ``subtask_name`` is empty. The printer
  6754. doesn't know what it's running; the archive's reference to it is
  6755. already broken.
  6756. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6757. with matching subtask_id+subtask_name is left alone. The cost of a false
  6758. positive is a print closed while it still runs: the reconcile takes its
  6759. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6760. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6761. cost of a false negative is the ghost-print loop in #1542. What the
  6762. archive is closed as is ``_reconciled_outcome``'s call.
  6763. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6764. MQTT has connected but the first ``push_status`` response hasn't been
  6765. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6766. The reconcile caller in ``on_printer_status_change`` is already gated
  6767. on a real ``state.state``, so in normal operation this branch is
  6768. unreachable; it's kept as belt-and-braces for future callers and for
  6769. the narrow window where a partial state update could arrive
  6770. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6771. ``not stale`` on degenerate input is strictly conservative: a real
  6772. stale archive will still be caught by the next push_status arriving
  6773. with terminal state.
  6774. """
  6775. current_state = (state.state or "").upper()
  6776. if current_state in ("", "UNKNOWN"):
  6777. # No real push_status yet — PrinterState defaults are not evidence.
  6778. return False, ""
  6779. if current_state in ("IDLE", "FINISH", "FAILED"):
  6780. return True, f"printer state {current_state}"
  6781. # Below here the printer is in a running / pre-running state (RUNNING /
  6782. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6783. current_subtask_id = (state.subtask_id or "").strip()
  6784. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6785. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6786. current_subtask_name = (state.subtask_name or "").strip()
  6787. if not current_subtask_name:
  6788. return True, "printer subtask_name empty"
  6789. return False, ""
  6790. async def prime_kprofile_table(printer_id: int) -> int:
  6791. """Read the printer's calibration table once per connection.
  6792. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6793. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6794. report ``cali_idx`` and nothing else -- that number can only come from
  6795. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6796. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6797. backup, or the printer answering a query BambuStudio made on the report
  6798. topic we share. A Bambuddy that nobody visited showed a card with no K
  6799. values at all.
  6800. Only the diameters actually fitted are asked for, which is one request on a
  6801. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6802. what the backup does, and it is both wasteful and the thing that used to
  6803. blank the table.
  6804. Returns the number of nozzles whose table was read.
  6805. """
  6806. client = printer_manager.get_client(printer_id)
  6807. state = printer_manager.get_status(printer_id)
  6808. if client is None or state is None or not state.connected:
  6809. return 0
  6810. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6811. # ask once, and both entries are empty until the first push_status lands.
  6812. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6813. if not diameters:
  6814. logging.getLogger(__name__).debug(
  6815. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6816. printer_id,
  6817. )
  6818. return 0
  6819. primed = 0
  6820. for diameter in diameters:
  6821. try:
  6822. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6823. except Exception as exc: # noqa: BLE001
  6824. # A printer that won't answer costs the card its K values, nothing
  6825. # more — never the connection this runs on the back of.
  6826. logging.getLogger(__name__).warning(
  6827. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6828. )
  6829. continue
  6830. primed += 1
  6831. logging.getLogger(__name__).info(
  6832. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6833. )
  6834. return primed
  6835. def _sd_files_in_use(state) -> set[str]:
  6836. """Names of the SD-card files the printer may be printing right now (#3009).
  6837. The post-print cleanup works out what to delete from the finished archive,
  6838. not from the printer. When reconciliation closes an old archive because the
  6839. printer has moved on to a new job, and that job is the same file reprinted
  6840. from the printer's screen, the cleanup would delete the file mid-print.
  6841. Empty unless the printer is busy: on an ordinary completion the state is
  6842. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6843. name, a path or a URL depending on firmware, and some report only the
  6844. plate's G-code, so the job name is matched as well, in the same spellings
  6845. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6846. ignores case.
  6847. """
  6848. def _text(value) -> str:
  6849. return value.strip() if isinstance(value, str) else ""
  6850. if state is None:
  6851. return set()
  6852. current_state = _text(getattr(state, "state", None)).upper()
  6853. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6854. return set()
  6855. in_use: set[str] = set()
  6856. gcode_file = _text(getattr(state, "gcode_file", None))
  6857. if gcode_file:
  6858. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6859. # both legal in a file name, and raises on some inputs.
  6860. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6861. if name:
  6862. in_use.add(name.lower())
  6863. subtask_name = _text(getattr(state, "subtask_name", None))
  6864. if subtask_name:
  6865. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6866. for ext in (".3mf", ".gcode"):
  6867. in_use.add(f"{name}{ext}".lower())
  6868. return in_use
  6869. def _reconciled_outcome(archive, state) -> str:
  6870. """What a stale archive is closed as at reconnect (#3310).
  6871. A print that ends while Bambuddy restarts is never seen to end: the new
  6872. MQTT client's first status is already FINISH, which is not a transition.
  6873. The printer keeps reporting the finished job's ``subtask_id`` until the
  6874. next print, so a matching id proves the FINISH or FAILED is this
  6875. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  6876. started outside the cloud) or none -- says only that the print is over,
  6877. not how, and stays ``aborted``.
  6878. """
  6879. current_state = (state.state or "").upper()
  6880. if current_state not in ("FINISH", "FAILED"):
  6881. return "aborted"
  6882. archive_id = (archive.subtask_id or "").strip()
  6883. current_id = str(state.subtask_id or "").strip()
  6884. if archive_id in ("", "0") or archive_id != current_id:
  6885. return "aborted"
  6886. return "completed" if current_state == "FINISH" else "failed"
  6887. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  6888. """When a print reconciled as completed most likely ended, or None (#3310).
  6889. The printer does not say when it finished, and the reconnect can be hours
  6890. later. Its start plus the slicer's estimate for the plate it printed,
  6891. never later than now, is the best guess; None when either is missing,
  6892. and the run then keeps no duration, as an aborted one does.
  6893. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  6894. of another plate reuses the archive without changing ``archive.plate_id``.
  6895. """
  6896. started = archive.started_at
  6897. if not started:
  6898. return None
  6899. if started.tzinfo is None:
  6900. started = started.replace(tzinfo=timezone.utc)
  6901. plate = plate_id if plate_id is not None else archive.plate_id
  6902. estimate = None
  6903. if archive.file_path:
  6904. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  6905. full_path = (
  6906. app_settings.base_dir / archive.file_path
  6907. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6908. try:
  6909. estimate = extract_print_time_from_3mf(full_path, plate)
  6910. except Exception as exc: # noqa: BLE001
  6911. logging.getLogger(__name__).debug(
  6912. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  6913. )
  6914. if plate is None and estimate != archive.print_time_seconds:
  6915. # Without a plate the first plate's estimate is read. The archive
  6916. # carries the sum over all plates (#1593), so a difference means
  6917. # several plates and no telling which one printed.
  6918. estimate = None
  6919. elif plate is None:
  6920. # Nothing to read the plate from; the archive's own estimate, as for
  6921. # a single-plate file.
  6922. estimate = archive.print_time_seconds
  6923. if not estimate or estimate <= 0:
  6924. return None
  6925. return min(started + timedelta(seconds=int(estimate)), now)
  6926. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6927. """Synthesise ``on_print_complete`` for archives whose print can't be
  6928. running on the printer anymore.
  6929. Called once per MQTT (re)connection (from on_printer_status_change when
  6930. the connected edge flips False → True) and at Bambuddy startup (from
  6931. the FastAPI lifespan). Without this, a print that completes during a
  6932. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6933. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6934. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6935. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6936. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6937. closes the loop by faking the missed PRINT COMPLETE — the existing
  6938. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6939. and notifications.
  6940. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  6941. when the printer still reports the archive's own job as finished or
  6942. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  6943. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  6944. after a restart the printer's FINISH is not one (#3310).
  6945. Returns the number of archives reconciled.
  6946. """
  6947. state = printer_manager.get_status(printer_id)
  6948. if not state:
  6949. return 0
  6950. # Don't reconcile while disconnected — we'd be making a decision against
  6951. # stale cached state. The connected → reconcile edge handles this.
  6952. if not state.connected:
  6953. return 0
  6954. from backend.app.models.archive import PrintArchive
  6955. reconciled = 0
  6956. async with async_session() as db:
  6957. result = await db.execute(
  6958. select(PrintArchive).where(
  6959. PrintArchive.printer_id == printer_id,
  6960. PrintArchive.status == "printing",
  6961. )
  6962. )
  6963. active = list(result.scalars().all())
  6964. if not active:
  6965. return 0
  6966. # The plate each run printed, from its queue job (#3310).
  6967. from backend.app.models.print_queue import PrintQueueItem
  6968. async with async_session() as db:
  6969. plate_rows = await db.execute(
  6970. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  6971. PrintQueueItem.printer_id == printer_id,
  6972. PrintQueueItem.status == "printing",
  6973. PrintQueueItem.archive_id.in_([a.id for a in active]),
  6974. )
  6975. )
  6976. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  6977. logger = logging.getLogger(__name__)
  6978. for archive in active:
  6979. is_stale, reason = _is_active_archive_stale(archive, state)
  6980. if not is_stale:
  6981. continue
  6982. logger.info(
  6983. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6984. printer_id,
  6985. archive.id,
  6986. archive.filename,
  6987. reason,
  6988. )
  6989. # Synthesised payload: minimal fields the on_print_complete chain
  6990. # needs. `_reconciled` marker lets downstream code distinguish this
  6991. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6992. # metrics / debug logging). raw_data is the live printer state so
  6993. # the usage tracker can compare end-of-print remain% against the
  6994. # captured start values.
  6995. outcome = _reconciled_outcome(archive, state)
  6996. payload = {
  6997. "status": outcome,
  6998. "filename": archive.filename,
  6999. "subtask_name": archive.print_name or "",
  7000. "subtask_id": archive.subtask_id or "",
  7001. "raw_data": state.raw_data or {},
  7002. "_reconciled": True,
  7003. }
  7004. if outcome != "aborted":
  7005. # The printer's progress and layer are this job's, so a partial
  7006. # run is charged what it printed rather than nothing.
  7007. if state.progress:
  7008. payload["last_progress"] = state.progress
  7009. if state.layer_num:
  7010. payload["last_layer_num"] = state.layer_num
  7011. if outcome == "failed":
  7012. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7013. if outcome == "completed":
  7014. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7015. if ended:
  7016. payload["_reconciled_completed_at"] = ended
  7017. try:
  7018. await on_print_complete(printer_id, payload)
  7019. reconciled += 1
  7020. except Exception as e:
  7021. # Catch-all: a reconciliation failure must not block the
  7022. # printer's normal status flow. The archive stays in
  7023. # ``status="printing"`` and the next reconnect retries.
  7024. logger.warning(
  7025. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7026. archive.id,
  7027. e,
  7028. )
  7029. return reconciled
  7030. # #2547: clearance left between the nozzle and the top of the print when the
  7031. # plate is commanded back into camera framing. The nozzle is parked away from
  7032. # the part by then, so this is belt-and-braces against a max_z_height that
  7033. # under-reports (e.g. a slicer that excludes a final Z hop).
  7034. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7035. # How far below the restored position to drop the plate again afterwards, so
  7036. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7037. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7038. # on machines with less headroom.
  7039. _PLATE_PARK_DROP_MM = 100.0
  7040. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7041. # this axis, so it is a proven-safe speed for the full travel.
  7042. _PLATE_RESTORE_FEEDRATE = 600
  7043. # Time allowed for the plate to reach the restored position before the camera
  7044. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7045. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7046. # How long `_background_finish_photo` waits for this producer. Must cover the
  7047. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7048. # notification path's own photo wait so a slow producer degrades to a
  7049. # photo-less notification rather than a missed one. The chamber light's
  7050. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7051. # camera_light.MAX_DELAY_SECONDS stays below it.
  7052. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7053. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7054. """The ``_active_prints`` keys a finished print may be registered under.
  7055. Matching how they were registered in on_print_start. Shared by
  7056. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7057. to find the same binding.
  7058. """
  7059. possible_keys = []
  7060. # Try subtask_name variations first (most reliable for matching)
  7061. if subtask_name:
  7062. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7063. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7064. possible_keys.append((printer_id, subtask_name))
  7065. # Try filename variations
  7066. if filename:
  7067. # Extract just the filename if it's a path
  7068. fname = filename.split("/")[-1] if "/" in filename else filename
  7069. if fname.endswith(".3mf"):
  7070. possible_keys.append((printer_id, fname))
  7071. elif fname.endswith(".gcode"):
  7072. base_name = fname.rsplit(".", 1)[0]
  7073. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7074. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7075. possible_keys.append((printer_id, fname))
  7076. else:
  7077. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7078. possible_keys.append((printer_id, f"{fname}.3mf"))
  7079. possible_keys.append((printer_id, fname))
  7080. # Also try full path versions
  7081. if filename.endswith(".3mf"):
  7082. possible_keys.append((printer_id, filename))
  7083. elif filename.endswith(".gcode"):
  7084. base_name = filename.rsplit(".", 1)[0]
  7085. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7086. possible_keys.append((printer_id, filename))
  7087. else:
  7088. possible_keys.append((printer_id, f"{filename}.3mf"))
  7089. possible_keys.append((printer_id, filename))
  7090. return possible_keys
  7091. def _archive_name_forms(archive) -> set[str]:
  7092. """The names an archive could be echoed back as, in normalised form (#3240).
  7093. Its print name, and its filename with and without the 3MF extension.
  7094. """
  7095. forms = set()
  7096. if archive.print_name:
  7097. forms.add(_normalise_subtask_name(archive.print_name))
  7098. if archive.filename:
  7099. forms.add(_normalise_subtask_name(archive.filename))
  7100. for suffix in (".gcode.3mf", ".3mf"):
  7101. if archive.filename.lower().endswith(suffix):
  7102. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7103. forms.discard("")
  7104. return forms
  7105. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7106. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7107. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7108. from the plate recorded when the job was dispatched. Neither is touched:
  7109. ``on_print_complete`` pops both, which is why the finish-photo producer
  7110. calls this before its first await, while they are still there.
  7111. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7112. archive, or that it only knows by a name -- and on any error: the producer
  7113. calls this before the ``try`` that always releases the photo consumer, so
  7114. it must not raise.
  7115. """
  7116. try:
  7117. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7118. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7119. if archive_id is None:
  7120. return None, None
  7121. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7122. except Exception:
  7123. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7124. return None, None
  7125. async def _max_z_for_current_print(
  7126. printer_id: int,
  7127. data: dict,
  7128. logger,
  7129. archive_id: int | None,
  7130. plate_id: int | None = None,
  7131. ) -> float | None:
  7132. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7133. This number becomes the target of a real Z move, so every step here refuses
  7134. rather than guesses. A height belonging to some *other* print is the one
  7135. failure that could drive the nozzle into the model: 20 mm carried onto a
  7136. 200 mm print would command the plate up through the part.
  7137. Three independent things therefore have to agree before a height is
  7138. returned:
  7139. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7140. when it started (see ``_bound_print``), never one found by name. A name
  7141. is not an identity: every plate of a multi-plate file shares one, and a
  7142. reprint reuses its archive row, so the newest archive with the right
  7143. name can be another plate of the same file. Support bundles show the
  7144. old name lookup doing exactly that (archive 288 for a print bound to
  7145. 169, 313 layers against 125), stopped only by the layer check below.
  7146. No binding, no move.
  7147. 2. **Identity.** The bound archive's name still has to be the finished
  7148. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7149. because the printer echoes spaces as underscores (#3240). Exact: not a
  7150. substring, and not the completion check's tolerance for a truncated
  7151. echo.
  7152. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7153. match the layer count the printer itself reported over MQTT for the print
  7154. that just ended. These come from genuinely different sources, so a
  7155. mismatch means the row is not this print, whatever its name says.
  7156. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7157. plate of a multi-plate file reuses the archive row without updating its
  7158. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7159. ``on_print_complete`` may already have flipped the status by the time we
  7160. run.
  7161. """
  7162. subtask_name = (data.get("subtask_name") or "").strip()
  7163. if not subtask_name:
  7164. # Nothing to identify the print by — refuse rather than fall back to
  7165. # "whatever ran last on this printer".
  7166. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7167. return None
  7168. if archive_id is None:
  7169. logger.info(
  7170. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7171. printer_id,
  7172. subtask_name,
  7173. )
  7174. return None
  7175. try:
  7176. from backend.app.models.archive import PrintArchive
  7177. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7178. async with async_session() as db:
  7179. result = await db.execute(
  7180. select(PrintArchive).where(
  7181. PrintArchive.id == archive_id,
  7182. PrintArchive.printer_id == printer_id,
  7183. PrintArchive.status.in_(("printing", "completed")),
  7184. PrintArchive.deleted_at.is_(None),
  7185. )
  7186. )
  7187. archive = result.scalar_one_or_none()
  7188. if archive is None or not archive.file_path:
  7189. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7190. return None
  7191. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7192. logger.warning(
  7193. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7194. printer_id,
  7195. archive_id,
  7196. subtask_name,
  7197. )
  7198. return None
  7199. client = printer_manager.get_client(printer_id)
  7200. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7201. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7202. logger.warning(
  7203. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7204. "— refusing to move the plate on a height that may not be this print's",
  7205. printer_id,
  7206. archive.id,
  7207. archive.total_layers,
  7208. reported_layers,
  7209. )
  7210. return None
  7211. # Stored relative to the data directory, like every other archive path
  7212. # (#3240: this read a `data_dir` setting that does not exist).
  7213. path = app_settings.base_dir / archive.file_path
  7214. plate = plate_id or archive.plate_id or 1
  7215. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7216. except Exception as e:
  7217. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7218. return None
  7219. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7220. """Raise the plate back into camera framing before the finish photo (#2547).
  7221. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7222. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7223. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7224. This commands an absolute ``G1 Z`` back to just above the last printed
  7225. layer.
  7226. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7227. clearance`` is a height the toolhead was physically at seconds earlier, so
  7228. it is inside the travel limits by construction and leaves the nozzle above
  7229. the part. It is also unambiguous across model families: Z is the
  7230. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7231. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7232. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7233. (#2579).
  7234. Returns True if the move was sent and waited out, False if it was skipped.
  7235. """
  7236. client = printer_manager.get_client(printer_id)
  7237. if client is None:
  7238. return False
  7239. # Re-read state immediately before commanding motion. If the queue has
  7240. # already started the next print, the printer is no longer ours to move.
  7241. state = getattr(client, "state", None)
  7242. if state is None or state.state != "FINISH":
  7243. logger.info(
  7244. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7245. printer_id,
  7246. getattr(state, "state", "unknown"),
  7247. )
  7248. return False
  7249. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7250. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7251. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7252. return False
  7253. logger.info(
  7254. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7255. printer_id,
  7256. target_z,
  7257. max_z_height,
  7258. _PLATE_RESTORE_CLEARANCE_MM,
  7259. _PLATE_RESTORE_SETTLE_SECONDS,
  7260. )
  7261. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7262. return True
  7263. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7264. """Drop the plate again after the finish photo (#2547).
  7265. Without this the user walks up to a finished print sitting just under the
  7266. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7267. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7268. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7269. print homes anyway.
  7270. """
  7271. client = printer_manager.get_client(printer_id)
  7272. state = getattr(client, "state", None) if client else None
  7273. if client is None or state is None or state.state != "FINISH":
  7274. return
  7275. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7276. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7277. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7278. """True if a queue item is about to take this printer (#2547).
  7279. The scheduler dispatches the next job the moment a print completes, and a
  7280. plate move interleaved with a print start is not a race worth having. The
  7281. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7282. this window; this closes the head of it.
  7283. """
  7284. try:
  7285. from backend.app.models.print_queue import PrintQueueItem
  7286. async with async_session() as db:
  7287. result = await db.execute(
  7288. select(PrintQueueItem.id)
  7289. .where(
  7290. PrintQueueItem.printer_id == printer_id,
  7291. PrintQueueItem.status.in_(("pending", "printing")),
  7292. )
  7293. .limit(1)
  7294. )
  7295. return result.scalar_one_or_none() is not None
  7296. except Exception as e:
  7297. # Fail closed: if we can't tell, don't move the plate.
  7298. logging.getLogger(__name__).debug(
  7299. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7300. )
  7301. return True
  7302. async def on_finish_photo_moment(printer_id: int, data: dict):
  7303. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7304. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7305. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7306. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7307. HMS halt, firmware variants). Grabs one frame via the same
  7308. external-camera / RTSP path the post-completion fallback uses, stores
  7309. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7310. ``_background_finish_photo`` consume the cached bytes when it runs.
  7311. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7312. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7313. set to Smooth (#1721). No force-on now means the user's explicit
  7314. timelapse=off in the slicer send dialog is respected.
  7315. """
  7316. logger = logging.getLogger(__name__)
  7317. trigger = data.get("trigger", "unknown")
  7318. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7319. logger.info(
  7320. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7321. printer_id,
  7322. trigger,
  7323. timelapse_was_active,
  7324. )
  7325. # If a timelapse is actively recording, skip the pre-capture — the
  7326. # post-completion path will extract the last frame from the recorded
  7327. # video, which still provides the best framing (toolhead parked,
  7328. # before bed drop) without the per-layer parking side effects.
  7329. if timelapse_was_active:
  7330. logger.info(
  7331. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7332. printer_id,
  7333. )
  7334. return
  7335. # #1790: register the producer-done event BEFORE the first await so the
  7336. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7337. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7338. # The `finally` below guarantees `set()` runs on every exit, including
  7339. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7340. producer_done = asyncio.Event()
  7341. _stage22_finish_in_flight[printer_id] = producer_done
  7342. # #3240: also before the first await. On the FINISH-state path
  7343. # `on_print_complete` is dispatched right behind us and pops both the
  7344. # print's archive binding and its plate; read here, they are still there.
  7345. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7346. # #2547: set once the plate has actually been raised, and read by the
  7347. # `finally` below. Declared out here so a failure anywhere after the move —
  7348. # a camera timeout, a DB error — still lowers the plate again.
  7349. restore_max_z: float | None = None
  7350. try:
  7351. async with async_session() as db:
  7352. from backend.app.api.routes.settings import get_setting
  7353. from backend.app.models.printer import Printer
  7354. capture_setting = await get_setting(db, "capture_finish_photo")
  7355. if capture_setting is not None and capture_setting.lower() != "true":
  7356. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7357. return
  7358. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7359. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7360. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7361. printer = result.scalar_one_or_none()
  7362. if printer is None:
  7363. logger.warning(
  7364. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7365. printer_id,
  7366. )
  7367. return
  7368. frame_bytes: bytes | None = None
  7369. # #2708: the banked frame arrives already rotated — it comes from
  7370. # `_capture_snapshot_for_notification`, which rotates before returning.
  7371. # Every other source below is a raw grab. Tracking which lets us store
  7372. # exactly one rotation in `_stage22_finish_frames` either way.
  7373. frame_already_rotated = False
  7374. # On the FINISH-state path the End G-code has already run, and two very
  7375. # different situations arrive here needing opposite answers.
  7376. #
  7377. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7378. # snippet may have ejected the plate — the scene in front of the camera
  7379. # is no longer the finished print, and no amount of moving the plate
  7380. # brings it back. Use the banked in-print frame instead.
  7381. #
  7382. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7383. # than the camera frames well, and the toolhead is parked out of the
  7384. # way. That is the *best* moment available on firmware that never emits
  7385. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7386. # back. Preferring the bank here unconditionally, as this code used to,
  7387. # is what shipped a mid-print photo with the toolhead over the part.
  7388. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7389. banked = _inprint_frame_bank.get(printer_id)
  7390. if banked:
  7391. frame_bytes = banked
  7392. frame_already_rotated = True
  7393. logger.info(
  7394. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7395. "frame (%d bytes) instead of a post-swap live grab",
  7396. len(banked),
  7397. )
  7398. else:
  7399. logger.warning(
  7400. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7401. "in-print bank is empty — falling back to a live grab, which may show a "
  7402. "swapped or empty plate",
  7403. printer_id,
  7404. )
  7405. # `restore_max_z` is set only once the plate is actually up, because the
  7406. # `finally` reads it to decide whether it owes a move back down.
  7407. #
  7408. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7409. # came up empty above: that machine may have just ejected its plate, and
  7410. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7411. # taking for a photo of a bed we already know may be bare.
  7412. if (
  7413. frame_bytes is None
  7414. and trigger == "finish_state"
  7415. and restore_plate_enabled
  7416. and not print_dispatch_context.end_gcode_injected(printer_id)
  7417. ):
  7418. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7419. if wants_restore is None:
  7420. logger.info(
  7421. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7422. printer_id,
  7423. )
  7424. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7425. logger.info(
  7426. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7427. printer_id,
  7428. )
  7429. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7430. restore_max_z = wants_restore
  7431. # Chamber light for the live capture below (#1655). The banked frame
  7432. # above was taken without it, like every in-print bank.
  7433. async with camera_light(printer if frame_bytes is None else None):
  7434. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7435. from backend.app.api.routes.camera import live_frame_for_capture
  7436. from backend.app.services.external_camera import capture_frame
  7437. # #2707: this used to collide with the live view and fail, which is
  7438. # how finish-photo notifications went out with no image attached.
  7439. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7440. defer, buffered = live_frame_for_capture(printer_id)
  7441. if defer:
  7442. frame_bytes = buffered
  7443. else:
  7444. frame_bytes = await capture_frame(
  7445. printer.external_camera_url,
  7446. printer.external_camera_type or "mjpeg",
  7447. snapshot_url=printer.external_camera_snapshot_url,
  7448. )
  7449. if frame_bytes:
  7450. logger.info(
  7451. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7452. len(frame_bytes),
  7453. )
  7454. elif frame_bytes is None:
  7455. from backend.app.api.routes.camera import get_buffered_frame
  7456. buffered = get_buffered_frame(printer_id)
  7457. if buffered:
  7458. frame_bytes = buffered
  7459. logger.info(
  7460. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7461. len(frame_bytes),
  7462. )
  7463. else:
  7464. from backend.app.services.camera import capture_camera_frame_bytes
  7465. frame_bytes = await capture_camera_frame_bytes(
  7466. ip_address=printer.ip_address,
  7467. access_code=printer.access_code,
  7468. model=printer.model,
  7469. timeout=15,
  7470. )
  7471. if frame_bytes:
  7472. logger.info(
  7473. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7474. len(frame_bytes),
  7475. )
  7476. if frame_bytes:
  7477. if not frame_already_rotated:
  7478. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7479. _stage22_finish_frames[printer_id] = frame_bytes
  7480. else:
  7481. logger.warning(
  7482. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7483. printer_id,
  7484. )
  7485. except Exception as e:
  7486. logger.warning(
  7487. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7488. printer_id,
  7489. e,
  7490. )
  7491. finally:
  7492. # #2547: we raised the plate, so we own lowering it — including when the
  7493. # capture above failed or threw partway through.
  7494. if restore_max_z is not None:
  7495. try:
  7496. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7497. except Exception as e:
  7498. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7499. # #1790: always unblock the consumer's bounded wait — whether we stored
  7500. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7501. # dict entry by the consumer doesn't affect signalling.
  7502. producer_done.set()
  7503. def _subtask_name_from_filename(filename: str) -> str:
  7504. """Recover the subtask name a print command would have carried for *filename*.
  7505. The dispatcher derives the printer-facing subtask name from the archive's
  7506. file name, so stripping the extensions back off gives the value MQTT echoes
  7507. on completion. Only the two extensions Bambuddy actually stores are removed,
  7508. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7509. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7510. """
  7511. name = PurePosixPath(filename).name
  7512. for suffix in (".3mf", ".gcode"):
  7513. if name.lower().endswith(suffix):
  7514. name = name[: -len(suffix)]
  7515. return name
  7516. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7517. """Whether the subtask name is the printed 3MF's own file name.
  7518. A print started from the printer's screen reports the same full name, with
  7519. its extension, as both subtask and file (#3009). A dispatched print reports
  7520. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7521. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7522. """
  7523. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7524. return False
  7525. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7526. # How the printer marks a subtask name it had to cut short. Observed on real
  7527. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7528. # (a name with multibyte characters came back at 98), so match the marker
  7529. # rather than a length.
  7530. _SUBTASK_TRUNCATION_MARKER = "..."
  7531. def _normalise_subtask_name(name: str) -> str:
  7532. """Canonical form for comparing a dispatched name against MQTT's echo.
  7533. The printer does not echo the name back verbatim: it substitutes
  7534. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7535. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7536. The 3MF lookup in this module has always known that -- it builds
  7537. space-to-underscore variants of every candidate filename, and its
  7538. directory search normalises both sides before comparing. This exists so
  7539. the completion check reads the same rule from the same place instead of
  7540. growing its own, which is exactly how it came to disagree (#2829).
  7541. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7542. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7543. are dropped after the substitution so both sides agree (#3241).
  7544. """
  7545. return name.strip().replace(" ", "_").strip("_").casefold()
  7546. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7547. """The 3MF files of the printer's folder listings that are this print's.
  7548. A file of the print's own name wins, in whichever folder. Only without one
  7549. is a file that merely contains the name taken, and then only when it is
  7550. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7551. candidates none can be told apart. Paths keep the listings' order.
  7552. """
  7553. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7554. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7555. if exact:
  7556. return exact
  7557. term = _normalise_subtask_name(search_term)
  7558. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7559. if len(partial) > 1:
  7560. logging.getLogger(__name__).info(
  7561. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7562. )
  7563. return []
  7564. return partial
  7565. def _subtask_names_match(expected: str, observed: str) -> bool:
  7566. """Whether two subtask names describe the same print.
  7567. Beyond the space/underscore substitution, the printer truncates long names
  7568. and marks the cut with ``...``. A truncated echo has to count as a match or
  7569. every print with a long name strands its queue item the same way.
  7570. """
  7571. expected_n = _normalise_subtask_name(expected)
  7572. observed_n = _normalise_subtask_name(observed)
  7573. if expected_n == observed_n:
  7574. return True
  7575. # Either side can be the truncated one: the printer truncates what it
  7576. # echoes, and an archive whose own filename was recorded from a previous
  7577. # truncated echo carries the marker too.
  7578. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7579. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7580. continue
  7581. # The full side has lost its edge underscores; a cut that lands right
  7582. # after one keeps it, so drop it here too (#3241). Nothing left before
  7583. # the marker is no evidence of anything, and must not match every name.
  7584. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7585. if kept and full.startswith(kept):
  7586. return True
  7587. return False
  7588. async def _queue_item_dispatched_name(db, item) -> str:
  7589. """The subtask name *item* was dispatched under, or "" when unknowable.
  7590. A row with no archive, or an archive with no file name, is unverifiable
  7591. rather than wrong; every caller answers that with its permissive branch.
  7592. """
  7593. if item.archive_id is None:
  7594. return ""
  7595. from backend.app.models.archive import PrintArchive
  7596. archive = await db.get(PrintArchive, item.archive_id)
  7597. if archive is None or not archive.filename:
  7598. return ""
  7599. return _subtask_name_from_filename(archive.filename)
  7600. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7601. """Whether this completion event is plausibly about *item*'s print.
  7602. The caller finds its queue row by printer and ``status='printing'`` alone,
  7603. which is all a completion event gives it -- there is no run identifier in
  7604. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7605. completion delivered for this printer closes whichever row happens to be
  7606. printing, however unrelated. Comparing the subtask name against the archive
  7607. the row was dispatched with costs one primary-key load and rules that out.
  7608. Deliberately permissive: it answers False only on a positive disagreement
  7609. between two names we actually have. A row with no archive, an archive with
  7610. no file name, or an event with no subtask name is unverifiable rather than
  7611. wrong, and refusing those would strand the item in ``printing`` and wedge
  7612. the printer's queue -- a worse failure than the one being prevented.
  7613. """
  7614. observed = (data.get("subtask_name") or "").strip()
  7615. if not observed or item.archive_id is None:
  7616. return True
  7617. from backend.app.models.archive import PrintArchive
  7618. archive = await db.get(PrintArchive, item.archive_id)
  7619. if archive is None or not archive.filename:
  7620. return True
  7621. expected = _subtask_name_from_filename(archive.filename)
  7622. if not expected or _subtask_names_match(expected, observed):
  7623. return True
  7624. logging.getLogger(__name__).warning(
  7625. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7626. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7627. "printing rather than closing a run this event is not about.",
  7628. item.id,
  7629. expected,
  7630. archive.id,
  7631. archive.filename,
  7632. observed,
  7633. )
  7634. return False
  7635. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7636. """Spend the 3MF download cache on a still-empty fallback archive.
  7637. ``on_print_complete`` drops the cache as its first act, which deletes the
  7638. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7639. print ran and the archive never got one, this is the last moment those bytes
  7640. exist (#2957).
  7641. """
  7642. logger = logging.getLogger(__name__)
  7643. names = [
  7644. n
  7645. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7646. if n
  7647. ]
  7648. for name in names:
  7649. try:
  7650. cached = get_cached_3mf(printer_id, name)
  7651. # The print has ended: its completion prices the archive, so no
  7652. # print-start estimate is scheduled to race it.
  7653. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7654. return
  7655. except Exception as e:
  7656. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7657. # Longest the print's end waits for its file to be deleted from the SD card
  7658. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7659. async def _cleanup_sd_card_after_print(
  7660. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7661. ) -> None:
  7662. """Delete a finished print's file from the printer's SD card."""
  7663. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7664. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7665. # auto-start files found in root on power cycle, causing ghost prints.
  7666. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7667. try:
  7668. if subtask_name:
  7669. archive_filename: str | None = None
  7670. async with async_session() as db:
  7671. from backend.app.models.archive import PrintArchive
  7672. from backend.app.models.printer import Printer
  7673. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7674. printer = result.scalar_one_or_none()
  7675. if archive_id:
  7676. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7677. archive_filename = archive_row.scalar_one_or_none()
  7678. if printer:
  7679. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7680. from backend.app.utils.filename import derive_remote_filename
  7681. # Primary candidate: the exact path the dispatcher uploaded to
  7682. # (derived from archive.filename via the same rule as upload).
  7683. # Without it, a library row that ended up with a doubled
  7684. # .gcode.3mf (#1542) leaves the real file behind because the
  7685. # subtask_name + ext fallbacks below don't match what's on the
  7686. # SD card. Fallbacks remain for archive-less prints (subtask
  7687. # never resolved to an archive) and for older naming variants.
  7688. candidate_paths: list[str] = []
  7689. if archive_filename:
  7690. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7691. for ext in (".3mf", ".gcode"):
  7692. fallback = f"/{subtask_name}{ext}"
  7693. if fallback not in candidate_paths:
  7694. candidate_paths.append(fallback)
  7695. # Three outcomes track across all candidates so the final log
  7696. # line reflects what actually happened. The A1 in #1721 always
  7697. # ends here with ``any_not_found=True`` and the others False
  7698. # — its firmware auto-cleans the SD card before our cleanup
  7699. # runs, every candidate FTP-DELE returns 550, and the old
  7700. # code burned 3 retries × 2 s × 3 candidates per print
  7701. # logging a misleading "may linger" WARNING on a successful
  7702. # print.
  7703. any_deleted = False
  7704. any_real_failure = False
  7705. any_not_found = False
  7706. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7707. for remote_path in candidate_paths:
  7708. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7709. logger.info(
  7710. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7711. remote_path,
  7712. printer.name,
  7713. )
  7714. continue
  7715. # Retry only the FAILED case — 550 NOT_FOUND will never
  7716. # recover by waiting, so a "file isn't here" answer
  7717. # advances immediately to the next candidate without
  7718. # consuming the retry budget.
  7719. for attempt in range(1, 4):
  7720. try:
  7721. delete_result = await delete_file_async(
  7722. printer.ip_address,
  7723. printer.access_code,
  7724. remote_path,
  7725. printer_model=printer.model,
  7726. )
  7727. except Exception as e:
  7728. delete_result = DeleteResult.FAILED
  7729. logger.warning(
  7730. "SD card cleanup attempt %d/3 raised for %s: %s",
  7731. attempt,
  7732. remote_path,
  7733. e,
  7734. )
  7735. if delete_result == DeleteResult.DELETED:
  7736. any_deleted = True
  7737. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7738. break
  7739. if delete_result == DeleteResult.NOT_FOUND:
  7740. any_not_found = True
  7741. break # 550 will not recover; try next candidate
  7742. # FAILED: real error — retry with backoff, then give up
  7743. if attempt < 3:
  7744. await asyncio.sleep(2)
  7745. else:
  7746. any_real_failure = True
  7747. logger.warning(
  7748. "SD card cleanup failed after 3 attempts for %s "
  7749. "(network/auth/transient error — file may linger on SD card)",
  7750. remote_path,
  7751. )
  7752. if not any_deleted and not any_real_failure and any_not_found:
  7753. # Every candidate said "not here." Either the printer
  7754. # firmware swept the SD card itself (common on A1) or the
  7755. # dispatcher's upload path doesn't match our candidate
  7756. # rule. Either way: nothing to clean up, no warning.
  7757. logger.debug(
  7758. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7759. "(printer likely self-cleaned)",
  7760. printer.name,
  7761. )
  7762. except Exception as e:
  7763. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7764. async def on_print_complete(printer_id: int, data: dict):
  7765. """Handle print completion - update the archive status.
  7766. The printer counts as printing until the print's usage is booked (or this
  7767. ends), so the AMS remain% weight sync can't charge it a second time while
  7768. the usage tracker works (WU-3). Marked before the first await.
  7769. """
  7770. from backend.app.services.usage_tracker import done_completing, mark_completing
  7771. mark_completing(printer_id)
  7772. try:
  7773. await _close_out_print(printer_id, data)
  7774. finally:
  7775. done_completing(printer_id)
  7776. async def _close_out_print(printer_id: int, data: dict):
  7777. import time
  7778. logger = logging.getLogger(__name__)
  7779. start_time = time.time()
  7780. def log_timing(section: str):
  7781. elapsed = time.time() - start_time
  7782. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7783. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7784. # A kill-switch stop sends its provider notification immediately. Keep the
  7785. # task so the later notification path can await it and avoid a duplicate;
  7786. # if that immediate attempt failed, the regular completion path retries.
  7787. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7788. # Last chance before the bytes go: if this print's archive is still an empty
  7789. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7790. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7791. # below deletes the file (#2957).
  7792. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7793. # A pending cool-off retry has nothing left to recover for — the cache is
  7794. # about to be dropped and the print is over.
  7795. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7796. if retry_task and not retry_task.done():
  7797. retry_task.cancel()
  7798. # Drop the 3MF download cache for this printer (#972). The print is over,
  7799. # nothing else legitimately needs the bytes; keeping them would only risk
  7800. # handing a stale file to the next print if it reuses the same name.
  7801. clear_3mf_cache(printer_id)
  7802. try:
  7803. ws_data = {
  7804. "status": data.get("status"),
  7805. "filename": data.get("filename"),
  7806. "subtask_name": data.get("subtask_name"),
  7807. "timelapse_was_active": data.get("timelapse_was_active"),
  7808. }
  7809. await ws_manager.send_print_complete(printer_id, ws_data)
  7810. log_timing("WebSocket send_print_complete")
  7811. except Exception as e:
  7812. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7813. # Capture user info before clearing (needed for print log entry)
  7814. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7815. # Clear current print user tracking (Issue #206)
  7816. printer_manager.clear_current_print_user(printer_id)
  7817. # If the user explicitly stopped this print from the queue UI the printer will
  7818. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7819. # correct "print stopped" notification/email is sent instead of a failure alert.
  7820. _raw_status = data.get("status", "completed")
  7821. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7822. logger.info(
  7823. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7824. _raw_status,
  7825. printer_id,
  7826. )
  7827. data = {**data, "status": "cancelled"}
  7828. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7829. logger.info(
  7830. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7831. _raw_status,
  7832. printer_id,
  7833. )
  7834. data = {**data, "status": "cancelled", "_kill_switch": True}
  7835. _user_stopped_printers.discard(printer_id)
  7836. _kill_switch_stopped.discard(printer_id)
  7837. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7838. # may have left material on the bed: a user can cancel ten hours into a
  7839. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7840. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7841. # `_user_stopped_printers` is only populated when the user stops via the
  7842. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7843. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7844. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7845. # Auto Off power cycles and Bambuddy restarts.
  7846. try:
  7847. notify_live_activities.print_finished(printer_id, data)
  7848. except Exception:
  7849. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7850. _final_status = data.get("status", "completed")
  7851. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7852. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7853. # MQTT relay - publish print complete
  7854. try:
  7855. printer_info = printer_manager.get_printer(printer_id)
  7856. if printer_info:
  7857. await mqtt_relay.on_print_complete(
  7858. printer_id,
  7859. printer_info.name,
  7860. printer_info.serial_number,
  7861. data.get("filename", ""),
  7862. data.get("subtask_name", ""),
  7863. data.get("status", "completed"),
  7864. )
  7865. except Exception:
  7866. pass # Don't fail print complete callback if MQTT fails
  7867. filename = data.get("filename", "")
  7868. subtask_name = data.get("subtask_name", "")
  7869. if not filename and not subtask_name:
  7870. # Which print ended can't be told: the printer reported no name since
  7871. # Bambuddy started (a print that failed while preparing, a calibration).
  7872. # Charge nothing, but close the print session, which otherwise kept the
  7873. # AMS weight sync off until the next print (AS-5). A print archived as
  7874. # running is closed and charged by the reconnect reconcile.
  7875. logger.warning("Print complete without filename or subtask_name")
  7876. try:
  7877. from backend.app.services.usage_tracker import discard_session
  7878. async with async_session() as db:
  7879. await discard_session(db, printer_id)
  7880. except Exception as e:
  7881. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7882. return
  7883. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7884. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7885. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7886. # Find the archive for this print
  7887. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7888. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7889. archive_id = None
  7890. for key in possible_keys:
  7891. archive_id = _active_prints.pop(key, None)
  7892. if archive_id:
  7893. _owned_print_archive_ids.discard(archive_id)
  7894. logger.info("Found archive %s with key %s", archive_id, key)
  7895. # Also clean up the printer's other keys pointing to this archive;
  7896. # another printer's are a plate of it still printing there.
  7897. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  7898. for k in keys_to_remove:
  7899. _active_prints.pop(k, None)
  7900. break
  7901. # The archive bound when the print started, before the name search below.
  7902. # Only this one may give the finish-photo plate restore a height (#3240):
  7903. # the search matches names by substring.
  7904. bound_archive_id = archive_id
  7905. ending_job = str(data.get("subtask_id") or "").strip()
  7906. if not archive_id and ending_job not in ("", "0"):
  7907. # Not bound (a restart since the start): this job's run, open on the
  7908. # printer. Only by its job id: a run open there can be of the print
  7909. # running now, while the end is of an earlier one closed late (the
  7910. # restart's reconcile of a missed end).
  7911. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  7912. if archive_id:
  7913. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  7914. if not archive_id:
  7915. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7916. async with async_session() as db:
  7917. from backend.app.models.archive import PrintArchive
  7918. # Try matching by subtask_name (stored as print_name) first. The
  7919. # same name rule as the queue's completion check: a name inside
  7920. # another ("Clip" in "Cable Clip") is a different print, and the
  7921. # printer's underscores for spaces and truncation still match.
  7922. if subtask_name:
  7923. printing = await db.scalars(
  7924. select(PrintArchive)
  7925. .where(PrintArchive.printer_id == printer_id)
  7926. .where(PrintArchive.status == "printing")
  7927. .order_by(PrintArchive.created_at.desc())
  7928. )
  7929. # A print started from the printer's screen reports its file
  7930. # name, extensions included, as the subtask (#3009).
  7931. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7932. archive = next(
  7933. (
  7934. candidate
  7935. for candidate in printing
  7936. if any(
  7937. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7938. or (
  7939. candidate.filename
  7940. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7941. )
  7942. for name in reported
  7943. )
  7944. ),
  7945. None,
  7946. )
  7947. if archive:
  7948. archive_id = archive.id
  7949. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7950. # Also try by filename
  7951. if not archive_id and filename:
  7952. result = await db.execute(
  7953. select(PrintArchive)
  7954. .where(PrintArchive.printer_id == printer_id)
  7955. .where(PrintArchive.filename == filename)
  7956. .where(PrintArchive.status == "printing")
  7957. .order_by(PrintArchive.created_at.desc())
  7958. .limit(1)
  7959. )
  7960. archive = result.scalar_one_or_none()
  7961. if archive:
  7962. archive_id = archive.id
  7963. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7964. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7965. # closed below. The stranded-job closer gives up after five and closed it
  7966. # first, so the job's auto-off and its billing never ran. Inline rather
  7967. # than in the background, so the next job of the same file isn't released
  7968. # (and uploaded under the name being deleted) while the cleanup still
  7969. # works on it. A delete already sent may still finish in its FTP thread
  7970. # after the cutoff, as one past delete_file_async's own timeout always did.
  7971. try:
  7972. await asyncio.wait_for(
  7973. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7974. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7975. )
  7976. except TimeoutError:
  7977. logger.warning(
  7978. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7979. printer_id,
  7980. _SD_CLEANUP_BUDGET_SECONDS,
  7981. )
  7982. log_timing("SD card cleanup")
  7983. # Update queue item status early — must run before the archive_id early-return
  7984. # so queue items don't get stuck in "printing" when archive lookup fails.
  7985. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7986. queue_item_id = None
  7987. billing_run_id: str | None = None
  7988. billing_user_id: int | None = None
  7989. billing_cost_center_id: int | None = None
  7990. billing_plate_id: int | None = None
  7991. queue_status = None
  7992. queue_auto_off = False
  7993. try:
  7994. from backend.app.core.database import run_with_retry
  7995. from backend.app.models.print_queue import PrintQueueItem
  7996. async def _update_queue_status(db):
  7997. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7998. nonlocal queue_item_id, queue_status, queue_auto_off
  7999. result = await db.execute(
  8000. select(PrintQueueItem)
  8001. .where(PrintQueueItem.printer_id == printer_id)
  8002. .where(PrintQueueItem.status == "printing")
  8003. )
  8004. printing_items = list(result.scalars().all())
  8005. if len(printing_items) > 1:
  8006. logger.warning(
  8007. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8008. printer_id,
  8009. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8010. )
  8011. item = printing_items[0] if printing_items else None
  8012. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8013. return
  8014. if item:
  8015. queue_status = data.get("status", "completed")
  8016. # MQTT sends "aborted" for cancelled prints; normalise to
  8017. # "cancelled" so it matches the queue schema Literal.
  8018. if queue_status == "aborted":
  8019. queue_status = "cancelled"
  8020. item.status = queue_status
  8021. item.completed_at = datetime.now(timezone.utc)
  8022. if queue_status == "failed" and not item.error_message:
  8023. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8024. # Bump usage counters on the source library file so admins can
  8025. # sort by "last printed" and (eventually) auto-purge stale
  8026. # files — #1008.
  8027. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8028. await db.commit()
  8029. queue_item_id = item.id
  8030. billing_run_id = item.billing_run_id
  8031. billing_user_id = item.created_by_id
  8032. billing_cost_center_id = item.cost_center_id
  8033. billing_plate_id = item.plate_id
  8034. queue_auto_off = item.auto_off_after
  8035. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8036. await run_with_retry(_update_queue_status, label="queue status update")
  8037. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8038. # their own sessions and have their own error handling — no retry needed.
  8039. if queue_item_id is not None:
  8040. # Batch orders (#342): this run may have been the last one an order
  8041. # owed. Re-evaluate here rather than lazily on read, so a finished
  8042. # order reports itself complete without someone opening the page.
  8043. try:
  8044. from backend.app.services.print_batch import refresh_batch_status_for_item
  8045. async with async_session() as db:
  8046. await refresh_batch_status_for_item(db, queue_item_id)
  8047. await db.commit()
  8048. except Exception as e:
  8049. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8050. # MQTT relay - publish queue job completed
  8051. try:
  8052. printer_info = printer_manager.get_printer(printer_id)
  8053. await mqtt_relay.on_queue_job_completed(
  8054. job_id=queue_item_id,
  8055. filename=filename or subtask_name,
  8056. printer_id=printer_id,
  8057. printer_name=printer_info.name if printer_info else "Unknown",
  8058. status=queue_status,
  8059. )
  8060. except Exception:
  8061. pass # Don't fail if MQTT fails
  8062. # Check if queue is now empty and send notification
  8063. try:
  8064. from sqlalchemy import func as sa_func
  8065. async with async_session() as db:
  8066. count_result = await db.execute(
  8067. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8068. )
  8069. pending_count = count_result.scalar() or 0
  8070. if pending_count == 0:
  8071. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8072. completed_result = await db.execute(
  8073. select(sa_func.count(PrintQueueItem.id)).where(
  8074. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8075. PrintQueueItem.completed_at >= today_start,
  8076. )
  8077. )
  8078. completed_count = completed_result.scalar() or 1
  8079. await notification_service.on_queue_completed(
  8080. completed_count=completed_count,
  8081. db=db,
  8082. )
  8083. except Exception:
  8084. pass # Don't fail if notification fails
  8085. # Handle auto_off_after - power off printer if the queue item opted
  8086. # in. Delegates to the smart-plug manager so the off honours each
  8087. # plug's configured strategy (time delay or temperature threshold),
  8088. # is cancelled if the printer starts printing again, and never cuts
  8089. # power on a loaded print (#1890). Previously an inline block here
  8090. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8091. # timeout regardless of print state — cutting a touchscreen reprint.
  8092. if queue_auto_off:
  8093. try:
  8094. async with async_session() as db:
  8095. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8096. except Exception as e:
  8097. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8098. except Exception as e:
  8099. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8100. log_timing("Queue item update")
  8101. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8102. # Must run before archive_id early-return so it fires for all prints (including
  8103. # prints started from BambuStudio/touchscreen that have no archive).
  8104. if data.get("status") == "completed":
  8105. try:
  8106. from backend.app.api.routes.settings import get_setting
  8107. async with async_session() as db:
  8108. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8109. threshold = float(threshold_str) if threshold_str else 35.0
  8110. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8111. async with async_session() as db:
  8112. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8113. if providers:
  8114. _bed_cool_waiters[printer_id] = {
  8115. "threshold": threshold,
  8116. "filename": filename or subtask_name or "",
  8117. "registered_at": time.time(),
  8118. }
  8119. logger.info(
  8120. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8121. printer_id,
  8122. threshold,
  8123. )
  8124. else:
  8125. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8126. except Exception as e:
  8127. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8128. # Capture the slicer estimate before usage tracking runs. The tracker may
  8129. # update archive.cost with this run's measured cost; billing partial runs
  8130. # against that already-partial value would discount the charge twice.
  8131. billing_planned_grams: float | None = None
  8132. billing_base_cost: float | None = None
  8133. if archive_id:
  8134. try:
  8135. async with async_session() as db:
  8136. from backend.app.models.archive import PrintArchive
  8137. billing_archive = await db.get(PrintArchive, archive_id)
  8138. if billing_archive:
  8139. billing_path = (
  8140. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8141. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8142. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8143. billing_archive,
  8144. billing_path,
  8145. billing_plate_id
  8146. if billing_plate_id is not None
  8147. else _get_start_plate_id(printer_id, archive_id),
  8148. )
  8149. except Exception as e:
  8150. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8151. # --- Track filament consumption (must run before archive_id early-return so usage
  8152. # is recorded even when auto-archive is disabled) ---
  8153. usage_results: list[dict] = []
  8154. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8155. stored_ams_mapping = data.get("ams_mapping")
  8156. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8157. # Drained either way, like the plate below: left over, it would be read by
  8158. # the archive's next run, dispatched without a mapping.
  8159. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8160. if not stored_ams_mapping:
  8161. stored_ams_mapping = registered_ams_mapping
  8162. # Always drain the plate_id register on completion — the session already
  8163. # consumed it at print-start injection; leaving it would leak into the next
  8164. # print on the same archive_id (rare but possible with reprints) (#1697).
  8165. # Capture the popped value so the completion notification can scope the
  8166. # archive-level (summed-across-plates per #1593) filament + time totals
  8167. # down to the single plate that was actually printed (#1785).
  8168. notify_plate_id: int | None = None
  8169. if archive_id:
  8170. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8171. # The start estimate must not outlive the real cost written below (COST-4).
  8172. if archive_id:
  8173. await _settle_archive_cost_estimate(archive_id)
  8174. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8175. try:
  8176. async with async_session() as db:
  8177. from backend.app.api.routes.settings import get_setting
  8178. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8179. if not _spoolman_on or _spoolman_on.lower() != "true":
  8180. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8181. async with async_session() as db:
  8182. usage_results = await usage_on_print_complete(
  8183. printer_id,
  8184. data,
  8185. printer_manager,
  8186. db,
  8187. archive_id=archive_id,
  8188. ams_mapping=stored_ams_mapping,
  8189. )
  8190. if usage_results:
  8191. await ws_manager.broadcast(
  8192. {
  8193. "type": "spool_usage_logged",
  8194. "printer_id": printer_id,
  8195. "usage": usage_results,
  8196. }
  8197. )
  8198. log_timing("Usage tracker")
  8199. except Exception as e:
  8200. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8201. # Drop the print-start context unconditionally — the Spoolman branch above
  8202. # skips the internal tracker entirely, so nothing else would clear what
  8203. # print start captured, and a row surviving its print would be restored
  8204. # onto the next one after a restart.
  8205. try:
  8206. from backend.app.services.usage_tracker import discard_session
  8207. async with async_session() as db:
  8208. await discard_session(db, printer_id)
  8209. except Exception as e:
  8210. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8211. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8212. # A partial run's cost from the Spoolman spools it was charged to; the
  8213. # built-in inventory's comes in usage_results.
  8214. spoolman_run_cost: float | None = None
  8215. if archive_id:
  8216. if data.get("status") == "completed":
  8217. try:
  8218. await _report_spoolman_usage(printer_id, archive_id)
  8219. log_timing("Spoolman usage report")
  8220. except Exception as e:
  8221. logger.warning("Spoolman usage reporting failed: %s", e)
  8222. else:
  8223. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8224. try:
  8225. async with async_session() as db:
  8226. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8227. printer_id,
  8228. archive_id,
  8229. db,
  8230. last_layer_num=data.get("last_layer_num"),
  8231. last_progress=data.get("last_progress"),
  8232. status=data.get("status") or "failed",
  8233. )
  8234. except Exception as e:
  8235. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8236. await _release_archived_spoolman_slots(printer_id)
  8237. log_timing("Filament usage tracking")
  8238. if not archive_id:
  8239. # The printer's own calibration run has no archive by design, so this
  8240. # arrives here every time one finishes. Returning before the no-archive
  8241. # notification keeps a calibration from being announced as a finished
  8242. # print. Everything above this point has already run — the plate-clear
  8243. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8244. # notification is skipped.
  8245. if is_internal_printer_job(filename, subtask_name):
  8246. logger.info(
  8247. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8248. filename,
  8249. subtask_name,
  8250. )
  8251. return
  8252. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8253. # Still send print-complete/failed/stopped notifications even without an archive.
  8254. # Try to enrich with queue/library-file data so user-specific emails work too.
  8255. async def _notify_no_archive():
  8256. try:
  8257. async with async_session() as db:
  8258. from backend.app.models.library import LibraryFile
  8259. from backend.app.models.print_queue import PrintQueueItem
  8260. from backend.app.models.printer import Printer
  8261. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8262. printer_obj = result.scalar_one_or_none()
  8263. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8264. # Only the queue item this completion itself closed (the
  8265. # reconciliation above, which checks the run belongs to it).
  8266. # A print started outside Bambuddy closed none, and must not
  8267. # borrow an earlier job's owner, email or times.
  8268. no_archive_data: dict | None = None
  8269. try:
  8270. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8271. if queue_item:
  8272. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8273. # How long it really ran, as the archive path reports it (#1198).
  8274. started = to_naive_utc(queue_item.started_at)
  8275. ended = to_naive_utc(queue_item.completed_at)
  8276. # Not for a completion reconciled at reconnect: it
  8277. # ended at an unknown time while the printer was
  8278. # offline, and "now" is the reconnect (DB-C9).
  8279. if (
  8280. not data.get("_reconciled")
  8281. and started
  8282. and ended
  8283. and (ended - started).total_seconds() > 0
  8284. ):
  8285. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8286. # Estimated time: the queue item caches it from its
  8287. # archive or library file; otherwise read the library
  8288. # file's metadata (LibraryFile has no column for it).
  8289. if queue_item.print_time_seconds:
  8290. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8291. elif queue_item.library_file_id:
  8292. lib_result = await db.execute(
  8293. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8294. )
  8295. lib_file = lib_result.scalar_one_or_none()
  8296. estimate = (
  8297. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8298. )
  8299. if estimate:
  8300. no_archive_data["print_time_seconds"] = estimate
  8301. except Exception as lookup_err:
  8302. logger.debug(
  8303. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8304. )
  8305. # Enrich with usage tracker results (captured in enclosing scope)
  8306. if usage_results:
  8307. if no_archive_data is None:
  8308. no_archive_data = {}
  8309. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8310. if total_from_usage > 0:
  8311. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8312. no_archive_data["usage_results"] = usage_results
  8313. # Try MQTT remaining_time for print duration when no queue/library data
  8314. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8315. mqtt_remaining = data.get("remaining_time")
  8316. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8317. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8318. ps = data.get("status", "completed")
  8319. logger.info(
  8320. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8321. )
  8322. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8323. await notification_service.on_print_complete(
  8324. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8325. )
  8326. else:
  8327. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8328. # Send user-specific email if we have a created_by_id
  8329. if no_archive_data and no_archive_data.get("created_by_id"):
  8330. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8331. await _dispatch_user_print_email(
  8332. ps,
  8333. no_archive_data["created_by_id"],
  8334. p_name,
  8335. raw_filename,
  8336. db,
  8337. )
  8338. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8339. except Exception as e:
  8340. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8341. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8342. return
  8343. log_timing("Archive lookup")
  8344. # Update archive status
  8345. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8346. try:
  8347. async with async_session() as db:
  8348. service = ArchiveService(db)
  8349. status = data.get("status", "completed")
  8350. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8351. if hms_errors:
  8352. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8353. failure_reason = derive_failure_reason(status, hms_errors)
  8354. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8355. # A reconciled completion closes out a stale archive at
  8356. # reconnect — it is not a user action, so don't mislabel it
  8357. # "userCancelled". It shares the stale-cleanup path's key
  8358. # (issue #2974) and records that the real end time is unknown,
  8359. # which is also why its logged duration is 0 (#2592). A failed
  8360. # one the printer's errors explain keeps their reason (#3310).
  8361. failure_reason = "noStatusUpdate"
  8362. elif data.get("_kill_switch"):
  8363. # Not the user's cancel: the kill switch stopped a print that did
  8364. # not come from Bambuddy.
  8365. failure_reason = "killSwitch"
  8366. if failure_reason:
  8367. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8368. elif status == "failed" and hms_errors:
  8369. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8370. await service.update_archive_status(
  8371. archive_id,
  8372. status=status,
  8373. completed_at=(
  8374. # A reconciled completed print ended at an estimated time,
  8375. # not at the reconnect (#3310).
  8376. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8377. if status in ("completed", "failed", "aborted", "cancelled")
  8378. else None
  8379. ),
  8380. failure_reason=failure_reason,
  8381. )
  8382. logger.info(
  8383. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8384. )
  8385. await ws_manager.send_archive_updated(
  8386. {
  8387. "id": archive_id,
  8388. "status": status,
  8389. }
  8390. )
  8391. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8392. # MQTT relay - publish archive updated
  8393. try:
  8394. await mqtt_relay.on_archive_updated(
  8395. archive_id=archive_id,
  8396. print_name=filename or subtask_name,
  8397. status=status,
  8398. )
  8399. except Exception:
  8400. pass # Don't fail if MQTT fails
  8401. except Exception as e:
  8402. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8403. # Continue with other operations even if archive update fails
  8404. log_timing("Archive status update")
  8405. # Apply finance wallet charge or release reservations once. For all partial
  8406. # terminal states (failed, aborted at the printer display, or cancelled via
  8407. # Bambuddy) use this run's measured spool delta, falling back to the last
  8408. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8409. # estimate and therefore cannot represent an interrupted run.
  8410. try:
  8411. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8412. async with async_session() as db:
  8413. from backend.app.models.archive import PrintArchive
  8414. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8415. archive = await db.get(PrintArchive, archive_id)
  8416. if archive and billing_run_id is None:
  8417. billing_run_id = getattr(archive, "billing_run_id", None)
  8418. if archive and archive.created_by_id is None and _print_user_info:
  8419. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8420. await db.flush()
  8421. run_status = data.get("status", "completed")
  8422. last_progress = data.get("last_progress")
  8423. if last_progress is None:
  8424. last_progress = data.get("progress")
  8425. actual_run_grams = _compute_run_filament_grams(
  8426. run_status,
  8427. billing_planned_grams,
  8428. last_progress,
  8429. usage_results,
  8430. )
  8431. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8432. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8433. charged = await apply_print_charge_for_archive(
  8434. db,
  8435. archive_id,
  8436. charged_user_id=billing_user_id,
  8437. cost_center_id=(
  8438. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8439. ),
  8440. print_queue_id=queue_item_id,
  8441. print_run_id=billing_run_id,
  8442. base_cost_override=billing_base_cost,
  8443. filament_usage=filament_usage,
  8444. )
  8445. await db.commit()
  8446. if charged:
  8447. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8448. except Exception as e:
  8449. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8450. printer_info = printer_manager.get_printer(printer_id)
  8451. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8452. billing_filename = filename or subtask_name or "Unknown"
  8453. billing_error = str(e)
  8454. try:
  8455. await ws_manager.broadcast(
  8456. {
  8457. "type": "billing_charge_failed",
  8458. "printer_id": printer_id,
  8459. "printer_name": billing_printer_name,
  8460. "filename": billing_filename,
  8461. "archive_id": archive_id,
  8462. }
  8463. )
  8464. except Exception as notification_error:
  8465. logger.error(
  8466. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8467. archive_id,
  8468. notification_error,
  8469. )
  8470. async def _notify_billing_charge_failed() -> None:
  8471. try:
  8472. async with async_session() as notification_db:
  8473. await notification_service.on_billing_charge_failed(
  8474. printer_id,
  8475. billing_printer_name,
  8476. billing_filename,
  8477. archive_id,
  8478. billing_error,
  8479. notification_db,
  8480. )
  8481. except Exception as provider_error:
  8482. logger.error(
  8483. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8484. archive_id,
  8485. provider_error,
  8486. exc_info=True,
  8487. )
  8488. spawn_background_task(
  8489. _notify_billing_charge_failed(),
  8490. name=f"billing-charge-failed-{archive_id}",
  8491. )
  8492. log_timing("Finance charge update")
  8493. # Write independent print log entry (separate table, never touches archives)
  8494. # The run's id, for the energy work below: the archive's newest run is
  8495. # the one started last, which with plates of it on two printers need not
  8496. # be the one that just ended.
  8497. completed_run_id: int | None = None
  8498. try:
  8499. async with async_session() as db:
  8500. from backend.app.models.archive import PrintArchive
  8501. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8502. archive = await db.get(PrintArchive, archive_id)
  8503. if archive is None:
  8504. # Deleted while it printed: its run has nothing left to end on.
  8505. await discard_open_runs(db, printer_id)
  8506. await db.commit()
  8507. if archive:
  8508. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8509. # source archive row rather than creating a new one, so an
  8510. # archive that was auto-created from a printer-initiated
  8511. # print (created_by_id=NULL) would otherwise stay unattributed
  8512. # forever. When we have a print-session user AND the archive
  8513. # has no attribution yet, credit the current user. Never
  8514. # overwrite an existing attribution — the original uploader
  8515. # keeps ownership.
  8516. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8517. if archive.created_by_id is None and _print_user_id is not None:
  8518. archive.created_by_id = _print_user_id
  8519. p_info = printer_manager.get_printer(printer_id)
  8520. # Per-run actuals — written to PrintLogEntry so stats reflect
  8521. # what THIS print actually used, not the source archive's
  8522. # first-run values (#1378). Helper handles the partial-print
  8523. # math (failed / cancelled / stopped get scaled to progress
  8524. # or to tracked spool deltas).
  8525. _run_status = data.get("status", "completed")
  8526. # #2614: scope the per-run estimate to the printed plate. For a
  8527. # multi-plate 3MF dispatched one plate at a time, the archive's
  8528. # filament/cost are the whole-file totals; the PrintLogEntry must
  8529. # reflect only this plate. No effect on single-plate archives (the
  8530. # plate estimate equals the whole-file value) or on the tracker
  8531. # path (measured spool deltas win in _compute_run_filament_grams).
  8532. _est_full_path = (
  8533. app_settings.base_dir / archive.file_path if archive.file_path else None
  8534. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8535. # The plate that printed, as billing reads it: a reprint of
  8536. # another plate must not log the archive's first plate.
  8537. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8538. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8539. if _run_plate_id is None:
  8540. _run_plate_id = archive.plate_id
  8541. _run_grams = _compute_run_filament_grams(
  8542. _run_status,
  8543. _est_grams,
  8544. data.get("last_progress", data.get("progress")),
  8545. usage_results,
  8546. )
  8547. # Per-run cost — prefer usage_results sum. For partial prints
  8548. # we deliberately skip the topup-to-estimate logic in
  8549. # usage_tracker (which assumes the print completed); the raw
  8550. # tracked-spool sum is closer to what THIS run actually cost.
  8551. _run_cost: float | None = None
  8552. if usage_results:
  8553. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8554. if _run_cost is None and _run_status != "completed":
  8555. _run_cost = spoolman_run_cost
  8556. if _run_cost is None and _run_status == "completed":
  8557. _run_cost = _est_cost
  8558. from backend.app.models.printer import Printer as _Printer
  8559. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8560. run_entry = await write_log_entry(
  8561. db,
  8562. archive_id=archive.id,
  8563. # Captured by _update_queue_status above; None for
  8564. # printer-initiated prints with no queue row. Batch
  8565. # cost/energy roll-up joins on it (#342).
  8566. queue_item_id=queue_item_id,
  8567. status=_run_status,
  8568. print_name=archive.print_name,
  8569. # The plate this run printed, as the estimate above takes
  8570. # it; the archive's own is the latest run's.
  8571. plate_id=_run_plate_id,
  8572. printer_name=p_info.name if p_info else None,
  8573. printer_id=printer_id,
  8574. started_at=archive.started_at,
  8575. completed_at=archive.completed_at,
  8576. filament_type=archive.filament_type,
  8577. filament_color=archive.filament_color,
  8578. filament_used_grams=_run_grams,
  8579. cost=_run_cost,
  8580. wear_cost_per_hour=_wear_rate,
  8581. failure_reason=archive.failure_reason,
  8582. thumbnail_path=archive.thumbnail_path,
  8583. created_by_id=archive.created_by_id,
  8584. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8585. # Reconciled completions have an unknown real end time —
  8586. # log 0 duration instead of the whole disconnect gap (#2592),
  8587. # unless it was estimated (#3310).
  8588. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8589. # Its time is the estimate or nothing, never measured (#3310).
  8590. duration_unmeasured=bool(data.get("_reconciled")),
  8591. )
  8592. await record_archive_wear(db, archive, run_entry)
  8593. await db.commit()
  8594. completed_run_id = run_entry.id
  8595. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8596. except Exception as e:
  8597. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8598. log_timing("Print log entry")
  8599. # Run slow operations as background tasks to avoid blocking the event loop
  8600. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8601. async def _background_energy_calculation():
  8602. """Calculate and save energy usage in background.
  8603. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8604. backend restart no longer loses per-print energy data).
  8605. """
  8606. try:
  8607. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8608. async with async_session() as db:
  8609. from backend.app.models.archive import PrintArchive
  8610. archive = await db.get(PrintArchive, archive_id)
  8611. if archive is None:
  8612. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8613. return
  8614. starting_kwh = archive.energy_start_kwh
  8615. if starting_kwh is None:
  8616. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  8617. return
  8618. candidates = await energy_plug_candidates(db, printer_id)
  8619. if not candidates:
  8620. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8621. return
  8622. # Same ordering as the start reading, so the delta below is
  8623. # against the counter that produced `starting_kwh` (#2859).
  8624. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8625. if selected is None:
  8626. logger.warning(
  8627. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8628. printer_id,
  8629. ", ".join(plug.name for plug in candidates),
  8630. )
  8631. return
  8632. plug, energy = selected
  8633. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8634. energy_used = round(energy["total"] - starting_kwh, 4)
  8635. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8636. if energy_used < 0:
  8637. logger.warning(
  8638. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8639. archive_id,
  8640. starting_kwh,
  8641. energy["total"],
  8642. )
  8643. return
  8644. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8645. # Each hour of the print at the price of that hour (#1251). If
  8646. # that fails, the last price known, as before, rather than no
  8647. # energy at all. Read first: the session may be unusable after.
  8648. last_price = await stored_price(db)
  8649. try:
  8650. energy_cost_value = round(
  8651. await print_energy_cost(
  8652. db,
  8653. plug_id=archive.energy_start_plug_id,
  8654. start_at=archive.energy_start_at,
  8655. start_kwh=starting_kwh,
  8656. start_price=archive.energy_start_price,
  8657. end_kwh=energy["total"],
  8658. end_plug_id=plug.id,
  8659. price_now=await current_price(db),
  8660. ),
  8661. 3,
  8662. )
  8663. except Exception as e:
  8664. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8665. energy_cost_value = round(energy_used * last_price, 3)
  8666. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8667. # reprint doesn't visually clobber the source archive's energy data
  8668. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8669. from sqlalchemy import func
  8670. from backend.app.models.print_log import PrintLogEntry
  8671. existing_runs = await db.scalar(
  8672. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8673. )
  8674. if (existing_runs or 0) <= 1:
  8675. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8676. # we just wrote for THIS print. Either way it's the first run.
  8677. archive.energy_kwh = energy_used
  8678. archive.energy_cost = energy_cost_value
  8679. # Backfill the latest PrintLogEntry for this archive with energy
  8680. # (write_log_entry above ran before this background task completed,
  8681. # so energy fields are still NULL on that row).
  8682. if completed_run_id is not None:
  8683. run_row = await db.get(PrintLogEntry, completed_run_id)
  8684. else:
  8685. latest_run = await db.execute(
  8686. select(PrintLogEntry)
  8687. .where(PrintLogEntry.archive_id == archive_id)
  8688. .order_by(PrintLogEntry.id.desc())
  8689. .limit(1)
  8690. )
  8691. run_row = latest_run.scalar_one_or_none()
  8692. if run_row is not None:
  8693. run_row.energy_kwh = energy_used
  8694. run_row.energy_cost = energy_cost_value
  8695. await db.commit()
  8696. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8697. except Exception as e:
  8698. logger.warning("[ENERGY-BG] Failed: %s", e)
  8699. async def _background_finish_photo() -> str | None:
  8700. """Capture finish photo in background. Returns photo filename if captured."""
  8701. # #2547: set once this function has raised the plate itself (the
  8702. # timelapse path, where the moment producer returned without doing it).
  8703. # Declared out here so the `finally` can lower it again no matter where
  8704. # the capture below fails.
  8705. plate_restored_z: float | None = None
  8706. try:
  8707. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8708. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8709. # Read phase: settings + printer + archive in a short session, released
  8710. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8711. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8712. # tens of seconds; holding this session across it pinned one pooled
  8713. # connection idle-in-transaction per finishing print (issue #2572).
  8714. async with async_session() as db:
  8715. from backend.app.api.routes.settings import get_setting
  8716. from backend.app.models.archive import PrintArchive
  8717. from backend.app.models.printer import Printer
  8718. capture_enabled = await get_setting(db, "capture_finish_photo")
  8719. if capture_enabled is not None and capture_enabled.lower() != "true":
  8720. return None
  8721. if not archive_id:
  8722. return None
  8723. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8724. archive = (
  8725. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8726. ).scalar_one_or_none()
  8727. if not printer or not archive:
  8728. return None
  8729. import uuid
  8730. from datetime import datetime
  8731. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8732. if not archive.file_path:
  8733. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8734. archive_dir = resolve_archive_dir(archive)
  8735. photo_filename = None
  8736. # Prefer the timelapse last-frame source when a timelapse was
  8737. # recording — it captures the moment after the toolhead parks
  8738. # but before the bed drops, which the live-camera grab below
  8739. # would miss (#1397). Skipped for external cameras (those have
  8740. # their own framing and don't see a Bambu timelapse). Only
  8741. # runs when the USER explicitly enabled timelapse for this
  8742. # print — #1721 removed Bambuddy's force-on at dispatch
  8743. # because it caused per-layer nozzle parking on Smooth-mode
  8744. # slicer profiles.
  8745. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8746. printer.external_camera_enabled and printer.external_camera_url
  8747. )
  8748. timelapse_still_pending = False
  8749. if prefer_timelapse_source:
  8750. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8751. archive_id=archive_id,
  8752. archive_dir=archive_dir,
  8753. rotation=getattr(printer, "camera_rotation", 0),
  8754. )
  8755. # #1721: replacement framing path — on_finish_photo_moment
  8756. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8757. # parked, bed not yet dropped) and cached the JPEG bytes in
  8758. # _stage22_finish_frames. Consume them now so the saved photo
  8759. # has the better framing instead of the post-bed-drop angle
  8760. # the live-camera fallback below would give.
  8761. if not photo_filename:
  8762. # #1790: on the FINISH-state fallback path the producer
  8763. # task is dispatched back-to-back with this consumer, so
  8764. # a bare pop would race past with an empty result and
  8765. # the RTSP fallback below would collide with the
  8766. # producer's still-in-flight grab (single-client RTSP
  8767. # on Bambu printers). Wait for the producer to finish
  8768. # or give up before touching the cache.
  8769. #
  8770. # #2547: 20s was enough when the producer only ever grabbed a
  8771. # frame. It now also raises the plate first, which costs the
  8772. # settle window before the grab even starts — so the budget has
  8773. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8774. # under the notification's own photo wait below.
  8775. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8776. if in_flight is not None:
  8777. try:
  8778. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8779. except TimeoutError:
  8780. logger.warning(
  8781. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8782. printer_id,
  8783. )
  8784. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8785. if cached_frame:
  8786. # Already rotated by the producer (#2708) — rotating again
  8787. # here would undo the fix on the banked-frame path, whose
  8788. # bytes reach the cache having been rotated once already.
  8789. photos_dir = archive_dir / "photos"
  8790. photos_dir.mkdir(parents=True, exist_ok=True)
  8791. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8792. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8793. photo_path = photos_dir / photo_filename
  8794. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8795. logger.info(
  8796. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8797. photo_filename,
  8798. len(cached_frame),
  8799. )
  8800. # #2547: the timelapse path reaches the live grab below whenever the
  8801. # video hasn't landed in time — the documented usual outcome on
  8802. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8803. # returned early for those prints without raising the plate, so
  8804. # without this the photo that actually ships in the notification is
  8805. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8806. # asked us to fix. The archive still gets the better video frame
  8807. # later; this is about the image the user is sent.
  8808. #
  8809. # Gated on `timelapse_was_active` precisely because that is the
  8810. # condition under which the producer skipped. On every other path it
  8811. # has already raised and lowered the plate, and repeating that here
  8812. # would be a second pointless round trip.
  8813. if (
  8814. not photo_filename
  8815. and data.get("timelapse_was_active")
  8816. and not print_dispatch_context.end_gcode_injected(printer_id)
  8817. ):
  8818. try:
  8819. async with async_session() as db:
  8820. from backend.app.api.routes.settings import get_setting
  8821. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8822. if restore_setting is None or restore_setting.lower() == "true":
  8823. max_z = await _max_z_for_current_print(
  8824. printer_id, data, logger, bound_archive_id, notify_plate_id
  8825. )
  8826. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8827. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8828. plate_restored_z = max_z
  8829. except Exception as e:
  8830. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8831. # Fallback chain: external camera → buffered live frame →
  8832. # fresh RTSP capture. Only runs if the timelapse path above
  8833. # didn't already produce a photo.
  8834. # Chamber light for the live capture below (#1655).
  8835. async with camera_light(printer if not photo_filename else None):
  8836. if not photo_filename:
  8837. if printer.external_camera_enabled and printer.external_camera_url:
  8838. logger.info("[PHOTO-BG] Using external camera")
  8839. from backend.app.api.routes.camera import live_frame_for_capture
  8840. from backend.app.services.external_camera import capture_frame
  8841. # #2707: the second half of the finish-photo failure — the
  8842. # pre-capture and this fallback both collided with the live
  8843. # view. None here continues down the fallback chain.
  8844. defer, buffered = live_frame_for_capture(printer_id)
  8845. if defer:
  8846. frame_data = buffered
  8847. else:
  8848. frame_data = await capture_frame(
  8849. printer.external_camera_url,
  8850. printer.external_camera_type or "mjpeg",
  8851. snapshot_url=printer.external_camera_snapshot_url,
  8852. )
  8853. if frame_data:
  8854. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8855. photos_dir = archive_dir / "photos"
  8856. photos_dir.mkdir(parents=True, exist_ok=True)
  8857. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8858. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8859. photo_path = photos_dir / photo_filename
  8860. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8861. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8862. else:
  8863. # Check if camera stream is active - use buffered frame to avoid freeze
  8864. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8865. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8866. active_chamber_for_printer = [
  8867. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8868. ]
  8869. buffered_frame = get_buffered_frame(printer_id)
  8870. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8871. # Use frame from active stream
  8872. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8873. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8874. photos_dir = archive_dir / "photos"
  8875. photos_dir.mkdir(parents=True, exist_ok=True)
  8876. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8877. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8878. photo_path = photos_dir / photo_filename
  8879. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8880. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8881. else:
  8882. # No active stream - capture new frame
  8883. from backend.app.services.camera import capture_finish_photo
  8884. photo_filename = await capture_finish_photo(
  8885. printer_id=printer_id,
  8886. ip_address=printer.ip_address,
  8887. access_code=printer.access_code,
  8888. model=printer.model,
  8889. archive_dir=archive_dir,
  8890. rotation=getattr(printer, "camera_rotation", 0),
  8891. )
  8892. # Write phase: attach the photo in a fresh short-lived session.
  8893. if photo_filename:
  8894. async with async_session() as db:
  8895. from backend.app.models.archive import PrintArchive
  8896. arch = await db.get(PrintArchive, archive_id)
  8897. if arch is not None:
  8898. photos = arch.photos or []
  8899. photos.append(photo_filename)
  8900. arch.photos = photos
  8901. await db.commit()
  8902. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8903. # The short wait above is bounded so a slow printer can't hold up
  8904. # the print-complete notification, which is what the caller is
  8905. # blocking on. When it ran out with the video still on its way,
  8906. # keep waiting off to the side and add the better frame to the
  8907. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8908. # users, whose videos routinely take minutes to transfer, never get
  8909. # the pre-bed-drop framing this path exists to provide.
  8910. #
  8911. # Spawned here rather than at the point the wait gave up: both this
  8912. # function and the upgrade do a read-modify-write on `photos`, and
  8913. # the live-camera fallback above can take tens of seconds. Starting
  8914. # the upgrade before that write means the two can interleave and one
  8915. # silently drops the other's entry, leaving a JPEG on disk that the
  8916. # gallery never lists.
  8917. if timelapse_still_pending:
  8918. spawn_background_task(
  8919. _upgrade_finish_photo_from_timelapse(
  8920. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8921. ),
  8922. name=f"finish-photo-upgrade-{archive_id}",
  8923. )
  8924. return photo_filename
  8925. except Exception as e:
  8926. logger.warning("[PHOTO-BG] Failed: %s", e)
  8927. return None
  8928. finally:
  8929. # #2547: we raised the plate, so we owe the move back down — even if
  8930. # the capture in between threw. Otherwise the user finds the print
  8931. # pinned under the nozzle.
  8932. if plate_restored_z is not None:
  8933. try:
  8934. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8935. except Exception as e:
  8936. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8937. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8938. # Photo capture task - result will be used by notifications
  8939. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8940. log_timing("Background tasks scheduled (energy, photo)")
  8941. # Also run smart plug, notifications, and maintenance as background tasks
  8942. print_status = data.get("status", "completed")
  8943. async def _background_smart_plug():
  8944. """Handle smart plug automation in background."""
  8945. try:
  8946. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8947. async with async_session() as db:
  8948. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8949. logger.info("[AUTO-OFF-BG] Completed")
  8950. except Exception as e:
  8951. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8952. async def _background_notifications(finish_photo_filename: str | None = None):
  8953. """Send print complete notifications in background."""
  8954. try:
  8955. logger.info(
  8956. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8957. )
  8958. async with async_session() as db:
  8959. from backend.app.models.archive import PrintArchive
  8960. from backend.app.models.printer import Printer
  8961. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8962. printer = result.scalar_one_or_none()
  8963. printer_name = printer.name if printer else f"Printer {printer_id}"
  8964. archive_data = None
  8965. if archive_id:
  8966. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8967. archive = archive_result.scalar_one_or_none()
  8968. if archive:
  8969. # Actual elapsed time from started_at/completed_at when both are
  8970. # populated (every terminal status sets completed_at after #1198).
  8971. # Falls back to None so the notification path can decide whether to
  8972. # render the slicer estimate as a last resort.
  8973. actual_time_seconds = None
  8974. # Unknown for a completion reconciled at reconnect: the
  8975. # print ended while the printer was offline and
  8976. # completed_at is the reconnect, so the gap would read
  8977. # as the duration -- 14 h for a night offline (DB-C9).
  8978. # An estimated end (#3310) gives the estimate.
  8979. if (
  8980. archive.started_at
  8981. and archive.completed_at
  8982. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  8983. ):
  8984. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8985. if elapsed > 0:
  8986. actual_time_seconds = int(elapsed)
  8987. archive_data = {
  8988. "print_time_seconds": archive.print_time_seconds,
  8989. "actual_time_seconds": actual_time_seconds,
  8990. "actual_filament_grams": archive.filament_used_grams,
  8991. "failure_reason": archive.failure_reason,
  8992. "created_by_id": archive.created_by_id,
  8993. }
  8994. # Scale filament usage for partial prints
  8995. if print_status != "completed" and archive.filament_used_grams:
  8996. progress = data.get("progress") or 0
  8997. scale = _partial_progress_scale(progress)
  8998. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8999. archive_data["progress"] = progress
  9000. # Pass per-slot data from archive.extra_data
  9001. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9002. slots = archive.extra_data["filament_slots"]
  9003. if print_status != "completed":
  9004. scale = _partial_progress_scale(data.get("progress"))
  9005. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9006. archive_data["filament_slots"] = slots
  9007. # Scope project-summed totals down to the plate that was
  9008. # actually printed — see _scope_notification_archive_data_to_plate
  9009. # for the why (#1785).
  9010. archive_data = _scope_notification_archive_data_to_plate(
  9011. archive_data,
  9012. archive.file_path,
  9013. notify_plate_id,
  9014. print_status,
  9015. data.get("progress"),
  9016. app_settings.base_dir,
  9017. )
  9018. # Enrich filament_grams from usage_results when archive has no 3MF data
  9019. if not archive_data.get("actual_filament_grams") and usage_results:
  9020. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9021. if total_from_usage > 0:
  9022. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9023. # Pass usage tracker results for AMS slot info in notifications
  9024. if usage_results:
  9025. archive_data["usage_results"] = usage_results
  9026. # Add finish photo URL and image bytes if available
  9027. if finish_photo_filename:
  9028. photo_url, photo_bytes = await _finish_photo_for_notification(
  9029. db, archive, archive_id, finish_photo_filename
  9030. )
  9031. if photo_url:
  9032. archive_data["finish_photo_url"] = photo_url
  9033. if photo_bytes:
  9034. archive_data["image_data"] = photo_bytes
  9035. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9036. await notification_service.on_print_complete(
  9037. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9038. )
  9039. else:
  9040. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9041. # Post-print outcome confirmation (#1898). Runs in this
  9042. # background task so the finish photo fetched above rides
  9043. # along with the prompt.
  9044. if print_status == "completed" and archive_id:
  9045. await _dispatch_outcome_confirmation_safely(
  9046. db, printer_id, printer_name, data, archive_id, archive_data
  9047. )
  9048. # Send user-specific email notification
  9049. if archive_data:
  9050. created_by_id = archive_data.get("created_by_id")
  9051. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9052. await _dispatch_user_print_email(
  9053. print_status,
  9054. created_by_id,
  9055. printer_name,
  9056. raw_filename,
  9057. db,
  9058. image_data=archive_data.get("image_data"),
  9059. finish_photo_url=archive_data.get("finish_photo_url"),
  9060. )
  9061. logger.info("[NOTIFY-BG] Completed")
  9062. except Exception as e:
  9063. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9064. async def _background_maintenance_check():
  9065. """Check for maintenance due in background."""
  9066. if print_status != "completed":
  9067. return
  9068. try:
  9069. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9070. async with async_session() as db:
  9071. from backend.app.models.printer import Printer
  9072. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9073. printer = result.scalar_one_or_none()
  9074. printer_name = printer.name if printer else f"Printer {printer_id}"
  9075. await ensure_default_types(db)
  9076. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9077. attention = [
  9078. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9079. ]
  9080. items_needing_attention = [
  9081. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9082. for item in attention
  9083. ]
  9084. if items_needing_attention:
  9085. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9086. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9087. # MQTT relay - publish maintenance alerts
  9088. for item in attention:
  9089. current_value, threshold, unit = maintenance_alert_values(item)
  9090. try:
  9091. await mqtt_relay.on_maintenance_alert(
  9092. printer_id=printer_id,
  9093. printer_name=printer_name,
  9094. maintenance_type=item.maintenance_type_name,
  9095. current_value=current_value,
  9096. threshold=threshold,
  9097. unit=unit,
  9098. )
  9099. except Exception:
  9100. pass # Don't fail if MQTT fails
  9101. else:
  9102. logger.info("[MAINT-BG] Completed (no items need attention)")
  9103. except Exception as e:
  9104. logger.warning("[MAINT-BG] Failed: %s", e)
  9105. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9106. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9107. # Notification task waits for photo capture to complete first (with timeout).
  9108. # When a timelapse was recording, photo sourcing polls the per-print
  9109. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9110. # carries the correct bed-up photo instead of falling through to the
  9111. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9112. #
  9113. # #2547: both budgets now have to cover a plate restore as well.
  9114. #
  9115. # Without timelapse, the wait is on the moment producer, which raises the
  9116. # plate before its grab — so this has to outlast that producer's own budget.
  9117. #
  9118. # With timelapse, the capture polls up to
  9119. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9120. # falls back to a live grab, which is the case that raises the plate. At the
  9121. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9122. # restore would have moved the plate for a photo nobody waited for.
  9123. photo_wait_timeout = (
  9124. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9125. if data.get("timelapse_was_active")
  9126. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9127. )
  9128. async def _photo_then_notify():
  9129. """Wait for photo capture, then send notification with photo URL."""
  9130. finish_photo = None
  9131. try:
  9132. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9133. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9134. except TimeoutError:
  9135. logger.warning(
  9136. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9137. photo_wait_timeout,
  9138. )
  9139. except Exception as e:
  9140. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9141. try:
  9142. await _background_notifications(finish_photo)
  9143. except Exception as e:
  9144. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9145. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9146. # Stitch external camera layer timelapse if session was active
  9147. print_status = data.get("status", "completed")
  9148. async def _background_layer_timelapse():
  9149. """Stitch layer timelapse and attach to archive."""
  9150. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9151. try:
  9152. if print_status == "completed":
  9153. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9154. # The run the frames belong to, read before the stitch: it can
  9155. # take long enough for the archive to start printing again.
  9156. run_started_at = None
  9157. if archive_id:
  9158. async with async_session() as db:
  9159. run_archive = await ArchiveService(db).get_archive(archive_id)
  9160. run_started_at = run_archive.started_at if run_archive else None
  9161. timelapse_path = await tl_complete(printer_id)
  9162. if timelapse_path and archive_id:
  9163. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  9164. elif timelapse_path:
  9165. # Timelapse created but no archive - just clean up
  9166. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9167. else:
  9168. # Print failed or cancelled - cancel timelapse session
  9169. cancel_session(printer_id)
  9170. logger.info(
  9171. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9172. )
  9173. except Exception as e:
  9174. logger.warning("[LAYER-TL] Failed: %s", e)
  9175. # A completed print's session left _active_sessions when its stitch
  9176. # began: the one there now belongs to the next print, which may have
  9177. # started during the stitch, and must not lose its frames.
  9178. if print_status != "completed":
  9179. try:
  9180. cancel_session(printer_id)
  9181. except Exception:
  9182. pass # Best-effort timelapse session cancellation on error
  9183. layer_timelapse = _background_layer_timelapse()
  9184. if archive_id and print_status == "completed":
  9185. layer_timelapse = _mark_run_finishing(archive_id, layer_timelapse)
  9186. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9187. log_timing("All background tasks scheduled")
  9188. # Auto-scan for timelapse if recording was active during the print
  9189. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9190. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9191. # Schedule timelapse scan as background task with retries
  9192. # The printer needs time to encode the video after print completion
  9193. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id)
  9194. log_timing("Timelapse scan scheduled")
  9195. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9196. # AMS sensor history recording
  9197. _ams_history_task: asyncio.Task | None = None
  9198. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9199. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9200. def _retention_days(stored: str | None, default: int) -> int:
  9201. """A history retention setting as days to keep: at least 1, the default
  9202. when unset or unreadable. A stored 0 or less (the API took one before it
  9203. had a minimum) would put the cutoff at now and delete all history."""
  9204. try:
  9205. return max(1, int(stored)) if stored is not None else default
  9206. except (TypeError, ValueError):
  9207. return default
  9208. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9209. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9210. _ams_alarm_cooldown: dict[str, datetime] = {}
  9211. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9212. # (printer_id, ams_id) already reported as sending the drop index and no
  9213. # percentage. Logged once each so a supported printer that turns out to do this
  9214. # shows up in a support bundle rather than as a user wondering where the
  9215. # humidity reading went -- see the note at the read site below (#3140).
  9216. _ams_index_only_logged: set[tuple[int, int]] = set()
  9217. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9218. """Temperature at which the AMS alarm fires, falling back to the display band.
  9219. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9220. when a notification was sent as well, which is why a room above it made the
  9221. alarm fire once an hour for as long as the weather lasted -- and the only way
  9222. to stop that was to raise the display band and lose the colour that says the
  9223. unit is warm (#2905).
  9224. Unset resolves to the fair threshold, so an install that never sets one is
  9225. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9226. so that arrives here as a string and is handled by the same branch as any
  9227. other unparseable value -- there is no separate sentinel to keep in sync.
  9228. A non-positive value is refused rather than honoured: zero would alarm
  9229. permanently, and it is far more likely to be a cleared field than a
  9230. deliberate choice.
  9231. """
  9232. if raw_alarm_value is None:
  9233. return fair_threshold
  9234. try:
  9235. value = float(raw_alarm_value)
  9236. except (TypeError, ValueError):
  9237. return fair_threshold
  9238. if not math.isfinite(value) or value <= 0:
  9239. return fair_threshold
  9240. return value
  9241. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9242. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9243. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9244. # partway through a cool-down would otherwise resume alarming about heat the
  9245. # user asked for — the same internal-timestamp-row pattern as
  9246. # support.py's debug_logging_enabled_at.
  9247. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9248. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9249. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9250. # matters when it never does.
  9251. AMS_DRYING_GRACE_MINUTES = 120
  9252. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9253. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9254. Anything older than the grace cap would expire on its next visit anyway, so
  9255. discarding it here costs nothing and stops rows for deleted printers from
  9256. accumulating.
  9257. Stamps ahead of now get two defences, because a box whose clock jumps
  9258. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9259. ones are discarded outright, and the rest are clamped to now. Without the
  9260. clamp the cap would measure from a moment that has not happened yet and hold
  9261. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9262. after a clock jump is a far better failure than an alarm silently disabled
  9263. for hours.
  9264. """
  9265. from backend.app.models.settings import Settings
  9266. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9267. setting = result.scalar_one_or_none()
  9268. if not setting or not setting.value:
  9269. return {}
  9270. try:
  9271. raw = json.loads(setting.value)
  9272. except (ValueError, TypeError):
  9273. return {} # Corrupted row → no latch, alarms behave as they did before
  9274. if not isinstance(raw, dict):
  9275. return {}
  9276. now = datetime.now(timezone.utc)
  9277. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9278. latch: dict[str, datetime] = {}
  9279. for key, value in raw.items():
  9280. try:
  9281. stamp = datetime.fromisoformat(str(value))
  9282. except (ValueError, TypeError):
  9283. continue
  9284. if stamp.tzinfo is None:
  9285. stamp = stamp.replace(tzinfo=timezone.utc)
  9286. if not (now - window <= stamp <= now + window):
  9287. continue
  9288. # Nothing may sit in the future: suppression is measured as now minus
  9289. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9290. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9291. latch[str(key)] = min(stamp, now)
  9292. return latch
  9293. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9294. """Persist the latch, writing only when it actually changed.
  9295. Adds the session change but does not commit — the caller's own commit
  9296. carries it, so the latch lands in the same transaction as the sensor rows
  9297. that produced it.
  9298. """
  9299. from backend.app.models.settings import Settings
  9300. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9301. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9302. setting = result.scalar_one_or_none()
  9303. if setting is None:
  9304. # Don't create the row on installs that never dry anything.
  9305. if payload != "{}":
  9306. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9307. elif setting.value != payload:
  9308. setting.value = payload
  9309. def _ams_has_filament(ams_data: dict) -> bool:
  9310. """True if this AMS unit has at least one tray slot holding filament.
  9311. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9312. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9313. still report sensor readings, but those readings are ambient and not
  9314. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9315. humidity/temperature alarms on this check so empty units don't generate
  9316. hourly noise. Sensor history still records regardless so the UI charts
  9317. stay continuous.
  9318. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9319. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9320. """
  9321. bits = ams_data.get("tray_exist_bits")
  9322. if isinstance(bits, str) and bits.strip():
  9323. try:
  9324. return int(bits, 16) > 0
  9325. except ValueError:
  9326. pass
  9327. trays = ams_data.get("tray")
  9328. if isinstance(trays, list):
  9329. return any(
  9330. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9331. )
  9332. return False
  9333. async def record_ams_history():
  9334. """Background task to record AMS humidity and temperature data."""
  9335. logger = logging.getLogger(__name__)
  9336. # Wait a short time for MQTT connections to establish on startup
  9337. await asyncio.sleep(10)
  9338. while True:
  9339. try:
  9340. from backend.app.models.ams_history import AMSSensorHistory
  9341. from backend.app.models.printer import Printer
  9342. from backend.app.models.settings import Settings
  9343. async with async_session() as db:
  9344. # Get all active printers
  9345. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9346. printers = result.scalars().all()
  9347. # Get alarm thresholds from settings
  9348. humidity_threshold = 60.0 # Default: fair threshold
  9349. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9350. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9351. setting = result.scalar_one_or_none()
  9352. if setting:
  9353. try:
  9354. humidity_threshold = float(setting.value)
  9355. except (ValueError, TypeError):
  9356. pass # Keep default threshold if stored value is invalid
  9357. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9358. setting = result.scalar_one_or_none()
  9359. if setting:
  9360. try:
  9361. temp_fair_threshold = float(setting.value)
  9362. except (ValueError, TypeError):
  9363. pass # Keep default threshold if stored value is invalid
  9364. # The alarm gets its own threshold, seeded from the resolved fair
  9365. # value so an install that has never set one behaves exactly as
  9366. # it did before (#2905). ams_temp_fair decides when the card turns
  9367. # amber; 35 C is a reasonable place to change a colour and not a
  9368. # reasonable place to page someone. A room above it makes the
  9369. # alarm fire once an hour for as long as the weather lasts, and
  9370. # the only way to stop it was to raise the display band and lose
  9371. # the colour that says the unit is warm.
  9372. #
  9373. # An unset value is stored as the literal "None", which the except
  9374. # below swallows the same way it swallows garbage -- so the
  9375. # fallback costs nothing and needs no sentinel of its own.
  9376. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9377. setting = result.scalar_one_or_none()
  9378. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9379. temp_fair_threshold, setting.value if setting else None
  9380. )
  9381. # Per-filament humidity threshold overrides (#1605) — resolved
  9382. # per-AMS below from the loaded tray types. Reuses the same
  9383. # resolver as the auto-drying scheduler so behavior stays in
  9384. # lockstep across both consumers.
  9385. from backend.app.services.print_scheduler import PrintScheduler
  9386. per_type_humidity_thresholds: dict[str, int] = {}
  9387. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9388. setting = result.scalar_one_or_none()
  9389. if setting and setting.value:
  9390. try:
  9391. raw = json.loads(setting.value)
  9392. if isinstance(raw, dict):
  9393. for k, v in raw.items():
  9394. try:
  9395. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9396. v
  9397. )
  9398. except (TypeError, ValueError):
  9399. continue
  9400. except (ValueError, TypeError):
  9401. pass # Invalid JSON → no overrides, fall through to global threshold
  9402. # Per-AMS drying latch (#1802), loaded once per pass and written
  9403. # back below only if a unit changed it.
  9404. drying_latch = await _load_ams_drying_latch(db)
  9405. drying_latch_before = dict(drying_latch)
  9406. recorded_count = 0
  9407. for printer in printers:
  9408. # Get current state from printer manager
  9409. state = printer_manager.get_status(printer.id)
  9410. if not state or not state.connected or not state.raw_data:
  9411. continue # Skip disconnected printers - don't use stale data
  9412. raw_data = state.raw_data
  9413. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9414. continue
  9415. # Record data for each AMS unit
  9416. for ams_data in raw_data["ams"]:
  9417. ams_id = int(ams_data.get("id", 0))
  9418. # Percentage only. The 1-5 index is inverted, so
  9419. # charting it as a percentage drew the wettest units as
  9420. # the driest (#3140); a unit that reports no percentage
  9421. # leaves a gap in the chart instead. See
  9422. # utils/ams_humidity.
  9423. humidity = ams_humidity_percent(ams_data)
  9424. # No supported printer is known to send the index
  9425. # alone -- the report came from unsupported firmware,
  9426. # and no install has been seen using the old fallback.
  9427. # "Known" is doing work there, so say so once per unit:
  9428. # the alternative is a silent blank card.
  9429. if humidity is None and ams_data.get("humidity") is not None:
  9430. unit_key = (printer.id, ams_id)
  9431. if unit_key not in _ams_index_only_logged:
  9432. _ams_index_only_logged.add(unit_key)
  9433. logger.info(
  9434. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9435. "percentage. The index is inverted and is not shown as a percentage "
  9436. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9437. "Please report this with the printer and AMS firmware versions.",
  9438. printer.name,
  9439. ams_id,
  9440. )
  9441. # Get temperature
  9442. temperature = None
  9443. temp_str = ams_data.get("temp")
  9444. if temp_str is not None:
  9445. try:
  9446. temperature = float(temp_str)
  9447. except (ValueError, TypeError):
  9448. pass # Skip unparseable temperature value
  9449. # Skip if no data
  9450. if humidity is None and temperature is None:
  9451. continue
  9452. # Record the data point
  9453. history = AMSSensorHistory(
  9454. printer_id=printer.id,
  9455. ams_id=ams_id,
  9456. humidity=humidity,
  9457. # Both columns hold the same reading now that the
  9458. # index can no longer reach ``humidity``. Writing it
  9459. # through the same value also stops a genuine 0%
  9460. # from being stored as NULL, which the old truthiness
  9461. # test did.
  9462. humidity_raw=humidity,
  9463. temperature=temperature,
  9464. )
  9465. db.add(history)
  9466. recorded_count += 1
  9467. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9468. is_ams_ht = ams_id >= 128
  9469. if is_ams_ht:
  9470. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9471. else:
  9472. ams_label = f"AMS-{chr(65 + ams_id)}"
  9473. # Skip alarm dispatch for empty AMS units — humidity /
  9474. # temperature readings are ambient with no filament to
  9475. # protect, and the hourly notification just becomes
  9476. # noise. Sensor history was already recorded above so
  9477. # the UI charts stay continuous (#1619). Per-AMS check
  9478. # so a multi-AMS setup with one loaded + one empty
  9479. # still alarms on the loaded unit.
  9480. if not _ams_has_filament(ams_data):
  9481. continue
  9482. # Resolve per-filament humidity threshold for this AMS
  9483. # unit (#1605). Falls back to the global ams_humidity_fair
  9484. # when no per-type overrides are configured.
  9485. trays = ams_data.get("tray", []) or []
  9486. effective_humidity_threshold = float(
  9487. PrintScheduler.resolve_humidity_threshold(
  9488. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9489. )
  9490. )
  9491. # Check humidity alarm (only if above threshold)
  9492. if humidity is not None and humidity > effective_humidity_threshold:
  9493. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9494. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9495. now = datetime.now(timezone.utc)
  9496. if (
  9497. last_alarm is None
  9498. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9499. ):
  9500. _ams_alarm_cooldown[cooldown_key] = now
  9501. logger.info(
  9502. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9503. )
  9504. try:
  9505. # Call different notification method based on AMS type
  9506. if is_ams_ht:
  9507. await notification_service.on_ams_ht_humidity_high(
  9508. printer.id,
  9509. printer.name,
  9510. ams_label,
  9511. humidity,
  9512. effective_humidity_threshold,
  9513. db,
  9514. )
  9515. else:
  9516. await notification_service.on_ams_humidity_high(
  9517. printer.id,
  9518. printer.name,
  9519. ams_label,
  9520. humidity,
  9521. effective_humidity_threshold,
  9522. db,
  9523. )
  9524. except Exception as e:
  9525. logger.warning("Failed to send humidity alarm: %s", e)
  9526. # A drying cycle heats the unit far past ams_temp_fair on
  9527. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9528. # AMS-HT, against a 35 C default — so the alarm fired
  9529. # once an hour for the whole cycle and kept firing while
  9530. # the unit cooled back down (#1802). Latch on the
  9531. # firmware's own drying state and hold until the reading
  9532. # returns to normal. Humidity is deliberately left alone:
  9533. # it falls during drying, which is the whole point.
  9534. latch_key = f"{printer.id}:{ams_id}"
  9535. # The latch releases at `threshold`, so it takes the alarm
  9536. # number too. Handing it the display band would strand the
  9537. # latch on any unit that settles back above it -- a room
  9538. # where the AMS rests at 37.7 C never returns under a 35 C
  9539. # band, so the latch could only expire on the grace cap
  9540. # rather than releasing when the unit had actually cooled.
  9541. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9542. drying_active=is_drying_active(ams_data),
  9543. temperature=temperature,
  9544. threshold=temp_alarm_threshold,
  9545. latched_at=drying_latch.get(latch_key),
  9546. now=datetime.now(timezone.utc),
  9547. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9548. )
  9549. if new_latch is None:
  9550. drying_latch.pop(latch_key, None)
  9551. else:
  9552. drying_latch[latch_key] = new_latch
  9553. # Check temperature alarm (only if above threshold)
  9554. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9555. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9556. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9557. now = datetime.now(timezone.utc)
  9558. if (
  9559. last_alarm is None
  9560. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9561. ):
  9562. _ams_alarm_cooldown[cooldown_key] = now
  9563. logger.info(
  9564. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9565. f"{temperature}°C > {temp_alarm_threshold}°C"
  9566. )
  9567. try:
  9568. # Call different notification method based on AMS type
  9569. if is_ams_ht:
  9570. # The reported threshold has to be the one
  9571. # that fired, or the message says "> 35 °C"
  9572. # while firing at 45.
  9573. await notification_service.on_ams_ht_temperature_high(
  9574. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9575. )
  9576. else:
  9577. await notification_service.on_ams_temperature_high(
  9578. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9579. )
  9580. except Exception as e:
  9581. logger.warning("Failed to send temperature alarm: %s", e)
  9582. if drying_latch != drying_latch_before:
  9583. await _save_ams_drying_latch(db, drying_latch)
  9584. await db.commit()
  9585. if recorded_count > 0:
  9586. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9587. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9588. global _ams_cleanup_counter
  9589. _ams_cleanup_counter += 1
  9590. if _ams_cleanup_counter >= 288:
  9591. _ams_cleanup_counter = 0
  9592. # Get retention days from settings
  9593. from backend.app.models.settings import Settings
  9594. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9595. setting = result.scalar_one_or_none()
  9596. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9597. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9598. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9599. await db.commit()
  9600. if result.rowcount > 0:
  9601. logger.info(
  9602. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9603. )
  9604. # Wait until next recording interval
  9605. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9606. except asyncio.CancelledError:
  9607. break
  9608. except Exception as e:
  9609. logger.warning("AMS history recording failed: %s", e)
  9610. await asyncio.sleep(60) # Wait a bit before retrying
  9611. def start_ams_history_recording():
  9612. """Start the AMS history recording background task."""
  9613. global _ams_history_task
  9614. if _ams_history_task is None:
  9615. _ams_history_task = asyncio.create_task(record_ams_history())
  9616. logging.getLogger(__name__).info("AMS history recording started")
  9617. def stop_ams_history_recording():
  9618. """Stop the AMS history recording background task."""
  9619. global _ams_history_task
  9620. if _ams_history_task:
  9621. _ams_history_task.cancel()
  9622. _ams_history_task = None
  9623. logging.getLogger(__name__).info("AMS history recording stopped")
  9624. # Printer sensor history recording (nozzle / bed / chamber)
  9625. _printer_sensor_history_task: asyncio.Task | None = None
  9626. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9627. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9628. _printer_sensor_cleanup_counter = 0
  9629. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9630. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9631. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9632. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9633. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9634. _SENSOR_TARGET_KEYS = {
  9635. "nozzle": "nozzle_target",
  9636. "nozzle_2": "nozzle_2_target",
  9637. "bed": "bed_target",
  9638. "chamber": "chamber_target",
  9639. }
  9640. async def record_printer_sensor_history():
  9641. """Background task to record nozzle / bed / chamber readings.
  9642. Pulls from `state.temperatures` (already normalised across all printer
  9643. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9644. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9645. """
  9646. logger = logging.getLogger(__name__)
  9647. await asyncio.sleep(10)
  9648. while True:
  9649. try:
  9650. from backend.app.models.printer import Printer
  9651. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9652. from backend.app.models.settings import Settings
  9653. async with async_session() as db:
  9654. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9655. printers = result.scalars().all()
  9656. recorded_count = 0
  9657. for printer in printers:
  9658. state = printer_manager.get_status(printer.id)
  9659. if not state or not state.connected:
  9660. continue
  9661. temps = getattr(state, "temperatures", None) or {}
  9662. if not isinstance(temps, dict):
  9663. continue
  9664. for kind in _SENSOR_KINDS:
  9665. if kind not in temps:
  9666. continue
  9667. try:
  9668. value = float(temps[kind])
  9669. except (ValueError, TypeError):
  9670. continue
  9671. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9672. target_val: float | None = None
  9673. if target_raw is not None:
  9674. try:
  9675. target_val = float(target_raw)
  9676. except (ValueError, TypeError):
  9677. target_val = None
  9678. db.add(
  9679. PrinterSensorHistory(
  9680. printer_id=printer.id,
  9681. sensor_kind=kind,
  9682. value=value,
  9683. target=target_val,
  9684. )
  9685. )
  9686. recorded_count += 1
  9687. await db.commit()
  9688. if recorded_count > 0:
  9689. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9690. # Periodic cleanup — once every ~24h at this interval.
  9691. global _printer_sensor_cleanup_counter
  9692. _printer_sensor_cleanup_counter += 1
  9693. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9694. if _printer_sensor_cleanup_counter >= cleanup_every:
  9695. _printer_sensor_cleanup_counter = 0
  9696. result = await db.execute(
  9697. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9698. )
  9699. setting = result.scalar_one_or_none()
  9700. retention_days = _retention_days(
  9701. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9702. )
  9703. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9704. cleanup = await db.execute(
  9705. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9706. )
  9707. await db.commit()
  9708. if cleanup.rowcount > 0:
  9709. logger.info(
  9710. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9711. cleanup.rowcount,
  9712. retention_days,
  9713. )
  9714. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9715. except asyncio.CancelledError:
  9716. break
  9717. except Exception as e:
  9718. logger.warning("Printer sensor history recording failed: %s", e)
  9719. await asyncio.sleep(60)
  9720. def start_printer_sensor_history_recording():
  9721. global _printer_sensor_history_task
  9722. if _printer_sensor_history_task is None:
  9723. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9724. logging.getLogger(__name__).info("Printer sensor history recording started")
  9725. def stop_printer_sensor_history_recording():
  9726. global _printer_sensor_history_task
  9727. if _printer_sensor_history_task:
  9728. _printer_sensor_history_task.cancel()
  9729. _printer_sensor_history_task = None
  9730. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9731. # Printer runtime tracking
  9732. _runtime_tracking_task: asyncio.Task | None = None
  9733. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9734. # Printers the runtime tracker has seen connected since startup. One of them
  9735. # going offline clears its timestamp, so the time it was away is not counted
  9736. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9737. # connecting after a restart -- keeps it for a grace period: a print that ran
  9738. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9739. _runtime_seen_connected: set[int] = set()
  9740. # A printer never seen connected this long after the tracker started is
  9741. # offline, not still connecting: its stored timestamp predates a gap too.
  9742. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9743. async def track_printer_runtime():
  9744. """Background task to track printer active runtime (RUNNING state only).
  9745. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9746. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9747. which track mechanical wear. Pause time has no motion and no wear, so
  9748. counting it inflates maintenance warnings (#1521).
  9749. """
  9750. logger = logging.getLogger(__name__)
  9751. # Wait for MQTT connections to establish on startup
  9752. await asyncio.sleep(15)
  9753. started = time.monotonic()
  9754. while True:
  9755. try:
  9756. from backend.app.models.printer import Printer
  9757. # Fetch printer IDs in a short-lived read-only session
  9758. async with async_session() as db:
  9759. result = await db.execute(
  9760. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9761. Printer.is_active.is_(True)
  9762. )
  9763. )
  9764. printer_rows = result.all()
  9765. now = datetime.now(timezone.utc)
  9766. updated_count = 0
  9767. # Update each printer in its own short session to minimise write-lock
  9768. # hold time and avoid blocking critical commits like queue status
  9769. # updates (#897).
  9770. for pid, pname, runtime_secs, last_update in printer_rows:
  9771. state = printer_manager.get_status(pid)
  9772. if not state:
  9773. logger.debug("[%s] Runtime tracking: no state available", pname)
  9774. continue
  9775. if not state.connected:
  9776. logger.debug("[%s] Runtime tracking: not connected", pname)
  9777. offline = pid in _runtime_seen_connected or (
  9778. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9779. )
  9780. if offline and last_update is not None:
  9781. try:
  9782. async with async_session() as db:
  9783. printer = await db.get(Printer, pid)
  9784. if printer:
  9785. printer.last_runtime_update = None
  9786. await db.commit()
  9787. except Exception as e:
  9788. # Still marked: the next offline tick tries again.
  9789. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9790. continue
  9791. _runtime_seen_connected.discard(pid)
  9792. continue
  9793. _runtime_seen_connected.add(pid)
  9794. needs_commit = False
  9795. new_runtime = runtime_secs
  9796. new_last_update = last_update
  9797. if state.state == "RUNNING":
  9798. if last_update:
  9799. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9800. elapsed = (now - lu).total_seconds()
  9801. if elapsed > 0:
  9802. new_runtime = runtime_secs + int(elapsed)
  9803. updated_count += 1
  9804. needs_commit = True
  9805. logger.debug(
  9806. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9807. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9808. )
  9809. else:
  9810. needs_commit = True
  9811. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9812. new_last_update = now
  9813. else:
  9814. if last_update is not None:
  9815. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9816. new_last_update = None
  9817. needs_commit = True
  9818. if needs_commit:
  9819. try:
  9820. async with async_session() as db:
  9821. result = await db.execute(select(Printer).where(Printer.id == pid))
  9822. printer = result.scalar_one_or_none()
  9823. if printer:
  9824. printer.runtime_seconds = new_runtime
  9825. printer.last_runtime_update = new_last_update
  9826. await db.commit()
  9827. except Exception as e:
  9828. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9829. if updated_count > 0:
  9830. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9831. except asyncio.CancelledError:
  9832. logger.info("Runtime tracking cancelled")
  9833. break
  9834. except Exception as e:
  9835. logger.warning("Runtime tracking failed: %s", e)
  9836. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9837. def start_runtime_tracking():
  9838. """Start the printer runtime tracking background task."""
  9839. global _runtime_tracking_task
  9840. if _runtime_tracking_task is None:
  9841. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9842. logging.getLogger(__name__).info("Printer runtime tracking started")
  9843. def stop_runtime_tracking():
  9844. """Stop the printer runtime tracking background task."""
  9845. global _runtime_tracking_task
  9846. if _runtime_tracking_task:
  9847. _runtime_tracking_task.cancel()
  9848. _runtime_tracking_task = None
  9849. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9850. # SpoolBuddy device watchdog
  9851. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9852. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9853. async def _spoolbuddy_watchdog_loop():
  9854. """Periodic check for SpoolBuddy devices that have gone offline."""
  9855. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9856. while True:
  9857. try:
  9858. await spoolbuddy_watchdog()
  9859. except asyncio.CancelledError:
  9860. break
  9861. except Exception as e:
  9862. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9863. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9864. def start_spoolbuddy_watchdog():
  9865. global _spoolbuddy_watchdog_task
  9866. if _spoolbuddy_watchdog_task is None:
  9867. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9868. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9869. def stop_spoolbuddy_watchdog():
  9870. global _spoolbuddy_watchdog_task
  9871. if _spoolbuddy_watchdog_task:
  9872. _spoolbuddy_watchdog_task.cancel()
  9873. _spoolbuddy_watchdog_task = None
  9874. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9875. # Dead-MQTT-session recovery
  9876. #
  9877. # check_staleness() covers the "connected but silent" half-broken session. It
  9878. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9879. # is the only thing left watching at that point. When paho stops making
  9880. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9881. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9882. # offline with the UI open the whole time, recovered only when something
  9883. # happened to nudge it.
  9884. #
  9885. # This loop is that backstop. It only touches printers that had a working
  9886. # session and lost it, and only when the MQTT port still answers — a printer
  9887. # that is simply switched off is left to paho, since rebuilding a client
  9888. # against an unreachable host achieves nothing and would fill the log every
  9889. # night.
  9890. _connection_watchdog_task: asyncio.Task | None = None
  9891. CONNECTION_WATCHDOG_INTERVAL = 60
  9892. # How long a printer must have been silent before we stop trusting paho.
  9893. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9894. # so a session that is recovering on its own is never interrupted.
  9895. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9896. # Per-printer floor between rebuild attempts.
  9897. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9898. _connection_watchdog_last_attempt: dict[int, float] = {}
  9899. async def _recover_dead_printer_sessions() -> int:
  9900. """Rebuild MQTT clients that have been offline too long to still be trying.
  9901. Returns the number of printers a rebuild was attempted for (for tests and
  9902. for the caller's logging). Never raises: one unreachable printer must not
  9903. stop the sweep for the rest of the farm.
  9904. """
  9905. logger = logging.getLogger(__name__)
  9906. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9907. now = time.monotonic()
  9908. recovered = 0
  9909. for printer_id, client in list(printer_manager._clients.items()):
  9910. try:
  9911. if client.state.connected:
  9912. _connection_watchdog_last_attempt.pop(printer_id, None)
  9913. continue
  9914. # Time since the last inbound message is the age of the last known
  9915. # good session — no extra bookkeeping needed, and it is the same
  9916. # clock is_stale() reads. 0 means this client has never had one:
  9917. # that is the initial-connect path, where paho retrying is the
  9918. # correct and only behaviour, so leave it be.
  9919. last_msg = client._last_message_time
  9920. if not last_msg:
  9921. continue
  9922. offline_for = time.time() - last_msg
  9923. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9924. continue
  9925. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9926. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9927. continue
  9928. if not await check_port(client.ip_address, PORT_MQTT):
  9929. # Switched off, unplugged, or off the network. Paho's retry is
  9930. # the right handler; say so at debug level and move on.
  9931. logger.debug(
  9932. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9933. "— leaving the reconnect to paho",
  9934. printer_id,
  9935. offline_for,
  9936. )
  9937. _connection_watchdog_last_attempt[printer_id] = now
  9938. continue
  9939. _connection_watchdog_last_attempt[printer_id] = now
  9940. recovered += 1
  9941. logger.warning(
  9942. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9943. "rebuilding the client with a fresh session (last connect error: %s)",
  9944. printer_id,
  9945. offline_for,
  9946. PORT_MQTT,
  9947. client.last_connect_error or "none recorded",
  9948. )
  9949. # Async context, so this takes the hard-reset path: fresh client_id,
  9950. # paho's QoS 1 queue dropped. That matters — a project_file left
  9951. # unacked on the dead session would otherwise replay into the new
  9952. # one and trip 0500_4003 on the printer (#1136).
  9953. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9954. except Exception as e:
  9955. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9956. return recovered
  9957. async def _connection_watchdog_loop():
  9958. logger = logging.getLogger(__name__)
  9959. # Let the initial connects settle before judging anyone offline.
  9960. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9961. while True:
  9962. try:
  9963. await _recover_dead_printer_sessions()
  9964. except asyncio.CancelledError:
  9965. break
  9966. except Exception as e:
  9967. logger.warning("Connection watchdog sweep failed: %s", e)
  9968. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9969. def start_connection_watchdog():
  9970. global _connection_watchdog_task
  9971. if _connection_watchdog_task is None:
  9972. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9973. logging.getLogger(__name__).info("Printer connection watchdog started")
  9974. def stop_connection_watchdog():
  9975. global _connection_watchdog_task
  9976. if _connection_watchdog_task:
  9977. _connection_watchdog_task.cancel()
  9978. _connection_watchdog_task = None
  9979. _connection_watchdog_last_attempt.clear()
  9980. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9981. # Camera stream orphan cleanup
  9982. _camera_cleanup_task: asyncio.Task | None = None
  9983. CAMERA_CLEANUP_INTERVAL = 60
  9984. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9985. # kept frames of a failed stitch go after a day, not at the next restart.
  9986. TIMELAPSE_CLEANUP_EVERY = 60
  9987. async def _camera_cleanup_loop():
  9988. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9989. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9990. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9991. rounds = 0
  9992. while True:
  9993. try:
  9994. rounds += 1
  9995. await cleanup_orphaned_streams()
  9996. except asyncio.CancelledError:
  9997. break
  9998. except Exception as e:
  9999. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10000. try:
  10001. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10002. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10003. except asyncio.CancelledError:
  10004. break
  10005. except Exception as e:
  10006. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10007. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10008. def start_camera_cleanup():
  10009. global _camera_cleanup_task
  10010. if _camera_cleanup_task is None:
  10011. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10012. logging.getLogger(__name__).info("Camera stream cleanup started")
  10013. def stop_camera_cleanup():
  10014. global _camera_cleanup_task
  10015. if _camera_cleanup_task:
  10016. _camera_cleanup_task.cancel()
  10017. _camera_cleanup_task = None
  10018. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10019. # ---------------------------------------------------------------------------
  10020. # Expected-print TTL eviction
  10021. # ---------------------------------------------------------------------------
  10022. def _evict_stale_expected_prints() -> None:
  10023. """Remove entries from _expected_prints / _expected_print_creators that are
  10024. older than _EXPECTED_PRINT_TTL_SECONDS.
  10025. This prevents unbounded growth when a print is registered (via
  10026. register_expected_print) but on_print_start never fires — e.g. because the
  10027. printer disconnects, the app restarts, or the print is started directly from
  10028. the printer panel without going through the queue.
  10029. """
  10030. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10031. # (e.g. NTP sync, DST changes).
  10032. # A print that ended without its archive being found at completion leaves
  10033. # its id here; only running prints are owned.
  10034. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10035. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10036. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10037. if not stale_keys:
  10038. return
  10039. evicted: set[tuple[int, int]] = set()
  10040. for key in stale_keys:
  10041. archive_id = _expected_prints.pop(key, None)
  10042. if archive_id is not None:
  10043. evicted.add((key[0], archive_id))
  10044. _expected_print_creators.pop(key, None)
  10045. _expected_print_registered_at.pop(key, None)
  10046. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10047. # that have no remaining live keys in _expected_prints (all variants
  10048. # were just evicted) and are not printing right now. Print start pops
  10049. # only the names the printer reported, so the "<base>.gcode" variant
  10050. # outlives it; without the printing check its eviction two hours after
  10051. # dispatch threw away a running print's plate, AMS mapping and cost
  10052. # centre, which completion still reads (#3275).
  10053. for printer_id, archive_id in evicted:
  10054. if not _expected_or_printing_here(printer_id, archive_id):
  10055. _drop_dispatch(printer_id, archive_id)
  10056. logging.getLogger(__name__).info(
  10057. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10058. )
  10059. async def _expected_prints_cleanup_loop() -> None:
  10060. """Background task: periodically evict stale expected-print entries."""
  10061. while True:
  10062. try:
  10063. _evict_stale_expected_prints()
  10064. except asyncio.CancelledError:
  10065. raise
  10066. except Exception as e:
  10067. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10068. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10069. def start_expected_prints_cleanup() -> None:
  10070. global _expected_prints_cleanup_task
  10071. if _expected_prints_cleanup_task is None:
  10072. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10073. logging.getLogger(__name__).info("Expected prints cleanup started")
  10074. def stop_expected_prints_cleanup() -> None:
  10075. global _expected_prints_cleanup_task
  10076. if _expected_prints_cleanup_task:
  10077. _expected_prints_cleanup_task.cancel()
  10078. _expected_prints_cleanup_task = None
  10079. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10080. # ---------------------------------------------------------------------------
  10081. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10082. # ---------------------------------------------------------------------------
  10083. _auth_cleanup_task: asyncio.Task | None = None
  10084. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10085. async def _run_auth_cleanup() -> None:
  10086. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10087. from backend.app.core.database import async_session
  10088. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10089. from backend.app.models.user_totp import UserTOTP
  10090. now = datetime.now(timezone.utc)
  10091. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10092. try:
  10093. async with async_session() as db:
  10094. stale_cutoff = now - timedelta(hours=1)
  10095. result = await db.execute(
  10096. select(UserTOTP).where(
  10097. UserTOTP.is_enabled.is_(False),
  10098. UserTOTP.created_at < stale_cutoff,
  10099. )
  10100. )
  10101. stale_records = result.scalars().all()
  10102. if stale_records:
  10103. for rec in stale_records:
  10104. await db.delete(rec)
  10105. await db.commit()
  10106. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10107. except Exception as e:
  10108. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10109. # Remove expired revoked-JTI entries (they are no longer needed once the
  10110. # original token's exp has passed — the token would be rejected by JWT
  10111. # signature verification regardless).
  10112. try:
  10113. async with async_session() as db:
  10114. await db.execute(
  10115. delete(AuthEphemeralToken).where(
  10116. AuthEphemeralToken.token_type == "revoked_jti",
  10117. AuthEphemeralToken.expires_at < now,
  10118. )
  10119. )
  10120. await db.commit()
  10121. except Exception as e:
  10122. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10123. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10124. # Events outside this window can never affect rate-limit decisions — they only
  10125. # consume DB space. Use the same window constant as the rate limiter so the
  10126. # two are always in sync.
  10127. try:
  10128. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10129. async with async_session() as db:
  10130. await db.execute(
  10131. delete(AuthRateLimitEvent).where(
  10132. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10133. )
  10134. )
  10135. await db.commit()
  10136. except Exception as e:
  10137. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10138. async def _auth_cleanup_loop() -> None:
  10139. """Periodic background task: run auth cleanup every hour."""
  10140. while True:
  10141. try:
  10142. await _run_auth_cleanup()
  10143. except asyncio.CancelledError:
  10144. break
  10145. except Exception as e:
  10146. logging.warning("Auth cleanup loop error: %s", e)
  10147. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10148. def start_auth_cleanup() -> None:
  10149. global _auth_cleanup_task
  10150. if _auth_cleanup_task is None:
  10151. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10152. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10153. def stop_auth_cleanup() -> None:
  10154. global _auth_cleanup_task
  10155. if _auth_cleanup_task:
  10156. _auth_cleanup_task.cancel()
  10157. _auth_cleanup_task = None
  10158. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10159. @asynccontextmanager
  10160. async def lifespan(app: FastAPI):
  10161. # Startup
  10162. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10163. # anything else can spawn tasks that might trip it.
  10164. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10165. install_proactor_reset_filter()
  10166. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10167. # what turned descriptor exhaustion into a corrupted database (#2883).
  10168. from backend.app.core.fd_limit import raise_open_file_limit
  10169. raise_open_file_limit()
  10170. # Before init_db, so the warning is near the top of the log rather than
  10171. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10172. warn_if_running_on_uvloop()
  10173. await init_db()
  10174. # Browser download tokens expire after five minutes. Remove abandoned
  10175. # prepared ZIPs at startup as well as before each new preparation so a
  10176. # quiet appliance cannot retain an unusable bundle indefinitely.
  10177. try:
  10178. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10179. await prune_stale_printer_file_bundles()
  10180. except Exception as exc:
  10181. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10182. # After migrations, so the is_env_managed column exists. Never raises --
  10183. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10184. # startup (see apply_env_oidc_provider).
  10185. from backend.app.core.oidc_env import apply_env_oidc_provider
  10186. async with async_session() as oidc_db:
  10187. await apply_env_oidc_provider(oidc_db)
  10188. # Close out batches that finished before `completed` was a reachable status
  10189. # (#342). Without this the Batches tab opens on every batch created since
  10190. # the feature shipped, all still marked active. Never blocks startup.
  10191. try:
  10192. from backend.app.services.print_batch import backfill_batch_statuses
  10193. async with async_session() as batch_db:
  10194. await backfill_batch_statuses(batch_db)
  10195. except Exception as exc:
  10196. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10197. # Register an app-scoped httpx client for Bambu Cloud services so
  10198. # per-request BambuCloudService instances reuse the same connection pool
  10199. # (important for routes like /cloud/filament-info that chain many
  10200. # get_setting_detail calls). The shared client stores no region/token
  10201. # state, so the per-request ownership pattern that fixed the region-bleed
  10202. # bug is preserved.
  10203. import httpx as _httpx
  10204. from backend.app.services.bambu_cloud import set_shared_http_client
  10205. from backend.app.services.model_providers.makerworld.service import (
  10206. set_shared_http_client as set_shared_makerworld_http_client,
  10207. )
  10208. from backend.app.services.orca_cloud import (
  10209. set_shared_http_client as set_shared_orca_http_client,
  10210. )
  10211. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10212. set_shared_http_client(_shared_cloud_http_client)
  10213. # Reuse the same connection pool for MakerWorld — different host, same
  10214. # keep-alive pool saves a TLS handshake per request.
  10215. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10216. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10217. # each spun up (and never closed) its own client, leaking sockets.
  10218. set_shared_orca_http_client(_shared_cloud_http_client)
  10219. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10220. # This can happen when a print was cancelled mid-print on versions before this fix.
  10221. try:
  10222. async with async_session() as db:
  10223. from backend.app.models.print_queue import PrintQueueItem
  10224. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10225. aborted_items = result.scalars().all()
  10226. if aborted_items:
  10227. for item in aborted_items:
  10228. item.status = "cancelled"
  10229. await db.commit()
  10230. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10231. except Exception as e:
  10232. logging.warning("Failed to fix aborted queue items: %s", e)
  10233. # Restore debug logging state from previous session
  10234. await init_debug_logging()
  10235. # Set up printer manager callbacks
  10236. loop = asyncio.get_event_loop()
  10237. printer_manager.set_event_loop(loop)
  10238. printer_manager.set_status_change_callback(on_printer_status_change)
  10239. printer_manager.set_print_start_callback(on_print_start)
  10240. printer_manager.set_print_complete_callback(on_print_complete)
  10241. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10242. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10243. printer_manager.set_ams_change_callback(on_ams_change)
  10244. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10245. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10246. await printer_manager.load_awaiting_plate_clear_from_db()
  10247. # Layer change callback for external camera timelapse
  10248. async def on_layer_change(printer_id: int, layer_num: int):
  10249. """Capture timelapse frame on layer change + first layer notification."""
  10250. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10251. await tl_layer_change(printer_id, layer_num)
  10252. # #1867: bank a recent in-print frame so the finish-photo path has a
  10253. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10254. # #2547 added `on_print_progress` as a second driver — this one alone
  10255. # stops firing once the final layer begins.
  10256. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10257. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10258. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10259. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10260. # nozzle clean), so a bare layer_num check can fire minutes before the
  10261. # first real extrusion. We require gcode_state == RUNNING and
  10262. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10263. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10264. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10265. # edge fires later; _first_layer_notified stays clear until we actually send
  10266. # so a deferred re-evaluation can win. See issue #1837.
  10267. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10268. client = printer_manager.get_client(printer_id)
  10269. state = client.state if client else None
  10270. if not state or state.state != "RUNNING":
  10271. return
  10272. if state.mc_print_sub_stage not in (None, 0):
  10273. return
  10274. _first_layer_notified[printer_id] = True
  10275. try:
  10276. async with async_session() as db:
  10277. from backend.app.models.printer import Printer
  10278. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10279. printer = result.scalar_one_or_none()
  10280. if not printer:
  10281. return
  10282. printer_name = printer.name
  10283. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10284. total_layers = state.total_layers if state else 0
  10285. image_data = await _capture_snapshot_for_notification(
  10286. printer_id, printer, logging.getLogger(__name__)
  10287. )
  10288. await notification_service.on_first_layer_complete(
  10289. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10290. )
  10291. except Exception as e:
  10292. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10293. printer_manager.set_layer_change_callback(on_layer_change)
  10294. async def on_print_progress(printer_id: int, percent: int):
  10295. """#2547: keep the in-print frame bank fresh through the final layer.
  10296. `on_layer_change` stops the moment the last layer starts, which on the
  10297. H2C capture that closed #2547 left the bank stale for the three minutes
  10298. that layer took. Progress is the only field that keeps advancing there,
  10299. and it freezes before the End G-code runs — so banking on it stays
  10300. inside the print and never sees a swapped plate.
  10301. """
  10302. client = printer_manager.get_client(printer_id)
  10303. state = client.state if client else None
  10304. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10305. printer_manager.set_print_progress_callback(on_print_progress)
  10306. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10307. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10308. waiter = _bed_cool_waiters.get(printer_id)
  10309. if not waiter:
  10310. return
  10311. threshold = waiter["threshold"]
  10312. if bed_temp > threshold:
  10313. return
  10314. # Bed is at or below threshold — fire notification and remove waiter
  10315. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10316. if not waiter_info:
  10317. return # Another callback already handled it
  10318. bed_cool_logger = logging.getLogger(__name__)
  10319. bed_cool_logger.info(
  10320. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10321. bed_temp,
  10322. printer_id,
  10323. threshold,
  10324. )
  10325. try:
  10326. printer_info = printer_manager.get_printer(printer_id)
  10327. p_name = printer_info.name if printer_info else "Unknown"
  10328. async with async_session() as db:
  10329. await notification_service.on_bed_cooled(
  10330. printer_id=printer_id,
  10331. printer_name=p_name,
  10332. bed_temp=bed_temp,
  10333. threshold=threshold,
  10334. filename=waiter_info["filename"],
  10335. db=db,
  10336. )
  10337. except Exception as e:
  10338. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10339. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10340. async def on_drying_complete(printer_id: int, ams_id: int):
  10341. """Smart-plug auto-off-after-drying trigger (#1349).
  10342. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10343. manager walks all plugs linked to this printer and turns off only
  10344. the ones with ``auto_off_after_drying`` enabled, after their
  10345. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10346. dual-AMS dry that ends within the same MQTT push) call this once
  10347. per unit — the manager's ``_cancel_pending_off`` collapses
  10348. repeated scheduling on the same plug to one timer, so duplicate
  10349. fires are safe.
  10350. """
  10351. try:
  10352. async with async_session() as db:
  10353. await smart_plug_manager.on_drying_complete(printer_id, db)
  10354. except Exception as e:
  10355. logging.getLogger(__name__).warning(
  10356. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10357. printer_id,
  10358. ams_id,
  10359. e,
  10360. )
  10361. printer_manager.set_drying_complete_callback(on_drying_complete)
  10362. async def on_drying_cycle_end(printer_id: int, cycle):
  10363. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10364. from backend.app.services.spool_drying import record_drying_cycle
  10365. try:
  10366. async with async_session() as db:
  10367. await record_drying_cycle(db, printer_id, cycle)
  10368. except Exception as e:
  10369. logging.getLogger(__name__).warning(
  10370. "Failed to record drying for printer %d (AMS %d): %s",
  10371. printer_id,
  10372. cycle.ams_id,
  10373. e,
  10374. )
  10375. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10376. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10377. """Surface the read-back result of a spool assignment to the UI (#2582).
  10378. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10379. echoed back the filament id we pushed. We relay that as a websocket
  10380. event so the frontend can toast "loaded" / "assignment didn't take"
  10381. instead of the historic silent fire-and-forget, which made the
  10382. AMS→Studio hand-off feel random to users.
  10383. """
  10384. try:
  10385. from backend.app.services.spool_assignment_notifications import (
  10386. _slot_label_from_global_tray,
  10387. )
  10388. if ams_id == 255:
  10389. global_id = 254 + tray_id
  10390. elif ams_id >= 128:
  10391. global_id = ams_id
  10392. else:
  10393. global_id = ams_id * 4 + tray_id
  10394. slot_label = _slot_label_from_global_tray(global_id)
  10395. printer_info = printer_manager.get_printer(printer_id)
  10396. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10397. await ws_manager.broadcast(
  10398. {
  10399. "type": "spool_assignment_verified",
  10400. "printer_id": printer_id,
  10401. "printer_name": printer_name,
  10402. "ams_id": ams_id,
  10403. "tray_id": tray_id,
  10404. "slot": slot_label,
  10405. "verified": verified,
  10406. # Present on success: False means the filament setting landed
  10407. # but the K-profile (cali_idx) did not — the reporter's exact
  10408. # "loaded but no flow profile" symptom.
  10409. "kprofile_applied": detail.get("kprofile_applied", True),
  10410. }
  10411. )
  10412. except Exception as e:
  10413. logging.getLogger(__name__).warning(
  10414. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10415. printer_id,
  10416. ams_id,
  10417. tray_id,
  10418. e,
  10419. )
  10420. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10421. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10422. """Persist a mid-print tray change for completion-time attribution.
  10423. AMS filament backup switches trays without telling the slicer, so the
  10424. tray-change log is the only record of which spool fed which layers.
  10425. Keeping it only in memory meant a restart mid-print charged everything
  10426. to the tray that finished the job.
  10427. """
  10428. try:
  10429. from backend.app.services.usage_tracker import record_tray_change
  10430. async with async_session() as db:
  10431. await record_tray_change(db, printer_id, tray_global, layer_num)
  10432. except Exception as e:
  10433. logging.getLogger(__name__).warning(
  10434. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10435. printer_id,
  10436. tray_global,
  10437. layer_num,
  10438. e,
  10439. )
  10440. printer_manager.set_tray_change_callback(on_tray_change)
  10441. # Initialize MQTT relay from settings
  10442. async with async_session() as db:
  10443. from backend.app.api.routes.settings import get_setting
  10444. mqtt_settings = {
  10445. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10446. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10447. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10448. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10449. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10450. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10451. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10452. }
  10453. await mqtt_relay.configure(mqtt_settings)
  10454. # Restore MQTT smart plug subscriptions
  10455. if mqtt_settings.get("mqtt_enabled"):
  10456. from backend.app.models.smart_plug import SmartPlug
  10457. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10458. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10459. mqtt_plugs = result.scalars().all()
  10460. restored = 0
  10461. for plug in mqtt_plugs:
  10462. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10463. restored += 1
  10464. if restored:
  10465. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10466. # Connect to all active printers
  10467. async with async_session() as db:
  10468. await init_printer_connections(db)
  10469. # Auto-connect to Spoolman if enabled
  10470. async with async_session() as db:
  10471. from backend.app.api.routes.settings import get_setting
  10472. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10473. spoolman_url = await get_setting(db, "spoolman_url")
  10474. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10475. try:
  10476. client = await init_spoolman_client(spoolman_url)
  10477. if await client.health_check():
  10478. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10479. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10480. field_ok = await client.ensure_tag_extra_field()
  10481. if not field_ok:
  10482. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10483. # Register the BambuStudio slicer-preset fields used by the
  10484. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10485. # unknown extra keys, so these must exist before any update
  10486. # that touches them.
  10487. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10488. if not await client.ensure_extra_field(field_name):
  10489. logging.warning(
  10490. "Spoolman extra field %r registration failed — "
  10491. "spool slicer-preset edits will return 502",
  10492. field_name,
  10493. )
  10494. else:
  10495. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10496. except Exception as e:
  10497. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10498. # Start the print scheduler
  10499. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10500. # Start the smart plug scheduler for time-based on/off
  10501. smart_plug_manager.start_scheduler()
  10502. # Start the Home Assistant sensor poller (#1148)
  10503. ha_sensor_manager.start()
  10504. location_ha_sensor_manager.start()
  10505. # Resume any pending auto-offs that were interrupted by restart
  10506. await smart_plug_manager.resume_pending_auto_offs()
  10507. # Start the notification digest scheduler
  10508. notification_service.start_digest_scheduler()
  10509. notify_live_activities.start()
  10510. notify_widgets.start()
  10511. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10512. # provider in reactions/both mode; the notification routes resync them.
  10513. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10514. # until the next provider save, not the whole startup.
  10515. try:
  10516. await telegram_reaction_poller.start()
  10517. except Exception as e:
  10518. logging.warning("Telegram reaction poller did not start: %s", e)
  10519. # Start the GitHub backup scheduler
  10520. await github_backup_service.start_scheduler()
  10521. # Start the local backup scheduler
  10522. await local_backup_service.start_scheduler()
  10523. await obico_detection_service.start()
  10524. # Start the library trash sweeper (#1008)
  10525. await library_trash_service.start_scheduler()
  10526. # Start the archive auto-purge sweeper (#1008 follow-up)
  10527. await archive_purge_service.start_scheduler()
  10528. # Start AMS history recording
  10529. start_ams_history_recording()
  10530. # Start printer sensor (nozzle / bed / chamber) history recording
  10531. start_printer_sensor_history_recording()
  10532. # Start printer runtime tracking
  10533. start_runtime_tracking()
  10534. # Start SpoolBuddy device watchdog
  10535. start_spoolbuddy_watchdog()
  10536. # Start camera stream orphan cleanup
  10537. start_camera_cleanup()
  10538. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10539. start_connection_watchdog()
  10540. # One-shot sweep for timelapse session directories orphaned by a crash
  10541. # or restart that happened mid-print (in-memory session tracking can't
  10542. # survive that, and nothing else reaps the leftover frames/output file)
  10543. try:
  10544. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10545. removed = cleanup_orphaned_timelapse_sessions()
  10546. if removed:
  10547. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10548. except Exception as e:
  10549. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10550. # Start expected-print TTL eviction (prevents memory leak when prints are
  10551. # registered but on_print_start never fires)
  10552. start_expected_prints_cleanup()
  10553. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10554. start_auth_cleanup()
  10555. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10556. from backend.app.services import announcements as announcements_service
  10557. announcements_service.start()
  10558. from backend.app.services.printer_media import start_printer_download_cleanup
  10559. start_printer_download_cleanup()
  10560. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10561. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10562. from backend.app.services.loop_watchdog import start_loop_watchdog
  10563. start_loop_watchdog()
  10564. # Initialize virtual printer manager and sync from DB
  10565. from backend.app.services.virtual_printer import virtual_printer_manager
  10566. virtual_printer_manager.set_session_factory(async_session)
  10567. virtual_printer_manager.set_printer_manager(printer_manager)
  10568. try:
  10569. await virtual_printer_manager.sync_from_db()
  10570. logging.info("Virtual printer manager synced from database")
  10571. except Exception as e:
  10572. logging.warning("Failed to sync virtual printers: %s", e)
  10573. yield
  10574. # Shutdown
  10575. print_scheduler.stop()
  10576. smart_plug_manager.stop_scheduler()
  10577. ha_sensor_manager.stop()
  10578. location_ha_sensor_manager.stop()
  10579. notification_service.stop_digest_scheduler()
  10580. await notify_live_activities.close()
  10581. await notify_widgets.close()
  10582. await telegram_reaction_poller.aclose()
  10583. github_backup_service.stop_scheduler()
  10584. local_backup_service.stop_scheduler()
  10585. library_trash_service.stop_scheduler()
  10586. archive_purge_service.stop_scheduler()
  10587. obico_detection_service.stop()
  10588. stop_ams_history_recording()
  10589. stop_printer_sensor_history_recording()
  10590. stop_runtime_tracking()
  10591. stop_spoolbuddy_watchdog()
  10592. stop_camera_cleanup()
  10593. stop_connection_watchdog()
  10594. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10595. stop_loop_watchdog()
  10596. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10597. # cleanly rather than waiting on a queue that nothing will ever fill.
  10598. try:
  10599. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10600. await shutdown_all_broadcasters()
  10601. except Exception as e:
  10602. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10603. stop_expected_prints_cleanup()
  10604. stop_auth_cleanup()
  10605. from backend.app.services import announcements as announcements_service
  10606. announcements_service.stop()
  10607. from backend.app.services.printer_media import stop_printer_download_cleanup
  10608. await stop_printer_download_cleanup()
  10609. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10610. from backend.app.services import timelapse_jobs
  10611. await timelapse_jobs.cancel_all()
  10612. printer_manager.disconnect_all()
  10613. slot_unlink_grace.reset()
  10614. await close_spoolman_client()
  10615. # Stop all virtual printer services
  10616. await virtual_printer_manager.stop_all()
  10617. await mqtt_smart_plug_service.disconnect(timeout=2)
  10618. await mqtt_relay.disconnect(timeout=2)
  10619. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10620. set_shared_http_client(None)
  10621. set_shared_makerworld_http_client(None)
  10622. set_shared_orca_http_client(None)
  10623. await _shared_cloud_http_client.aclose()
  10624. # Checkpoint WAL (SQLite only) and close all database connections
  10625. from backend.app.core.db_dialect import is_sqlite
  10626. if is_sqlite():
  10627. try:
  10628. async with engine.begin() as conn:
  10629. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10630. logging.info("WAL checkpoint completed")
  10631. except Exception as e:
  10632. logging.warning("WAL checkpoint failed: %s", e)
  10633. await engine.dispose()
  10634. app = FastAPI(
  10635. title=app_settings.app_name,
  10636. description="Archive and manage Bambu Lab 3MF files",
  10637. version=APP_VERSION,
  10638. lifespan=lifespan,
  10639. )
  10640. # Added first so it sits innermost, next to the routes: a refused header's value
  10641. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10642. app.add_middleware(RefusedHeaderResponseMask)
  10643. def _json_safe(value):
  10644. """The validation errors with every non-finite number written as text."""
  10645. if isinstance(value, float) and not math.isfinite(value):
  10646. return str(value)
  10647. if isinstance(value, dict):
  10648. return {key: _json_safe(item) for key, item in value.items()}
  10649. if isinstance(value, list | tuple):
  10650. return [_json_safe(item) for item in value]
  10651. return value
  10652. @app.exception_handler(RequestValidationError)
  10653. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10654. """FastAPI's own 422, except that it survives a non-finite number.
  10655. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10656. them), and the default handler echoes the input back in its errors,
  10657. which JSON cannot hold: the request ended in an error instead of a 422.
  10658. """
  10659. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10660. # =============================================================================
  10661. # Authentication Middleware - Secures ALL API routes by default
  10662. # =============================================================================
  10663. # Public routes that don't require authentication even when auth is enabled
  10664. PUBLIC_API_ROUTES = {
  10665. # Auth routes needed before/during login
  10666. "/api/v1/auth/status",
  10667. "/api/v1/auth/login",
  10668. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10669. # Advanced auth status needed for login page
  10670. "/api/v1/auth/advanced-auth/status",
  10671. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10672. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10673. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10674. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10675. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10676. # OIDC routes that must be reachable without a JWT
  10677. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10678. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10679. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10680. # Connected apps: the app's server swaps a code for the user's identity,
  10681. # authenticated by its client secret rather than a login token.
  10682. "/api/v1/connect/token",
  10683. # Version check for updates (no sensitive data)
  10684. "/api/v1/updates/version",
  10685. # Metrics endpoint handles its own prometheus_token authentication
  10686. "/api/v1/metrics",
  10687. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10688. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10689. # hostname / timezone / locale and the chrony NTP-gate state. The
  10690. # response contains user-set defaults and a public sync flag — no
  10691. # secrets. Without this entry the global auth middleware returns 401
  10692. # before the route handler runs, regardless of the route's own
  10693. # "no auth required" intent.
  10694. "/api/v1/system/appliance",
  10695. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10696. # authenticates with a long-lived ``camwall``-scoped token in the query
  10697. # string — exactly like the camera streams two lists below, and for the same
  10698. # reason (no header to put a JWT in). "Public" here only means the middleware
  10699. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10700. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10701. # plain ``camera_stream`` token does NOT open this door.
  10702. "/api/v1/camwall/printers",
  10703. # Overlay branding: the route enforces overlay-scoped token authentication.
  10704. "/api/v1/overlay-branding/logo",
  10705. }
  10706. # Route prefixes that are public (for routes with dynamic segments)
  10707. PUBLIC_API_PREFIXES = [
  10708. # WebSocket connections handle their own auth
  10709. "/api/v1/ws",
  10710. # OIDC authorize redirects — include provider_id in path
  10711. "/api/v1/auth/oidc/authorize/",
  10712. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10713. # a phone with no session, so no header can carry a JWT — the single-use
  10714. # capability token in the path IS the credential (same reasoning as the
  10715. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10716. # good/reject on the one archive the token was minted for.
  10717. "/api/v1/archives/confirm/",
  10718. ]
  10719. # Route patterns that are public (read-only display data)
  10720. # These are checked with "in path" - needed because browsers load images/videos
  10721. # via <img src> and <video src> which don't include Authorization headers
  10722. PUBLIC_API_PATTERNS = [
  10723. # Thumbnails
  10724. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10725. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10726. # Images and media
  10727. "/photos/", # /archives/{id}/photos/{filename}
  10728. "/project-image/", # /archives/{id}/project-image/{path}
  10729. "/qrcode", # /archives/{id}/qrcode
  10730. "/timelapse", # /archives/{id}/timelapse (video)
  10731. "/cover", # /printers/{id}/cover
  10732. "/icon", # /external-links/{id}/icon
  10733. # Camera (streams loaded via <img> tag)
  10734. "/camera/stream", # /printers/{id}/camera/stream
  10735. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10736. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10737. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10738. # string (same reasoning as the camera streams above — no header to carry a
  10739. # JWT). "Public" only means the middleware steps aside; the route still runs
  10740. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10741. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10742. "/overlay-status", # /printers/{id}/overlay-status
  10743. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10744. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10745. # download token in the URL path instead.
  10746. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10747. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10748. # and these patterns match by substring. Without its own entry the middleware
  10749. # 401s the slicer's header-less request before the route's token check runs,
  10750. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10751. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10752. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10753. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10754. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10755. ]
  10756. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10757. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10758. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10759. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10760. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10761. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10762. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10763. Invalid entries are dropped with a warning rather than failing startup, so
  10764. a typo in one origin doesn't take the whole deployment down.
  10765. """
  10766. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10767. if not raw:
  10768. return ()
  10769. valid: list[str] = []
  10770. for item in raw.split(","):
  10771. candidate = item.strip()
  10772. if not candidate:
  10773. continue
  10774. try:
  10775. parsed = urlparse(candidate)
  10776. except ValueError as e:
  10777. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10778. continue
  10779. if parsed.scheme not in ("http", "https"):
  10780. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10781. continue
  10782. if not parsed.netloc:
  10783. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10784. continue
  10785. if parsed.path and parsed.path != "/":
  10786. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10787. continue
  10788. if parsed.query or parsed.fragment:
  10789. _security_headers_logger.warning(
  10790. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10791. )
  10792. continue
  10793. if "*" in parsed.netloc:
  10794. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10795. continue
  10796. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10797. if valid:
  10798. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10799. return tuple(valid)
  10800. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10801. def _frame_ancestors(default_value: str) -> str:
  10802. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10803. ``default_value`` is the strict directive used when the operator has not
  10804. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10805. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10806. Settings URL builder's preview). When trusted origins
  10807. are configured, ``'self'`` is always included so same-origin embedding never
  10808. breaks even if an operator forgets to add their own origin to the list.
  10809. """
  10810. if _TRUSTED_FRAME_ORIGINS:
  10811. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10812. return f"frame-ancestors {default_value};"
  10813. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10814. # patterns are anchored on the exact emitted name so the relaxed policies
  10815. # below can never apply to any other asset.
  10816. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10817. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10818. # -> /assets/pdf.worker.min-<hash>.js
  10819. # Vite also emits a one-line chunk under the second name that only exports the
  10820. # worker's URL. The page imports it as a module, and a module script is run
  10821. # under the importing document's policy, never its own response's, so it
  10822. # matching as well changes nothing.
  10823. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10824. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10825. @app.middleware("http")
  10826. async def security_headers_middleware(request, call_next):
  10827. """Add standard HTTP security headers to every response."""
  10828. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10829. # changes nothing for Bambuddy's own pages — index.html has no inline
  10830. # scripts since the SW registration moved to /sw-register.js. The reason
  10831. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10832. # script injected into the HTML on the edge, with a fresh hash on every
  10833. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10834. # it clones the same nonce onto its injected <script>, and the inline
  10835. # script passes the policy without us needing 'unsafe-inline'. See
  10836. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10837. csp_nonce = secrets.token_urlsafe(16)
  10838. # Routes that render their own HTML need it too, or their inline script is
  10839. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10840. # one that does: it submits its own form so a verdict still costs one tap.
  10841. request.state.csp_nonce = csp_nonce
  10842. response = await call_next(request)
  10843. response.headers["X-Content-Type-Options"] = "nosniff"
  10844. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10845. # browsers honour CSP frame-ancestors instead, and the legacy
  10846. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10847. # When operators have explicitly allowlisted trusted frame origins (#1191
  10848. # — typically Home Assistant on a different port), drop X-Frame-Options
  10849. # and let the CSP-side frame-ancestors directive govern embedding.
  10850. if not _TRUSTED_FRAME_ORIGINS:
  10851. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10852. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10853. # Content-Security-Policy for the React SPA.
  10854. # Notes:
  10855. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10856. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10857. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10858. # - media-src blob:: timelapse video player uses Blob URLs.
  10859. # - font-src data:: some icon fonts are embedded as data URIs.
  10860. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10861. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10862. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10863. # default CSP would render a blank page.
  10864. response.headers["Content-Security-Policy"] = (
  10865. "default-src 'self'; "
  10866. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10867. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10868. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10869. "connect-src 'self'; "
  10870. "font-src 'self' data: https://fonts.gstatic.com; "
  10871. "worker-src 'self' blob:; "
  10872. "object-src 'none'; "
  10873. "base-uri 'self'; " + _frame_ancestors("'none'")
  10874. )
  10875. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10876. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10877. # its emscripten/embind glue generates invoker functions with `new
  10878. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10879. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10880. # own response — not the document's — so relaxing it here confines
  10881. # eval to that DOM-less worker context. The document policy below
  10882. # stays nonce-strict, and this response header has no effect when the
  10883. # file is merely fetched (a fetch's CSP is enforced against the
  10884. # requesting document, not the resource's own headers).
  10885. response.headers["Content-Security-Policy"] = (
  10886. "default-src 'self'; "
  10887. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10888. "connect-src 'self'; "
  10889. "object-src 'none'; "
  10890. "base-uri 'self'; " + _frame_ancestors("'none'")
  10891. )
  10892. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10893. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10894. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10895. # rule as the STEP worker above: the policy that governs a dedicated
  10896. # worker is the one delivered with its own script, so the wasm compile
  10897. # has to be permitted here rather than on the document. Unlike the STEP
  10898. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10899. response.headers["Content-Security-Policy"] = (
  10900. "default-src 'self'; "
  10901. "script-src 'self' 'wasm-unsafe-eval'; "
  10902. "connect-src 'self'; "
  10903. "object-src 'none'; "
  10904. "base-uri 'self'; " + _frame_ancestors("'none'")
  10905. )
  10906. else:
  10907. # The streaming overlay is embedded same-origin by the URL builder's
  10908. # preview in Settings (#1422), so this branch allows 'self'.
  10909. # Embedding from anywhere else is still refused: 'self'
  10910. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10911. # a clickjacking page on another host is blocked exactly as before.
  10912. # (The overlay draws status over a camera feed and its only interactive
  10913. # element is the logo link, so there is nothing to bait a click into
  10914. # even from a same-origin framer.) Cross-origin embedding of the
  10915. # overlay — Home Assistant on another port — remains what
  10916. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10917. # allowlist in.
  10918. #
  10919. # The connected-app consent page (/connect/authorize) gets the same
  10920. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10921. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10922. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10923. # requires every ancestor to be this origin, so a foreign page -- a
  10924. # sidebar link's site included -- still cannot frame the consent
  10925. # screen to bait a click.
  10926. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10927. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10928. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10929. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10930. # the policy served with their own script, so each gets it in its own
  10931. # branch above and the document policy stays as strict as it was.
  10932. response.headers["Content-Security-Policy"] = (
  10933. "default-src 'self'; "
  10934. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10935. "style-src 'self' 'unsafe-inline'; "
  10936. "img-src 'self' data: blob:; "
  10937. "media-src 'self' blob:; "
  10938. "connect-src 'self' ws: wss:; "
  10939. "font-src 'self' data:; "
  10940. "object-src 'none'; "
  10941. "base-uri 'self'; "
  10942. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10943. )
  10944. if request.url.scheme == "https":
  10945. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10946. return response
  10947. @app.middleware("http")
  10948. async def auth_middleware(request, call_next):
  10949. """Enforce authentication on all API routes when auth is enabled.
  10950. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10951. regardless of whether individual routes have auth dependencies.
  10952. """
  10953. from starlette.responses import JSONResponse
  10954. path = request.url.path
  10955. # Only apply to API routes
  10956. if not path.startswith("/api/"):
  10957. return await call_next(request)
  10958. # Allow public routes
  10959. if path in PUBLIC_API_ROUTES:
  10960. return await call_next(request)
  10961. # Allow public prefixes
  10962. for prefix in PUBLIC_API_PREFIXES:
  10963. if path.startswith(prefix):
  10964. return await call_next(request)
  10965. # Allow public patterns (read-only display data like thumbnails)
  10966. for pattern in PUBLIC_API_PATTERNS:
  10967. if pattern in path:
  10968. return await call_next(request)
  10969. # Check if auth is enabled. Fail CLOSED on any exception during the
  10970. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10971. # an attacker who could force a DB exception (e.g. file-descriptor
  10972. # exhaustion via login flood) bypass auth on every protected endpoint.
  10973. # Only the probe is guarded: the request itself runs outside the try, so an
  10974. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10975. try:
  10976. async with async_session() as db:
  10977. from backend.app.core.auth import is_auth_enabled
  10978. auth_enabled = await is_auth_enabled(db)
  10979. except Exception:
  10980. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10981. return JSONResponse(
  10982. status_code=503,
  10983. content={"detail": "Authentication service temporarily unavailable"},
  10984. )
  10985. if not auth_enabled:
  10986. # Auth disabled, allow all requests
  10987. return await call_next(request)
  10988. # Auth is enabled - require valid token
  10989. auth_header = request.headers.get("Authorization")
  10990. x_api_key = request.headers.get("X-API-Key")
  10991. # Check for API key auth first
  10992. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10993. # API key authentication - let the request through to be validated by route handler
  10994. # API keys are validated per-route since they have different permission levels
  10995. return await call_next(request)
  10996. # Check for JWT auth
  10997. if not auth_header or not auth_header.startswith("Bearer "):
  10998. return JSONResponse(
  10999. status_code=401,
  11000. content={"detail": "Authentication required"},
  11001. headers={"WWW-Authenticate": "Bearer"},
  11002. )
  11003. # Validate JWT token
  11004. import jwt
  11005. try:
  11006. from backend.app.core.auth import (
  11007. ALGORITHM,
  11008. SECRET_KEY,
  11009. _is_token_fresh,
  11010. get_user_by_username,
  11011. is_jti_revoked,
  11012. )
  11013. token = auth_header.replace("Bearer ", "")
  11014. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11015. username = payload.get("sub")
  11016. if not username:
  11017. raise ValueError("No username in token")
  11018. jti = payload.get("jti")
  11019. if not jti:
  11020. raise ValueError("No jti in token")
  11021. iat = payload.get("iat")
  11022. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11023. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11024. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11025. async with async_session() as db:
  11026. if await is_jti_revoked(jti, db):
  11027. return JSONResponse(
  11028. status_code=401,
  11029. content={"detail": "Token has been revoked"},
  11030. headers={"WWW-Authenticate": "Bearer"},
  11031. )
  11032. user = await get_user_by_username(db, username)
  11033. if not user or not user.is_active:
  11034. return JSONResponse(
  11035. status_code=401,
  11036. content={"detail": "User not found or inactive"},
  11037. headers={"WWW-Authenticate": "Bearer"},
  11038. )
  11039. if not _is_token_fresh(iat, user):
  11040. return JSONResponse(
  11041. status_code=401,
  11042. content={"detail": "Token no longer valid"},
  11043. headers={"WWW-Authenticate": "Bearer"},
  11044. )
  11045. except jwt.ExpiredSignatureError:
  11046. return JSONResponse(
  11047. status_code=401,
  11048. content={"detail": "Token has expired"},
  11049. headers={"WWW-Authenticate": "Bearer"},
  11050. )
  11051. except (jwt.InvalidTokenError, ValueError):
  11052. return JSONResponse(
  11053. status_code=401,
  11054. content={"detail": "Invalid token"},
  11055. headers={"WWW-Authenticate": "Bearer"},
  11056. )
  11057. except Exception:
  11058. # Not a bad token but a failure checking it (database, pool): refuse,
  11059. # as for the probe above, rather than answer 401 -- the frontend reads
  11060. # a 401 from /auth/me as final and signs the user out.
  11061. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11062. return JSONResponse(
  11063. status_code=503,
  11064. content={"detail": "Authentication service temporarily unavailable"},
  11065. )
  11066. return await call_next(request)
  11067. @app.middleware("http")
  11068. async def trace_id_middleware(request, call_next):
  11069. """Stamp every HTTP request with a trace ID and echo it back.
  11070. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11071. @app.middleware decorators LIFO, so the last-decorated runs first
  11072. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11073. which means auth-middleware log lines (and every line emitted on the
  11074. way down to and back from the route handler) all carry the same
  11075. trace ID. If we put it before auth, auth's logs would be stamped
  11076. with the *previous* request's ID — useless for correlation.
  11077. Honours an inbound ``X-Trace-Id`` header so callers running their
  11078. own tracing can correlate their span IDs with our log lines, but
  11079. only if the value passes the whitelist gate in
  11080. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11081. rejected (too long, contains control chars, etc.) silently triggers
  11082. a freshly minted server-side ID rather than failing the request.
  11083. The minted (or echoed) ID is set on a ContextVar so that every log
  11084. record emitted during the request — application logs *and* uvicorn's
  11085. access log — carries it via TraceIDFilter, and is also written to
  11086. the ``X-Trace-Id`` response header so clients can pin a server-side
  11087. log search to the exact request they made.
  11088. """
  11089. from backend.app.core.trace import (
  11090. generate_trace_id,
  11091. normalise_inbound_trace_id,
  11092. trace_id_var,
  11093. )
  11094. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11095. trace_id = inbound if inbound is not None else generate_trace_id()
  11096. token = trace_id_var.set(trace_id)
  11097. try:
  11098. response = await call_next(request)
  11099. finally:
  11100. # Reset the ContextVar so a record emitted in a totally
  11101. # unrelated background task that just happens to inherit this
  11102. # context doesn't keep referencing this request's ID forever.
  11103. # In practice ContextVar.reset is best-effort under asyncio
  11104. # task-spawn semantics, but the cost is one attribute write so
  11105. # we may as well do it.
  11106. trace_id_var.reset(token)
  11107. response.headers["X-Trace-Id"] = trace_id
  11108. return response
  11109. # API routes
  11110. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11111. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11112. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11113. app.include_router(users.router, prefix=app_settings.api_prefix)
  11114. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11115. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11116. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11117. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11118. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11119. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11120. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11121. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11122. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11123. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11124. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11125. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11126. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11127. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11128. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11129. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11130. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11131. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11132. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11133. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11134. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11135. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11136. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11137. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11138. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11139. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11140. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11141. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11142. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11143. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11144. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11145. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11146. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11147. app.include_router(library.router, prefix=app_settings.api_prefix)
  11148. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11149. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11150. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11151. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11152. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11153. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11154. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11155. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11156. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11157. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11158. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11159. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11160. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11161. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11162. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11163. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11164. app.include_router(system.router, prefix=app_settings.api_prefix)
  11165. app.include_router(support.router, prefix=app_settings.api_prefix)
  11166. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11167. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11168. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11169. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11170. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11171. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11172. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11173. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11174. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11175. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11176. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11177. # Serve static files (React build)
  11178. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11179. # Compressed, and cached for good where Vite hashed the name (#3175).
  11180. app.mount(
  11181. "/assets",
  11182. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11183. name="assets",
  11184. )
  11185. if (app_settings.static_dir / "img").exists():
  11186. app.mount(
  11187. "/img",
  11188. StaticFiles(directory=app_settings.static_dir / "img"),
  11189. name="img",
  11190. )
  11191. if (app_settings.static_dir / "icons").exists():
  11192. app.mount(
  11193. "/icons",
  11194. StaticFiles(directory=app_settings.static_dir / "icons"),
  11195. name="icons",
  11196. )
  11197. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11198. # falls through to the SPA catch-all and returns index.html, which the
  11199. # browser's font sanitizer rejects ("downloadable font: rejected by
  11200. # sanitizer").
  11201. if (app_settings.static_dir / "fonts").exists():
  11202. app.mount(
  11203. "/fonts",
  11204. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11205. name="fonts",
  11206. )
  11207. @app.get("/")
  11208. async def serve_frontend():
  11209. """Serve the React frontend."""
  11210. index_file = app_settings.static_dir / "index.html"
  11211. if index_file.exists():
  11212. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11213. return {
  11214. "message": "Bambuddy API",
  11215. "docs": "/docs",
  11216. "frontend": "Build and place React app in /static directory",
  11217. }
  11218. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11219. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11220. # forever, but the HTML wrapping it is the only file that knows which hash
  11221. # is current. Without explicit cache-control headers Chromium decides
  11222. # heuristically (typically 10% of the time since Last-Modified) and on
  11223. # long-running kiosks happily serves stale HTML across browser restarts.
  11224. # That stale HTML references an old bundle hash, the old bundle is also
  11225. # in the disk cache, and the user ends up running pre-update JS forever
  11226. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11227. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11228. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11229. @app.get("/health")
  11230. async def health_check():
  11231. """Health check endpoint."""
  11232. return {"status": "healthy"}
  11233. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11234. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11235. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11236. # in deployment debugging.
  11237. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  11238. async def serve_manifest():
  11239. """Serve PWA manifest."""
  11240. manifest_file = app_settings.static_dir / "manifest.json"
  11241. if manifest_file.exists():
  11242. return FileResponse(manifest_file, media_type="application/manifest+json")
  11243. return {"error": "Manifest not found"}
  11244. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  11245. async def serve_service_worker():
  11246. """Serve service worker."""
  11247. sw_file = app_settings.static_dir / "sw.js"
  11248. if sw_file.exists():
  11249. return FileResponse(
  11250. sw_file,
  11251. media_type="application/javascript",
  11252. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11253. )
  11254. return {"error": "Service worker not found"}
  11255. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  11256. async def serve_sw_register():
  11257. """Serve the service-worker registration bootstrap script.
  11258. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11259. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11260. """
  11261. reg_file = app_settings.static_dir / "sw-register.js"
  11262. if reg_file.exists():
  11263. return FileResponse(reg_file, media_type="application/javascript")
  11264. return {"error": "sw-register.js not found"}
  11265. # ── GCode viewer static files ────────────────────────────────────────────────
  11266. # Catch-all route for React Router (must be last)
  11267. @app.get("/{full_path:path}")
  11268. async def serve_spa(full_path: str):
  11269. """Serve React app for client-side routing."""
  11270. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11271. if full_path.startswith("api/"):
  11272. from fastapi import HTTPException
  11273. raise HTTPException(status_code=404, detail="Not found")
  11274. index_file = app_settings.static_dir / "index.html"
  11275. if index_file.exists():
  11276. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11277. return {"error": "Frontend not built"}