main.py 613 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666
  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. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  465. # Used by usage tracker to map 3MF slots to physical AMS trays
  466. _print_ams_mappings: dict[int, list[int]] = {}
  467. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  468. _print_cost_center_ids: dict[int, int] = {}
  469. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  470. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  471. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  472. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  473. # for the queue path. Cleared on print completion or TTL eviction.
  474. _print_plate_ids: dict[int, int] = {}
  475. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  476. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  477. _last_progress_milestone: dict[int, int] = {}
  478. # Track whether first layer complete notification has been sent for current print
  479. _first_layer_notified: dict[int, bool] = {}
  480. # Track whether we already sent a kill-switch stop for the current unauthorized print
  481. _unauthorized_print_kill_sent: set[int] = set()
  482. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  483. # lookup briefly so an unknown active print does not query the database on
  484. # every status frame. A short TTL keeps settings changes responsive.
  485. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  486. _kill_switch_setting_cache: tuple[bool, float] | None = None
  487. # Provider notification started when the kill switch stops a print. The later
  488. # MQTT print-complete callback awaits this task and only sends its regular
  489. # provider notification when the immediate attempt failed.
  490. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  491. # HMS faults already notified, with when each was last seen:
  492. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  493. # fault that flickers beside a held notice was forgotten on every gap and
  494. # notified on every return (#3226). The window is long because the measured
  495. # gaps reach 64 s.
  496. _notified_hms_errors: dict[int, dict[str, float]] = {}
  497. _HMS_CLEAR_GRACE_SECONDS = 600.0
  498. # The print state each printer was last seen in, and the faults recorded before
  499. # it last changed, which are forgotten as soon as they are gone (see
  500. # _take_new_hms_faults).
  501. _hms_print_state: dict[int, str] = {}
  502. _hms_forget_when_gone: dict[int, set[str]] = {}
  503. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  504. # Used for snapshot-diff detection at print completion
  505. _timelapse_baselines: dict[int, set[str]] = {}
  506. # Printers whose baseline above was taken off a card that could not be read,
  507. # so it is empty without the card being empty (#3412).
  508. _timelapse_baselines_unread: set[int] = set()
  509. # Archives whose last run still has work after it completed: the timelapse
  510. # scan and the layer timelapse stitch. Both tell their run from a later one by
  511. # the archive's start time, so a queue dispatch of the same file must not start
  512. # a new run on the archive until they end (_claim_reusable_archive in the
  513. # scheduler). archive_id -> number of such tasks.
  514. _archive_runs_finishing: dict[int, int] = {}
  515. async def _while_run_finishes(archive_id: int, work):
  516. """Run ``work`` with the archive marked as still finishing its last run.
  517. Marked by the caller's spawn already: see ``_mark_run_finishing``."""
  518. try:
  519. return await work
  520. finally:
  521. left = _archive_runs_finishing.get(archive_id, 0) - 1
  522. if left > 0:
  523. _archive_runs_finishing[archive_id] = left
  524. else:
  525. _archive_runs_finishing.pop(archive_id, None)
  526. def _mark_run_finishing(archive_id: int, work):
  527. """``work`` wrapped to keep the archive marked until it ends. Marked now,
  528. before the task starts, so no dispatch between the spawn and its first
  529. step can take the archive."""
  530. _archive_runs_finishing[archive_id] = _archive_runs_finishing.get(archive_id, 0) + 1
  531. return _while_run_finishes(archive_id, work)
  532. # Track printers waiting for bed to cool after print completion.
  533. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  534. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  535. _bed_cool_waiters: dict[int, dict] = {}
  536. # Track printers where the user explicitly stopped the print from the queue UI.
  537. # When on_print_complete fires with status "failed" for these printers we treat it
  538. # as "cancelled" (stopped by user) so the correct notification email is sent.
  539. _user_stopped_printers: set[int] = set()
  540. # Printers whose running print the kill switch stopped. Their completion is a
  541. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  542. _kill_switch_stopped: set[int] = set()
  543. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  544. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  545. # holds the previous observation so we only fire on the True → False edge (a
  546. # False → False repeat doesn't notify; an initial False at startup doesn't
  547. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  548. # holds the per-printer pending asyncio task that fires the notification
  549. # after a debounce window — cancelled if the printer reconnects before the
  550. # window elapses, so transient MQTT blips don't flood the user.
  551. _printer_last_connected: dict[int, bool] = {}
  552. # Printers whose relay offline event went out, so the reconnect publishes the
  553. # matching online event and a blip shorter than the debounce publishes neither.
  554. _printer_offline_published: set[int] = set()
  555. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  556. # Debounce: a printer must stay offline this long before we notify. Sized
  557. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  558. # so a single stale-trigger cooldown isn't enough to fire — only a real
  559. # offline that survives one reconnect attempt notifies.
  560. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  561. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  562. # when status="failed" to label the print's failure_reason in archives.
  563. #
  564. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  565. # which is wrong on two counts:
  566. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  567. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  568. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  569. # the public wiki) as part of its user-cancel sequence. Matching on the module
  570. # alone caused user-cancellations to be archived as "Layer shift" failures.
  571. # We now match by full short code only — anything not in this map leaves
  572. # failure_reason=None rather than guessing.
  573. # Values are the canonical camelCase failure-reason keys, NOT display labels
  574. # (issue #2974). The vocabulary is enforced on writes by
  575. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  576. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  577. # Statistics breakdown. Storing a label here instead put a second spelling of
  578. # the same cause into one column: the Failure Analysis widget groups on the raw
  579. # value, so a print the backend classified and an identical one a user
  580. # classified counted as two different reasons, and the label form could never
  581. # be translated because there was no key for ``t()`` to resolve.
  582. _HMS_FAILURE_REASONS: dict[str, str] = {
  583. # Layer shift / step loss
  584. "0300_4057": "layerShift",
  585. "0300_4068": "layerShift",
  586. "0300_800C": "layerShift",
  587. # Filament runout (printer-side & per-AMS-slot)
  588. "0300_8004": "filamentRunout",
  589. "0700_8011": "filamentRunout",
  590. "0701_8011": "filamentRunout",
  591. "0702_8011": "filamentRunout",
  592. "0703_8011": "filamentRunout",
  593. "0704_8011": "filamentRunout",
  594. "0705_8011": "filamentRunout",
  595. "0706_8011": "filamentRunout",
  596. "0707_8011": "filamentRunout",
  597. "07FF_8011": "filamentRunout",
  598. # Clogged nozzle / extruder
  599. "0300_4006": "cloggedNozzle",
  600. "0300_8016": "cloggedNozzle",
  601. "0300_801C": "cloggedNozzle",
  602. "0700_8003": "cloggedNozzle",
  603. "0700_8007": "cloggedNozzle",
  604. "0700_8013": "cloggedNozzle",
  605. "0701_8003": "cloggedNozzle",
  606. "0701_8007": "cloggedNozzle",
  607. "0701_8013": "cloggedNozzle",
  608. "0702_8003": "cloggedNozzle",
  609. # AI print monitoring — spaghetti / the model coming off the plate.
  610. # `spaghettiDetached` is a key the archive editor already offers for this
  611. # failure mode, not a new one, so a derived reason opens the dropdown on
  612. # that option rather than blank — and survives the next save, which clears
  613. # any value the editor does not recognise.
  614. #
  615. # A module-0x0C row is safe here despite the warning above: that warning is
  616. # about matching on the module alone, and 0C00_8042 is a full short code
  617. # with a documented meaning ("The AI print monitor has detected a spaghetti
  618. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  619. # cannot collide.
  620. #
  621. # 0300_8003's own text ends "before continuing your print", but on an X2D
  622. # it arrives with the print already paused, offering only
  623. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  624. #
  625. # Two neighbours are left out on purpose, so this does not get re-derived:
  626. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  627. # reads as a warning about a print that is still running, not a halt.
  628. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  629. # the waste chute. That is not the print failing.
  630. #
  631. # That line is drawn from the text, not from `severity`, because severity
  632. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  633. # module/error word with no level in it, and bambu_mqtt.py gives every
  634. # print_error entry a flat severity=3. Matching on the short code alone is
  635. # the right shape for derive_failure_reason, not an omission.
  636. "0300_8003": "spaghettiDetached",
  637. "0C00_8042": "spaghettiDetached",
  638. }
  639. def _hms_short_code(attr: int, code: int | str) -> str:
  640. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  641. if isinstance(code, str):
  642. code_int = int(code.replace("0x", ""), 16) if code else 0
  643. else:
  644. code_int = int(code or 0)
  645. attr_int = int(attr or 0)
  646. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  647. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  648. """Derive the failure_reason key for an archived print.
  649. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  650. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  651. no HMS code matches (don't guess — null is honest). The keys are the
  652. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  653. translated at render time.
  654. """
  655. if status in ("aborted", "cancelled"):
  656. return "userCancelled"
  657. if status != "failed":
  658. return None
  659. for err in hms_errors or []:
  660. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  661. if short_code in _HMS_FAILURE_REASONS:
  662. return _HMS_FAILURE_REASONS[short_code]
  663. return None
  664. # Track created_by_id for expected prints so the user email can be sent even when
  665. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  666. # {(printer_id, filename): created_by_id}
  667. _expected_print_creators: dict[tuple[int, str], int] = {}
  668. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  669. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  670. # tag tuple changes for the slot. Cleared when the slot is reported empty
  671. # so remove + reinsert reliably re-prompts the UI.
  672. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  673. async def _broadcast_unknown_tag(
  674. *,
  675. printer_id: int,
  676. ams_id: int,
  677. tray_id: int,
  678. tag_uid: str,
  679. tray_uuid: str,
  680. tray_type: str | None = None,
  681. tray_color: str | None = None,
  682. tray_sub_brands: str | None = None,
  683. tray_count: int | None = None,
  684. ) -> None:
  685. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  686. _logger = logging.getLogger(__name__)
  687. slot_key = (ams_id, tray_id)
  688. tag_key = (tag_uid or "", tray_uuid or "")
  689. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  690. if per_printer.get(slot_key) == tag_key:
  691. _logger.debug(
  692. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  693. printer_id,
  694. ams_id,
  695. tray_id,
  696. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  697. )
  698. return
  699. _logger.info(
  700. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  701. printer_id,
  702. ams_id,
  703. tray_id,
  704. tray_type,
  705. tray_color,
  706. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  707. )
  708. # Broadcast first; only commit the dedup if the WS write succeeds.
  709. # If broadcast raises, the next MQTT push retries instead of being
  710. # permanently silenced by a poisoned dedup entry.
  711. await ws_manager.broadcast(
  712. {
  713. "type": "unknown_tag",
  714. "printer_id": printer_id,
  715. "ams_id": ams_id,
  716. "tray_id": tray_id,
  717. "tag_uid": tag_uid,
  718. "tray_uuid": tray_uuid,
  719. "tray_type": tray_type,
  720. "tray_color": tray_color,
  721. "tray_sub_brands": tray_sub_brands,
  722. "tray_count": tray_count,
  723. }
  724. )
  725. per_printer[slot_key] = tag_key
  726. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  727. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  728. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  729. if per_printer is None:
  730. return
  731. per_printer.pop((ams_id, tray_id), None)
  732. # TTL for expected-print entries: evict registrations older than this to prevent
  733. # unbounded growth when a print is registered but never starts (e.g. printer
  734. # disconnect, app restart, print started from the printer panel).
  735. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  736. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  737. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  738. # Cleanup loop interval
  739. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  740. _expected_prints_cleanup_task: asyncio.Task | None = None
  741. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  742. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  743. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  744. possible_keys: list[tuple[int, str]] = []
  745. filename = (state.gcode_file or state.current_print or "").strip()
  746. subtask_name = (state.subtask_name or "").strip()
  747. if subtask_name:
  748. possible_keys.append((printer_id, subtask_name))
  749. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  750. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  751. if filename:
  752. base_name = filename.rsplit("/", 1)[-1]
  753. if base_name.endswith(".gcode.3mf"):
  754. root_name = base_name[: -len(".gcode.3mf")]
  755. possible_keys.append((printer_id, root_name))
  756. possible_keys.append((printer_id, base_name))
  757. possible_keys.append((printer_id, f"{root_name}.gcode"))
  758. possible_keys.append((printer_id, f"{root_name}.3mf"))
  759. elif base_name.endswith(".3mf"):
  760. root_name = base_name[: -len(".3mf")]
  761. possible_keys.append((printer_id, root_name))
  762. possible_keys.append((printer_id, base_name))
  763. elif base_name.endswith(".gcode"):
  764. root_name = base_name[: -len(".gcode")]
  765. possible_keys.append((printer_id, root_name))
  766. possible_keys.append((printer_id, f"{root_name}.3mf"))
  767. possible_keys.append((printer_id, base_name))
  768. else:
  769. possible_keys.append((printer_id, base_name))
  770. possible_keys.append((printer_id, f"{base_name}.3mf"))
  771. return possible_keys
  772. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  773. """The id of who started the print, unless that user has been deleted since.
  774. Deleting a user forgets them in printer_manager, but a print that ended a
  775. moment before still holds them.
  776. """
  777. if not print_user or print_user.get("user_id") is None:
  778. return None
  779. from backend.app.models.user import User
  780. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  781. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  782. """Check the cheap, process-local print ownership signals."""
  783. if printer_manager.get_current_print_user(printer_id):
  784. return True
  785. return any(
  786. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  787. for key in _build_status_print_keys(printer_id, state)
  788. )
  789. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  790. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  791. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  792. async def _printing_archive_without_job_id(
  793. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  794. ):
  795. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  796. An archive with a real id of its own is a print that reported one: a "0"
  797. print is not it, even under the same name (one whose completion was missed
  798. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  799. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  800. """
  801. from backend.app.models.archive import PrintArchive
  802. query = select(PrintArchive).where(
  803. PrintArchive.printer_id == printer_id,
  804. PrintArchive.status == "printing",
  805. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  806. )
  807. if dispatched_only:
  808. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  809. if live_only:
  810. query = query.where(PrintArchive.deleted_at.is_(None))
  811. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  812. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  813. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  814. """The archive of the print running on ``printer_id``, or None (#3327).
  815. By the print's subtask_id first, which the firmware mints per print; with
  816. ``printing_only`` only an archive that is still printing (a leftover row of
  817. a completion never seen must not stand in for another job). A print
  818. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  819. screen) reports subtask_id "0", which links it to nothing: the archive
  820. Bambuddy bound to the running print comes next, the one completion charges
  821. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  822. own prints, so with ``by_name`` a "0" print last falls back to its printing
  823. archive under the name the printer reports. That can be an earlier run of
  824. the same name whose completion was missed while Bambuddy was down: good
  825. enough for a plate label or a cover, not for which objects skip-objects
  826. offers, so those callers leave it off. None until the archive exists, and
  827. never a deleted one.
  828. """
  829. from backend.app.models.archive import PrintArchive
  830. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  831. if subtask_id not in ("", "0"):
  832. query = select(PrintArchive).where(
  833. PrintArchive.printer_id == printer_id,
  834. PrintArchive.subtask_id == subtask_id,
  835. PrintArchive.deleted_at.is_(None),
  836. )
  837. if printing_only:
  838. query = query.where(PrintArchive.status == "printing")
  839. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  840. if archive is not None:
  841. return archive
  842. bound = next(
  843. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  844. None,
  845. )
  846. if bound is not None:
  847. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  848. if not by_name or subtask_id != "0":
  849. return None
  850. reported = _reported_print_names(printer_id, state)
  851. if not reported:
  852. return None
  853. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  854. def _bind_active_print(
  855. printer_id: int,
  856. archive_id: int,
  857. archive_filename: str | None,
  858. filename: str | None = None,
  859. subtask_name: str | None = None,
  860. ) -> None:
  861. """Track a running print under every name its completion may report.
  862. One set for every path that binds a print (new archive, expected print,
  863. restart resume, fallback): the archive's file name, the name the printer
  864. reported, and the subtask with and without ``.3mf``. Paths that registered
  865. fewer names lost the bound archive at completion, and with it the plate
  866. restore's height (#3240), whenever MQTT reported a name they had left out.
  867. """
  868. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  869. if name:
  870. _active_prints[(printer_id, name)] = archive_id
  871. async def _discard_open_runs_of(printer_id: int) -> None:
  872. """Drop the printer's open runs when its print ended with no archive to
  873. end them on. Its own session; never in the way of the completion."""
  874. try:
  875. from backend.app.services.print_log import discard_open_runs
  876. async with async_session() as db:
  877. await discard_open_runs(db, printer_id)
  878. await db.commit()
  879. except Exception as e:
  880. logging.getLogger(__name__).warning("[RUN] Could not drop the open runs of printer %s: %s", printer_id, e)
  881. async def _open_run_for(archive_id: int, printer_id: int) -> None:
  882. """Write the run of the print that just started on the archive (archive
  883. redesign). In a session of its own and never in the way of the print
  884. start: until its readers move over, the archive still carries the print.
  885. The archive's start must be committed before."""
  886. try:
  887. from backend.app.models.archive import PrintArchive
  888. from backend.app.models.printer import Printer
  889. from backend.app.services.print_log import open_run
  890. async with async_session() as db:
  891. archive = await db.get(PrintArchive, archive_id)
  892. if archive is None:
  893. return
  894. printer_name = await db.scalar(select(Printer.name).where(Printer.id == printer_id))
  895. await open_run(
  896. db, archive, printer_id=printer_id, printer_name=printer_name, plate_id=_print_plate_ids.get(archive_id)
  897. )
  898. await db.commit()
  899. except Exception as e:
  900. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  901. def _mark_owned_if_dispatched(archive) -> None:
  902. """Remember a running print's archive as Bambuddy's when it carries a
  903. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  904. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  905. if archive.billing_run_id is not None or archive.created_by_id is not None:
  906. _owned_print_archive_ids.add(archive.id)
  907. async def _is_printer_kill_switch_enabled_cached() -> bool:
  908. """Return the kill-switch setting without querying on every MQTT frame."""
  909. global _kill_switch_setting_cache
  910. now = time.monotonic()
  911. if _kill_switch_setting_cache is not None:
  912. enabled, expires_at = _kill_switch_setting_cache
  913. if now < expires_at:
  914. return enabled
  915. async with async_session() as db:
  916. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  917. enabled = await is_printer_kill_switch_enabled(db)
  918. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  919. return enabled
  920. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  921. """Resolve whether the current print was started by Bambuddy.
  922. ``None`` means identity is not yet safe to decide. The kill switch must
  923. defer in that case: stopping a print is irreversible, and the first status
  924. frames after a restart may arrive before all subtask fields are populated.
  925. """
  926. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  927. return True
  928. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  929. # printer's screen) play gcode from its read-only system partition, where no
  930. # user file can be. Only that path counts: a calibration *name* proves
  931. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  932. # path, and any print can be given that name.
  933. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  934. return True
  935. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  936. # which nothing distinguishes from a user's file given that name, so it is
  937. # not exempt: with the kill switch on, calibrate on those printers with the
  938. # switch off.
  939. possible_keys = _build_status_print_keys(printer_id, state)
  940. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  941. # is on disk. subtask_id is minted per print and pins the answer to the job
  942. # actually running, rather than to an unrelated one that reuses a filename.
  943. raw_subtask_id = getattr(state, "subtask_id", None)
  944. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  945. if subtask_id == "":
  946. # Not reported yet: the first frames after a restart can lack it.
  947. return None
  948. from backend.app.models.archive import PrintArchive
  949. if subtask_id == "0":
  950. # A print started outside the cloud from Bambu Studio, Handy or the
  951. # printer's screen reports "0", so there is no id to match: one of
  952. # Bambuddy's printing archives on this printer under the name the
  953. # printer reports, compared as the printer echoes names (spaces become
  954. # underscores). Nothing reported to compare yet: wait.
  955. reported = _reported_print_names(printer_id, state)
  956. if not reported:
  957. return None
  958. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  959. else:
  960. result = await db.execute(
  961. select(PrintArchive)
  962. .where(
  963. PrintArchive.printer_id == printer_id,
  964. PrintArchive.status == "printing",
  965. PrintArchive.subtask_id == subtask_id,
  966. )
  967. .order_by(PrintArchive.created_at.desc())
  968. .limit(1)
  969. )
  970. archive = result.scalar_one_or_none()
  971. # An archive row on its own proves nothing: `on_print_start` archives every
  972. # print it observes, including ones started from Bambu Studio or Handy, and
  973. # stamps them with the same status and subtask_id. Authorizing on its mere
  974. # existence would disable the kill switch the moment the 3MF finishes
  975. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  976. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  977. # (carried over from the queue item that started it).
  978. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  979. # Rehydrate the fast in-memory path for subsequent status frames. Include
  980. # both the archive filename and every normalized key reported by MQTT.
  981. _owned_print_archive_ids.add(archive.id)
  982. _active_prints[(printer_id, archive.filename)] = archive.id
  983. for key in possible_keys:
  984. _active_prints[key] = archive.id
  985. return True
  986. # No dispatch marker. Before calling this someone else's print, check whether
  987. # Bambuddy has a job of its own running on this printer: a library-file
  988. # dispatch has no archive at send time, and an archive created seconds later
  989. # by `on_print_start` carries neither marker. The queue row, which the
  990. # scheduler commits to status="printing" before the MQTT send, is the one
  991. # durable record every Bambuddy print has. It cannot be tied to this
  992. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  993. # print is irreversible, and refusing to act costs nothing but a log line.
  994. from backend.app.models.print_queue import PrintQueueItem
  995. dispatched_here = await db.scalar(
  996. select(PrintQueueItem.id)
  997. .where(
  998. PrintQueueItem.printer_id == printer_id,
  999. PrintQueueItem.status == "printing",
  1000. )
  1001. .limit(1)
  1002. )
  1003. if dispatched_here is not None:
  1004. return None
  1005. return False
  1006. async def _send_kill_switch_provider_notification(
  1007. printer_id: int,
  1008. printer_name: str,
  1009. data: dict,
  1010. ) -> bool:
  1011. """Send the immediate print-stopped provider notification.
  1012. Returning a success flag lets the normal MQTT completion path retry when
  1013. this early notification could not be delivered.
  1014. """
  1015. logger = logging.getLogger(__name__)
  1016. try:
  1017. async with async_session() as db:
  1018. await notification_service.on_print_complete(
  1019. printer_id,
  1020. printer_name,
  1021. "stopped",
  1022. data,
  1023. db,
  1024. )
  1025. return True
  1026. except Exception as e:
  1027. logger.warning(
  1028. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1029. printer_id,
  1030. e,
  1031. )
  1032. return False
  1033. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1034. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1035. if task is None:
  1036. return False
  1037. try:
  1038. return await task
  1039. except Exception as e:
  1040. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1041. return False
  1042. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1043. """Capture the smart plug lifetime counter on the archive at print start.
  1044. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1045. tracking survives a backend restart mid-print. The print-end handler reads
  1046. this value back from the DB and computes the delta against the current
  1047. plug counter.
  1048. """
  1049. _logger = logging.getLogger(__name__)
  1050. try:
  1051. candidates = await energy_plug_candidates(db, printer_id)
  1052. if not candidates:
  1053. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1054. return False
  1055. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1056. if selected is None:
  1057. # Naming the plugs matters here: with several linked to one printer
  1058. # this is the difference between "the meter is offline" and "you
  1059. # linked only accessories" (#2859).
  1060. _logger.warning(
  1061. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1062. printer_id,
  1063. archive.id,
  1064. ", ".join(plug.name for plug in candidates),
  1065. )
  1066. return False
  1067. plug, energy = selected
  1068. archive.energy_start_kwh = float(energy["total"])
  1069. # With the plug's snapshots, what lets the cost follow the price over
  1070. # the print rather than take the price at its end (#1251). A price that
  1071. # can't be had must not cost the print its energy reading.
  1072. archive.energy_start_at = utcnow_naive()
  1073. archive.energy_start_plug_id = plug.id
  1074. try:
  1075. from backend.app.services.energy_price import current_price
  1076. archive.energy_start_price = await current_price(db)
  1077. except Exception as e:
  1078. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1079. archive.energy_start_price = None
  1080. try:
  1081. from backend.app.services.print_log import mirror_energy_start
  1082. await mirror_energy_start(db, archive, printer_id=printer_id)
  1083. except Exception as e:
  1084. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1085. await db.commit()
  1086. _logger.info(
  1087. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1088. f" ({context})" if context else "",
  1089. archive.id,
  1090. plug.name,
  1091. energy["total"],
  1092. )
  1093. return True
  1094. except Exception as e:
  1095. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1096. return False
  1097. def forget_print_creator(user_id: int) -> None:
  1098. """The print-start emails of a deleted user's jobs go to nobody, not to
  1099. whoever is given the id next (SQLite reuses it)."""
  1100. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1101. del _expected_print_creators[key]
  1102. async def forget_printer(printer_id: int) -> None:
  1103. """Drop what is kept for a deleted printer's id, here and in the services.
  1104. SQLite used to give the id to the next printer created, which inherited it
  1105. all: the running print's owner (its prints passed the kill switch and were
  1106. billed to that user), the plate-clear gate, pending and suppressed
  1107. notifications, the camera feed, the plate references. Ids are no longer
  1108. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1109. stay. Called after the delete is committed, and again by work that was in
  1110. flight and wrote state back.
  1111. Every printer-keyed map of this module is listed here or, with the reason,
  1112. in tests/unit/test_forget_printer.py.
  1113. """
  1114. from backend.app.api.routes import camera
  1115. from backend.app.services import (
  1116. bambu_ftp,
  1117. kprofile_drift,
  1118. layer_timelapse,
  1119. plate_detection,
  1120. print_dispatch_context,
  1121. usage_tracker,
  1122. )
  1123. from backend.app.services.notify_live_activities import notify_live_activities
  1124. from backend.app.services.obico_detection import obico_detection_service
  1125. from backend.app.services.printer_file_cache import printer_file_cache
  1126. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1127. archive_ids = set()
  1128. for tracked in (_active_prints, _expected_prints):
  1129. for key in [key for key in tracked if key[0] == printer_id]:
  1130. archive_ids.add(tracked.pop(key))
  1131. for archive_id in archive_ids:
  1132. _owned_print_archive_ids.discard(archive_id)
  1133. _print_ams_mappings.pop(archive_id, None)
  1134. _print_cost_center_ids.pop(archive_id, None)
  1135. _print_plate_ids.pop(archive_id, None)
  1136. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1137. for key in [key for key in tracked if key[0] == printer_id]:
  1138. del tracked[key]
  1139. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1140. _ams_index_only_logged.discard(key)
  1141. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1142. del _ams_alarm_cooldown[key]
  1143. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1144. # A kill-switch notice is about a stop that happened and is left to finish.
  1145. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1146. task = tasks.pop(printer_id, None)
  1147. if task is not None:
  1148. task.cancel()
  1149. for keyed in (
  1150. _stage22_finish_frames,
  1151. _stage22_finish_in_flight,
  1152. _inprint_frame_bank,
  1153. _inprint_frame_bank_ts,
  1154. _printer_reconciled_since_connect,
  1155. _printer_kprofiles_primed_since_connect,
  1156. _last_progress_milestone,
  1157. _first_layer_notified,
  1158. _kill_switch_notification_tasks,
  1159. _notified_hms_errors,
  1160. _hms_print_state,
  1161. _hms_forget_when_gone,
  1162. _timelapse_baselines,
  1163. _bed_cool_waiters,
  1164. _printer_last_connected,
  1165. _unknown_tag_last_broadcast,
  1166. _last_status_broadcast,
  1167. _connection_watchdog_last_attempt,
  1168. ):
  1169. keyed.pop(printer_id, None)
  1170. for marked in (
  1171. _unauthorized_print_kill_sent,
  1172. _user_stopped_printers,
  1173. _kill_switch_stopped,
  1174. _printer_offline_published,
  1175. _nozzle_count_updated,
  1176. _runtime_seen_connected,
  1177. _timelapse_baselines_unread,
  1178. ):
  1179. marked.discard(printer_id)
  1180. printer_manager.forget_printer(printer_id)
  1181. printer_file_cache.forget_printer(printer_id)
  1182. print_dispatch_context.clear(printer_id)
  1183. kprofile_drift.forget_printer(printer_id, deleted=True)
  1184. layer_timelapse.cancel_session(printer_id)
  1185. usage_tracker.forget_printer(printer_id)
  1186. obico_detection_service.forget_printer(printer_id)
  1187. bambu_ftp.clear_3mf_cache(printer_id)
  1188. await camera.forget_printer(printer_id)
  1189. printers.clear_cover_cache(printer_id)
  1190. print_scheduler.forget_printer(printer_id)
  1191. notify_live_activities.forget_printer(printer_id)
  1192. plate_detection.remove_printer_references(printer_id)
  1193. def register_expected_print(
  1194. printer_id: int,
  1195. filename: str,
  1196. archive_id: int,
  1197. ams_mapping: list[int] | None = None,
  1198. created_by_id: int | None = None,
  1199. cost_center_id: int | None = None,
  1200. plate_id: int | None = None,
  1201. ):
  1202. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1203. # Store with multiple filename variations to catch different naming patterns
  1204. _expected_prints[(printer_id, filename)] = archive_id
  1205. # Also store without .3mf extension if present
  1206. if filename.endswith(".3mf"):
  1207. base = filename[:-4]
  1208. _expected_prints[(printer_id, base)] = archive_id
  1209. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1210. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1211. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1212. # path attributes the whole file's filament total to the spool instead of just
  1213. # the printed plate (#1697). They describe this dispatch: one that has none
  1214. # drops what an earlier dispatch of the archive left (sent, never started),
  1215. # unless a plate of the archive is printing now and still needs them.
  1216. archive_printing = archive_id in set(_active_prints.values())
  1217. if ams_mapping is not None:
  1218. _print_ams_mappings[archive_id] = ams_mapping
  1219. elif not archive_printing:
  1220. _print_ams_mappings.pop(archive_id, None)
  1221. if cost_center_id is not None:
  1222. _print_cost_center_ids[archive_id] = cost_center_id
  1223. elif not archive_printing:
  1224. _print_cost_center_ids.pop(archive_id, None)
  1225. if plate_id is not None:
  1226. _print_plate_ids[archive_id] = plate_id
  1227. elif not archive_printing:
  1228. _print_plate_ids.pop(archive_id, None)
  1229. # Store created_by_id so the user start email can be sent even when the archive
  1230. # itself has no created_by_id (e.g. library-file-based queue prints)
  1231. if created_by_id is not None:
  1232. _expected_print_creators[(printer_id, filename)] = created_by_id
  1233. if filename.endswith(".3mf"):
  1234. base = filename[:-4]
  1235. _expected_print_creators[(printer_id, base)] = created_by_id
  1236. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1237. # Record registration time for TTL-based eviction
  1238. _registered_at = time.monotonic()
  1239. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1240. if filename.endswith(".3mf"):
  1241. base = filename[:-4]
  1242. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1243. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1244. logging.getLogger(__name__).info(
  1245. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1246. )
  1247. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1248. """Undo :func:`register_expected_print` when the print never went out.
  1249. Registration has to happen *before* the MQTT print command, because the
  1250. printer can report the print before the line after the send executes. So
  1251. every path that registers and then fails to send — a cancel winning the
  1252. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1253. between — leaves an expectation for a print that will never arrive.
  1254. The TTL sweep evicts those after two hours, which is far longer than it
  1255. takes a user to react to a failed dispatch by pressing print again: that
  1256. reprint would be folded into the *old* archive and take the stale
  1257. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1258. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1259. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1260. are keyed by archive, not by file, so they may only be dropped once no
  1261. live key still points at that archive.
  1262. """
  1263. keys = [(printer_id, filename)]
  1264. if filename.endswith(".3mf"):
  1265. base = filename[:-4]
  1266. keys.append((printer_id, base))
  1267. keys.append((printer_id, f"{base}.gcode"))
  1268. removed = False
  1269. for key in keys:
  1270. if _expected_prints.pop(key, None) is not None:
  1271. removed = True
  1272. _expected_print_creators.pop(key, None)
  1273. _expected_print_registered_at.pop(key, None)
  1274. # Still needed by another expected print of the archive, or a plate of it
  1275. # that is printing, as in the sweep.
  1276. if archive_id not in set(_expected_prints.values()) | set(_active_prints.values()):
  1277. _print_ams_mappings.pop(archive_id, None)
  1278. _print_cost_center_ids.pop(archive_id, None)
  1279. _print_plate_ids.pop(archive_id, None)
  1280. if removed:
  1281. logging.getLogger(__name__).info(
  1282. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1283. printer_id,
  1284. filename,
  1285. archive_id,
  1286. )
  1287. def _compute_run_filament_grams(
  1288. status: str,
  1289. archive_filament_used_grams: float | None,
  1290. progress: float | int | None,
  1291. usage_results: list[dict] | None,
  1292. ) -> float | None:
  1293. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1294. Priority for every status:
  1295. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1296. weight delta — same source that drives "Total Consumed" on the
  1297. Inventory page, so Stats and Inventory totals stay aligned).
  1298. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1299. back to the canonical "this print used X" value).
  1300. 3. For partial statuses: ``estimate * progress%``.
  1301. 4. ``None`` if nothing is known.
  1302. """
  1303. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1304. if tracked_grams > 0:
  1305. return round(tracked_grams, 1)
  1306. if status == "completed":
  1307. return archive_filament_used_grams
  1308. if archive_filament_used_grams:
  1309. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1310. if scale > 0:
  1311. return round(archive_filament_used_grams * scale, 1)
  1312. return None
  1313. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1314. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1315. stored_ams_mapping = data.get("ams_mapping")
  1316. if not stored_ams_mapping and archive_id:
  1317. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1318. return stored_ams_mapping
  1319. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1320. """Resolve plate_id for print start without consuming stored direct-Print state.
  1321. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1322. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1323. read it back at print-start without popping (the entry is popped on print
  1324. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1325. """
  1326. if archive_id is None:
  1327. return None
  1328. return _print_plate_ids.get(archive_id)
  1329. def _partial_progress_scale(progress: int | float | None) -> float:
  1330. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1331. Used by every site that multiplies a "would-have-used" slicer estimate
  1332. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1333. so the three sites in ``_background_notifications`` (and the per-plate
  1334. override helper) can't drift apart on the coercion shape.
  1335. """
  1336. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1337. def _scope_notification_archive_data_to_plate(
  1338. archive_data: dict,
  1339. archive_file_path: str | None,
  1340. plate_id: int | None,
  1341. print_status: str,
  1342. progress: int | float | None,
  1343. base_dir: Path,
  1344. ) -> dict:
  1345. """Override summed-across-plates totals in ``archive_data`` with the values
  1346. for ``plate_id`` so the completion notification reports what was actually
  1347. printed, not the whole project (#1785).
  1348. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1349. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1350. the archive card's "whole project" headline, wrong for the completion
  1351. notification of a single-plate print. The queue UI already re-reads the
  1352. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1353. notification payload (filament grams, time estimate, per-slot breakdown).
  1354. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1355. no per-plate values — in every fail case the original ``archive_data`` is
  1356. returned unchanged so the notification still sends.
  1357. """
  1358. if plate_id is None or not archive_file_path:
  1359. return archive_data
  1360. from backend.app.utils.threemf_tools import (
  1361. extract_filament_usage_from_3mf,
  1362. extract_print_time_from_3mf,
  1363. )
  1364. archive_path = base_dir / archive_file_path
  1365. if not archive_path.exists():
  1366. return archive_data
  1367. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1368. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1369. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1370. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1371. if plate_time:
  1372. archive_data["print_time_seconds"] = plate_time
  1373. # Gate both the grams headline AND the per-slot breakdown on the same
  1374. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1375. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1376. # to the project-level grams the archive columns already provide rather
  1377. # than ship a project-level headline next to an all-zero per-plate
  1378. # breakdown.
  1379. if plate_grams > 0:
  1380. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1381. archive_data["filament_slots"] = [
  1382. {
  1383. "slot_id": s.get("slot_id"),
  1384. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1385. "type": s.get("type", ""),
  1386. "color": s.get("color", ""),
  1387. }
  1388. for s in plate_slots
  1389. ]
  1390. return archive_data
  1391. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1392. """Best-effort filament metadata from the MQTT print-start snapshot.
  1393. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1394. file during print, see #1533) so the fallback PrintArchive still has
  1395. enough filament info to support the inventory views and AMS-expansion
  1396. planning the operator opens it for. Returns a dict with optional
  1397. ``filament_type`` and ``filament_color`` keys in the same
  1398. comma-separated format the 3MF extractor produces, so the rest of the
  1399. codebase treats the fallback archive identically to a normal one.
  1400. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1401. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1402. entries). When supplied, only the slots actually consumed by this
  1403. print contribute. Without it the function falls back to every loaded
  1404. AMS slot — less accurate but still useful.
  1405. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1406. that the unit tests pass directly, AND the on_print_start callback
  1407. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1408. bambu_mqtt service hands to main.py at runtime. The original
  1409. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1410. handled the inner shape and silently returned ``{}`` for every real
  1411. print start, leaving fallback archives' filament fields NULL — the
  1412. exact regression the fix was meant to close. Reported with a log
  1413. proving the AMS state was right there at
  1414. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1415. """
  1416. result: dict[str, str] = {}
  1417. # Look at the on_print_start wrapper first, then the inner shape.
  1418. raw_data = (data or {}).get("raw_data")
  1419. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1420. if not isinstance(ams_root, dict):
  1421. ams_root = (data or {}).get("ams") or {}
  1422. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1423. if not isinstance(ams_units, list) or not ams_units:
  1424. return result
  1425. from backend.app.services.print_scheduler import _global_tray_id
  1426. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1427. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1428. loaded: dict[int, tuple[str, str]] = {}
  1429. for unit in ams_units:
  1430. if not isinstance(unit, dict):
  1431. continue
  1432. try:
  1433. unit_id = int(unit.get("id", 0))
  1434. except (TypeError, ValueError):
  1435. continue
  1436. for tray in unit.get("tray") or []:
  1437. if not isinstance(tray, dict):
  1438. continue
  1439. try:
  1440. tray_id = int(tray.get("id", 0))
  1441. except (TypeError, ValueError):
  1442. continue
  1443. ttype = (tray.get("tray_type") or "").strip()
  1444. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1445. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1446. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1447. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1448. if not ttype:
  1449. continue # Empty / unloaded slot.
  1450. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1451. if not loaded:
  1452. return result
  1453. if ams_mapping:
  1454. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1455. filaments = [loaded[g] for g in used_ids if g in loaded]
  1456. if not filaments:
  1457. return result # Mapping points entirely at slots we have no data for.
  1458. else:
  1459. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1460. types_joined = ",".join(f[0] for f in filaments)
  1461. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1462. # Column limits per backend/app/models/archive.py: filament_type=50,
  1463. # filament_color=200.
  1464. if types_joined:
  1465. result["filament_type"] = types_joined[:50]
  1466. if colors_joined:
  1467. result["filament_color"] = colors_joined[:200]
  1468. return result
  1469. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1470. """Start a layer-timelapse session for *archive_id* when the printer has
  1471. an external camera configured. Returns True if a session was started.
  1472. Three call sites in on_print_start (expected-archive promotion, fallback
  1473. archive creation, fresh-archive creation) used to inline this same
  1474. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1475. on the first pass). Centralising the conditional + call here makes the
  1476. contract testable in isolation and keeps the three sites locked in step.
  1477. """
  1478. if not (printer.external_camera_enabled and printer.external_camera_url):
  1479. return False
  1480. from backend.app.services.layer_timelapse import start_session
  1481. start_session(
  1482. printer_id,
  1483. archive_id,
  1484. printer.external_camera_url,
  1485. printer.external_camera_type or "mjpeg",
  1486. snapshot_url=printer.external_camera_snapshot_url,
  1487. rotation=getattr(printer, "camera_rotation", 0),
  1488. )
  1489. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1490. return True
  1491. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1492. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1493. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1494. — since #2926 — the description the parser already resolved, which is preferred
  1495. when present so the queue's failure reason reads the same as the status
  1496. response. The short code still produces the bracketed label, and still
  1497. resolves the sentence for a caller whose entries predate the field. An entry
  1498. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1499. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1500. label when no description is on file. Returns None for an empty list so
  1501. callers can leave error_message unset.
  1502. """
  1503. if not hms_errors:
  1504. return None
  1505. from backend.app.services.hms_errors import get_error_description
  1506. parts: list[str] = []
  1507. for err in hms_errors:
  1508. try:
  1509. # `_hms_short_code` rather than a local derivation: this one used to
  1510. # format the error without masking it to 16 bits, so an `hms[]` entry
  1511. # whose code carries an alert-level group produced a five-digit label
  1512. # like "0500_3000A" — not a code the user can look up, and never a
  1513. # catalogue key, so the sentence was lost with it.
  1514. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1515. except (TypeError, ValueError):
  1516. continue
  1517. description = err.get("description") or get_error_description(short_code)
  1518. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1519. # groups and is not a code anyone can look up; its full code in the
  1520. # printer screen's four groups is (#2728).
  1521. full_code = str(err.get("full_code") or "")
  1522. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1523. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1524. return "; ".join(parts) if parts else None
  1525. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1526. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1527. print completes successfully. Gated to status=='completed': failed, cancelled
  1528. and aborted prints do not count as usage. Caller is responsible for committing
  1529. the session. No-op when the queue item has no linked library file (e.g. reprints
  1530. from an archive). See #1008."""
  1531. if queue_status != "completed" or item.library_file_id is None:
  1532. return
  1533. from backend.app.models.library import LibraryFile
  1534. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1535. if lib_file is None:
  1536. return
  1537. lib_file.print_count = (lib_file.print_count or 0) + 1
  1538. lib_file.last_printed_at = datetime.now(timezone.utc)
  1539. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1540. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1541. When on_print_complete fires with status 'failed' for a printer in this set we
  1542. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1543. rather than a 'print failed' notification.
  1544. """
  1545. _user_stopped_printers.add(printer_id)
  1546. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1547. _last_status_broadcast: dict[int, str] = {}
  1548. # Track printers where we've updated nozzle_count
  1549. _nozzle_count_updated: set[int] = set()
  1550. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1551. """Wait the debounce window then fire `on_printer_offline` if the printer
  1552. is still offline.
  1553. Scheduled by `on_printer_status_change` on the connected → disconnected
  1554. edge (#1752). Cancelled by the same handler if the printer reconnects
  1555. before the window elapses, so a single MQTT blip + recovery doesn't
  1556. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1557. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1558. route through the same status-change callback, so this covers both.
  1559. """
  1560. logger = logging.getLogger(__name__)
  1561. try:
  1562. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1563. still_offline = not printer_manager.is_connected(printer_id)
  1564. logger.info(
  1565. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1566. printer_id,
  1567. still_offline,
  1568. )
  1569. if not still_offline:
  1570. return
  1571. async with async_session() as db:
  1572. from backend.app.models.printer import Printer
  1573. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1574. printer = result.scalar_one_or_none()
  1575. if not printer:
  1576. logger.warning(
  1577. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1578. printer_id,
  1579. )
  1580. return
  1581. # Recorded only when the relay can publish it, so the reconnect's
  1582. # online event always has an offline before it.
  1583. if mqtt_relay.enabled and mqtt_relay.connected:
  1584. _printer_offline_published.add(printer_id)
  1585. try:
  1586. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1587. except Exception as e:
  1588. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1589. logger.info(
  1590. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1591. printer_id,
  1592. printer.name,
  1593. )
  1594. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1595. except asyncio.CancelledError:
  1596. raise
  1597. except Exception as e:
  1598. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1599. finally:
  1600. _printer_offline_notify_tasks.pop(printer_id, None)
  1601. def _hms_notify_key(error) -> str:
  1602. """What identifies a fault for notification de-duplication.
  1603. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1604. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1605. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1606. and -0006 together) shared a key and only the first was ever notified. An
  1607. entry without a full code falls back to attr and code together.
  1608. """
  1609. full_code = getattr(error, "full_code", "") or ""
  1610. if full_code:
  1611. return full_code.upper()
  1612. return f"{error.attr:08X}:{error.code}"
  1613. def _hms_fault_counts(error) -> bool:
  1614. """Whether a fault counts as a problem: the same rule the frontend's
  1615. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1616. It counts when Bambu publishes text for it or it offers action buttons, and
  1617. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1618. no actions does not count: those are things like "the top cover is open" or
  1619. "the chamber is hot, fan speed increased", which a printer can hold through
  1620. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1621. it always has; those are prompts such as "unable to start drying" (#2728).
  1622. """
  1623. if error.severity < 1:
  1624. return False
  1625. has_actions = bool(getattr(error, "actions", None))
  1626. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1627. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1628. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1629. """The new faults that count (see ``_hms_fault_counts``).
  1630. These go to the MQTT relay; the caller also needs a description before it
  1631. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1632. used to read ``severity >= 2`` when severity held the part byte; on the real
  1633. level that would drop the task-stopping errors (#2728).
  1634. """
  1635. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1636. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1637. """The faults on this printer not notified yet, and record them as notified.
  1638. Tracking is updated before anything is sent, so concurrent status callbacks
  1639. cannot notify the same fault twice. A notified fault is forgotten once it
  1640. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1641. and on is notified once (#3226), while one that clears and comes back much
  1642. later is notified again.
  1643. When ``print_state`` changes (a print resumed, started or finished), every
  1644. fault recorded so far is forgotten the first time it is gone, without the
  1645. wait: a runout fixed before resuming must be notified if it happens again a
  1646. few minutes later, while the printer sits paused. Not only the faults gone
  1647. at the change itself, because the update that flips the state can still
  1648. carry the old fault (a ``print_error`` entry stays until a payload brings
  1649. ``hms``).
  1650. """
  1651. now = time.time()
  1652. current = {_hms_notify_key(e) for e in errors}
  1653. seen = _notified_hms_errors.setdefault(printer_id, {})
  1654. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1655. if print_state is not None:
  1656. print_state = print_state.upper()
  1657. if _hms_print_state.get(printer_id, print_state) != print_state:
  1658. forget_when_gone.update(seen)
  1659. _hms_print_state[printer_id] = print_state
  1660. for key, last_seen in list(seen.items()):
  1661. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1662. del seen[key]
  1663. forget_when_gone.discard(key)
  1664. new = current - seen.keys()
  1665. for key in current:
  1666. seen[key] = now
  1667. if not seen:
  1668. _notified_hms_errors.pop(printer_id, None)
  1669. if not forget_when_gone:
  1670. _hms_forget_when_gone.pop(printer_id, None)
  1671. return _hms_errors_to_notify(errors, new)
  1672. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1673. # "Printing", -1 and 255 are "no stage" (#3211).
  1674. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1675. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1676. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1677. Records it as notified. Called only for a printing state with progress above 0.
  1678. Progress before the first layer is not progress through the print (#3211).
  1679. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1680. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1681. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1682. 75% notification together with Print Started, and since 75 was then on
  1683. record, 25 and 50 could never fire. So nothing counts while the printer
  1684. reports a layer count but has not started layer 1.
  1685. Without a layer count -- a print whose first frame carried no
  1686. ``total_layer_num``, until the pushall that asks for it is answered
  1687. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1688. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1689. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1690. reports neither keeps the old behaviour rather than never notifying.
  1691. """
  1692. if (state.layer_num or 0) < 1:
  1693. if (state.total_layers or 0) > 0:
  1694. return None
  1695. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1696. return None
  1697. progress = state.progress or 0
  1698. current_milestone = 0
  1699. if progress >= 75:
  1700. current_milestone = 75
  1701. elif progress >= 50:
  1702. current_milestone = 50
  1703. elif progress >= 25:
  1704. current_milestone = 25
  1705. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1706. _last_progress_milestone[printer_id] = current_milestone
  1707. return current_milestone
  1708. return None
  1709. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1710. """Handle printer status changes - broadcast via WebSocket."""
  1711. try:
  1712. notify_live_activities.observe(printer_id, state)
  1713. except Exception:
  1714. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1715. try:
  1716. pause_eta.observe(printer_id, state)
  1717. except Exception:
  1718. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1719. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1720. # transitions disconnected → connected — which covers both Bambuddy
  1721. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1722. # `reconcile_stale_active_prints` exactly once for this connection so
  1723. # any archive still in `status="printing"` that can't actually be
  1724. # running anymore (printer IDLE / different subtask / empty subtask)
  1725. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1726. # finished during a disconnect window + a smart-plug power cycle
  1727. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1728. # next boot. Reconciliation runs concurrently — it must not block the
  1729. # WebSocket dedup / broadcast logic below, and the connected edge is
  1730. # marked True BEFORE the await so concurrent status updates inside
  1731. # the same connection don't re-trigger reconciliation.
  1732. #
  1733. # Wait for a real push_status before reconciling (#1679): MQTT
  1734. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1735. # the connection, BEFORE `_request_push_all` round-trips. At that
  1736. # instant the `PrinterState` is still on construction defaults — most
  1737. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1738. # If reconcile spawns here, every in-flight archive falls through to
  1739. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1740. # creates a duplicate archive on the real PRINT COMPLETE and
  1741. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1742. # keeps the #1542 mechanism intact: once the first real push_status
  1743. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1744. # fires again with the flag still False — reconcile then runs against
  1745. # actual evidence.
  1746. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1747. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1748. _printer_reconciled_since_connect[printer_id] = True
  1749. spawn_background_task(
  1750. reconcile_stale_active_prints(printer_id),
  1751. name=f"reconcile-stale-prints-{printer_id}",
  1752. )
  1753. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1754. # Re-arm so the next reconnect triggers reconciliation again.
  1755. _printer_reconciled_since_connect[printer_id] = False
  1756. # Same edge, for the calibration table the AMS card reads its K values from.
  1757. #
  1758. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1759. # tables to ask for. A `state_known` gate alone is not enough: the first
  1760. # real push_status is what makes the state known, and the nozzle fields do
  1761. # not always arrive in it. Latching there would spend this connection's one
  1762. # attempt on a printer that could not yet say what was fitted.
  1763. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1764. if (
  1765. state.connected
  1766. and state_known
  1767. and nozzle_known
  1768. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1769. ):
  1770. _printer_kprofiles_primed_since_connect[printer_id] = True
  1771. spawn_background_task(
  1772. prime_kprofile_table(printer_id),
  1773. name=f"prime-kprofiles-{printer_id}",
  1774. )
  1775. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1776. _printer_kprofiles_primed_since_connect[printer_id] = False
  1777. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1778. # else in the AMS report changing -- a power cycle does it to every slot --
  1779. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1780. # while the printer is idle; needs_check is cheap and throttled per slot.
  1781. # Guarded: nothing here may stop the status broadcast below.
  1782. try:
  1783. if not state.connected:
  1784. kprofile_drift.forget_printer(printer_id)
  1785. elif kprofile_drift.needs_check(printer_id, state):
  1786. spawn_background_task(
  1787. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1788. name=f"reapply-kprofiles-{printer_id}",
  1789. )
  1790. except Exception:
  1791. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1792. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1793. # connected → disconnected. The "back online" channel is already covered
  1794. # by the print-failure notification (firmware reports gcode_state=FAILED
  1795. # on reconnect of an interrupted print), so there is no online
  1796. # notification. The MQTT relay gets both: offline after the debounce, and
  1797. # online on the reconnect that follows a published offline.
  1798. prev_connected = _printer_last_connected.get(printer_id)
  1799. _printer_last_connected[printer_id] = state.connected
  1800. if prev_connected is True and not state.connected:
  1801. existing = _printer_offline_notify_tasks.get(printer_id)
  1802. if existing is None or existing.done():
  1803. logging.getLogger(__name__).info(
  1804. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1805. printer_id,
  1806. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1807. )
  1808. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1809. _maybe_notify_printer_offline(printer_id),
  1810. name=f"printer-offline-notify-{printer_id}",
  1811. )
  1812. elif state.connected:
  1813. # Kept until the relay can actually send online: with its broker down
  1814. # now, the next status update after the reconnect sends it.
  1815. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1816. _printer_offline_published.discard(printer_id)
  1817. printer_info = printer_manager.get_printer(printer_id)
  1818. if printer_info:
  1819. try:
  1820. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1821. except Exception as e:
  1822. logging.getLogger(__name__).warning(
  1823. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1824. )
  1825. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1826. if pending is not None and not pending.done():
  1827. logging.getLogger(__name__).info(
  1828. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1829. printer_id,
  1830. )
  1831. pending.cancel()
  1832. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1833. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1834. temps = state.temperatures or {}
  1835. nozzle_temp = round(temps.get("nozzle", 0))
  1836. bed_temp = round(temps.get("bed", 0))
  1837. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1838. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1839. # Auto-detect dual-nozzle printers from MQTT temperature data
  1840. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1841. _nozzle_count_updated.add(printer_id)
  1842. # Update nozzle_count in database
  1843. async with async_session() as db:
  1844. from backend.app.models.printer import Printer
  1845. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1846. printer = result.scalar_one_or_none()
  1847. if printer and printer.nozzle_count != 2:
  1848. printer.nozzle_count = 2
  1849. await db.commit()
  1850. logging.getLogger(__name__).info(
  1851. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1852. )
  1853. # Include target temps for heating phase detection
  1854. bed_target = round(temps.get("bed_target", 0))
  1855. nozzle_target = round(temps.get("nozzle_target", 0))
  1856. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1857. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1858. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1859. #
  1860. # dry_countdown_stalled rides along because it is the one drying signal the
  1861. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1862. # dry_time stopped moving, so on the frame that flips it every other member
  1863. # of this key is identical and the push would be deduplicated away. Mid-print
  1864. # a temperature would eventually break the tie, but a parked command on an
  1865. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1866. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1867. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1868. ams_dry_key = (
  1869. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1870. if state.raw_data
  1871. else ()
  1872. )
  1873. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1874. #
  1875. # The filament identity fields are here because Configure Slot writes
  1876. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1877. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1878. # matched, this function returned before broadcasting, and the card kept
  1879. # showing the old filament until the 30s fallback poll or a page reload —
  1880. # even though the configure route asks the printer for a fresh pushall and
  1881. # that push does carry the new values. Reset always worked, because it
  1882. # clears tray_type.
  1883. #
  1884. # These fields only change when someone configures a slot or swaps a spool,
  1885. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1886. ams_tray_key = (
  1887. tuple(
  1888. (
  1889. t.get("id"),
  1890. t.get("tray_type", ""),
  1891. t.get("state"),
  1892. t.get("tray_color", ""),
  1893. t.get("tray_info_idx", ""),
  1894. t.get("tray_sub_brands", ""),
  1895. t.get("cali_idx"),
  1896. )
  1897. for a in (state.raw_data.get("ams") or [])
  1898. for t in a.get("tray", [])
  1899. )
  1900. if state.raw_data
  1901. else ()
  1902. )
  1903. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1904. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1905. # in the AMS change-hash (tray fields only, and widening that would fire
  1906. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1907. # screen changed no key at all and the card's inlet badges sat stale until a
  1908. # reload. Like the filament-backup flag, these only move when someone
  1909. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1910. fts_key = (
  1911. state.fila_switch.installed if state.fila_switch else False,
  1912. tuple(sorted(state.ams_switch_inlet.items())),
  1913. # Which hotend holds which slot. Unlike the two above this does move
  1914. # mid-print, on every filament change — but only between discrete slots,
  1915. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1916. # it live: it decides which hotend the Load dialog may offer and whether
  1917. # Unload has anything to act on.
  1918. tuple(
  1919. sorted(
  1920. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1921. # Sort on the extruder id alone: the other members are nullable
  1922. # and comparing None with an int raises.
  1923. key=lambda entry: entry[0],
  1924. )
  1925. ),
  1926. )
  1927. status_key = (
  1928. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1929. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1930. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1931. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1932. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1933. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1934. )
  1935. # Fields that change only when the machine does (a nozzle swap, a firmware
  1936. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1937. # but on an idle printer nothing else moves the key when they change.
  1938. machine_key = (
  1939. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1940. state.firmware_version,
  1941. state.developer_mode,
  1942. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1943. # Cooling/heating, switched on the printer's screen too: on an idle
  1944. # printer nothing else moves the key (PSF-4).
  1945. state.airduct_mode,
  1946. )
  1947. status_key = f"{status_key}:{machine_key}"
  1948. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1949. if not is_active_print:
  1950. _unauthorized_print_kill_sent.discard(printer_id)
  1951. elif printer_id in _unauthorized_print_kill_sent:
  1952. # stop_print() was already sent for this print; avoid all further
  1953. # ownership and settings work until the printer leaves an active state.
  1954. pass
  1955. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1956. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1957. _unauthorized_print_kill_sent.discard(printer_id)
  1958. else:
  1959. kill_switch_enabled = False
  1960. authorization: bool | None = None
  1961. status_logger = logging.getLogger(__name__)
  1962. try:
  1963. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1964. if kill_switch_enabled:
  1965. async with async_session() as db:
  1966. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1967. except Exception as e:
  1968. # Fail safe: a database/reconciliation error must never turn into an
  1969. # irreversible stop of a print whose ownership is still unknown.
  1970. authorization = None
  1971. status_logger.warning(
  1972. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1973. )
  1974. if not kill_switch_enabled or authorization is True:
  1975. _unauthorized_print_kill_sent.discard(printer_id)
  1976. elif authorization is None:
  1977. _unauthorized_print_kill_sent.discard(printer_id)
  1978. status_logger.debug(
  1979. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1980. printer_id,
  1981. )
  1982. else:
  1983. try:
  1984. stopped = printer_manager.stop_print(printer_id)
  1985. if stopped:
  1986. _unauthorized_print_kill_sent.add(printer_id)
  1987. _kill_switch_stopped.add(printer_id)
  1988. printer_info = printer_manager.get_printer(printer_id)
  1989. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1990. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1991. notification_data = {
  1992. "status": "stopped",
  1993. "filename": state.gcode_file or state.current_print or "",
  1994. "subtask_name": state.subtask_name or "",
  1995. "progress": state.progress,
  1996. "reason": "unauthorized_print",
  1997. }
  1998. status_logger.warning(
  1999. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2000. printer_id,
  2001. state.state,
  2002. )
  2003. try:
  2004. await ws_manager.broadcast(
  2005. {
  2006. "type": "kill_switch_triggered",
  2007. "printer_id": printer_id,
  2008. "printer_name": printer_name,
  2009. "filename": filename,
  2010. "reason": "unauthorized_print",
  2011. }
  2012. )
  2013. except Exception as e:
  2014. status_logger.warning(
  2015. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2016. )
  2017. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2018. if previous_task is not None and not previous_task.done():
  2019. previous_task.cancel()
  2020. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2021. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2022. name=f"kill-switch-notification-{printer_id}",
  2023. )
  2024. else:
  2025. status_logger.warning(
  2026. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2027. printer_id,
  2028. state.state,
  2029. )
  2030. except Exception as e:
  2031. status_logger.warning(
  2032. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2033. )
  2034. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2035. try:
  2036. printer_info = printer_manager.get_printer(printer_id)
  2037. if printer_info:
  2038. await mqtt_relay.on_printer_status(
  2039. printer_id,
  2040. state,
  2041. printer_info.name,
  2042. printer_info.serial_number,
  2043. printer_manager.is_awaiting_plate_clear(printer_id),
  2044. )
  2045. except Exception:
  2046. pass # Don't fail status callback if MQTT fails
  2047. if _last_status_broadcast.get(printer_id) == status_key:
  2048. return # No change, skip WebSocket broadcast
  2049. _last_status_broadcast[printer_id] = status_key
  2050. # Check for progress milestone notifications (25%, 50%, 75%)
  2051. progress = state.progress or 0
  2052. is_printing = state.state in ("RUNNING", "PRINTING")
  2053. if is_printing and progress > 0:
  2054. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2055. if current_milestone is not None:
  2056. try:
  2057. from backend.app.models.printer import Printer
  2058. # Read the printer in a short session and release the connection
  2059. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2060. # pinned a pooled connection per milestone, per printer (issue #2572).
  2061. async with async_session() as db:
  2062. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2063. printer = result.scalar_one_or_none()
  2064. printer_name = printer.name if printer else f"Printer {printer_id}"
  2065. filename = state.subtask_name or state.gcode_file or "Unknown"
  2066. # remaining_time is in minutes, convert to seconds for notification
  2067. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2068. # Capture camera snapshot for notification image attachment (no DB held).
  2069. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2070. # Notification send needs a session (provider/template lookups).
  2071. async with async_session() as db:
  2072. await notification_service.on_print_progress(
  2073. printer_id,
  2074. printer_name,
  2075. filename,
  2076. current_milestone,
  2077. db,
  2078. remaining_time_seconds,
  2079. image_data=image_data,
  2080. )
  2081. except Exception as e:
  2082. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2083. elif progress < 5:
  2084. # Reset milestone tracking when print restarts or new print begins
  2085. _last_progress_milestone[printer_id] = 0
  2086. _first_layer_notified[printer_id] = False
  2087. # HMS error codes that should not trigger notifications even though they
  2088. # have known descriptions (e.g. user-initiated actions, not real errors).
  2089. _HMS_NOTIFICATION_SUPPRESS = {
  2090. "0500_400E", # Printing was cancelled (user action, not an error)
  2091. }
  2092. # Check for new HMS errors and send notifications
  2093. current_hms_errors = getattr(state, "hms_errors", []) or []
  2094. if current_hms_errors:
  2095. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2096. if new_errors:
  2097. try:
  2098. from backend.app.models.printer import Printer
  2099. # Read the printer in a short session and release the connection
  2100. # BEFORE the ~15s camera snapshot below (issue #2572).
  2101. async with async_session() as db:
  2102. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2103. printer = result.scalar_one_or_none()
  2104. printer_name = printer.name if printer else f"Printer {printer_id}"
  2105. # Format error details for notification
  2106. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2107. module_names = {
  2108. 0x03: "Print/Task",
  2109. 0x05: "Nozzle/Extruder",
  2110. 0x07: "AMS/Filament",
  2111. 0x0C: "Motion Controller",
  2112. 0x12: "Chamber",
  2113. }
  2114. # Capture camera snapshot once for all error notifications (no DB held).
  2115. error_image_data = await _capture_snapshot_for_notification(
  2116. printer_id, printer, logging.getLogger(__name__)
  2117. )
  2118. # Notification sends need a session (provider/template lookups).
  2119. async with async_session() as db:
  2120. sent_count = 0
  2121. for error in new_errors:
  2122. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2123. # Build short code like "0700_8010"
  2124. # Mask to 16 bits to handle printers that send larger values
  2125. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2126. error_code_masked = error_code_int & 0xFFFF
  2127. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2128. # Only notify for errors Bambu publishes text for — printers
  2129. # send undocumented codes that aren't real errors, and Bambu
  2130. # lists some with empty text. Resolved at parse time (#2926);
  2131. # short_code is still needed for the suppression set below.
  2132. description = error.description
  2133. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2134. continue
  2135. error_type = f"{module_name} Error"
  2136. error_detail = description
  2137. await notification_service.on_printer_error(
  2138. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2139. )
  2140. sent_count += 1
  2141. if sent_count:
  2142. logging.getLogger(__name__).info(
  2143. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2144. )
  2145. # Also publish to MQTT relay (no DB): every new fault that
  2146. # counts, with or without text, the same set the UI counts.
  2147. printer_info = printer_manager.get_printer(printer_id)
  2148. if printer_info:
  2149. errors_data = [
  2150. {
  2151. "code": e.code,
  2152. "attr": e.attr,
  2153. "module": e.module,
  2154. "severity": e.severity,
  2155. }
  2156. for e in new_errors
  2157. ]
  2158. await mqtt_relay.on_printer_error(
  2159. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2160. )
  2161. except Exception as e:
  2162. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2163. else:
  2164. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2165. # across a print state change) are forgotten. Some codes, e.g. chamber
  2166. # temperature regulation during PETG prints, toggle every few seconds.
  2167. _take_new_hms_faults(printer_id, [], state.state)
  2168. await ws_manager.send_printer_status(
  2169. printer_id,
  2170. printer_state_to_dict(
  2171. state,
  2172. printer_id,
  2173. printer_manager.get_model(printer_id),
  2174. printer_manager.get_drying_targets(printer_id),
  2175. ),
  2176. )
  2177. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2178. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2179. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2180. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2181. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2182. K-profiles are per-nozzle and the printer's calibration table is numbered
  2183. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2184. switch's other inlet therefore silently invalidates every configured slot in
  2185. it: the index stays put and now resolves against the other nozzle's table.
  2186. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2187. and 0.020 on the right kept the left profile after the move, and a manual
  2188. RFID re-read only re-asserted the same wrong one.
  2189. Configuring a slot is a deliberate preparation step, so this re-selects
  2190. rather than re-configures: only the calibration binding moves, and only for
  2191. slots whose spool already has a stored profile for the new nozzle. A slot
  2192. Bambuddy knows nothing about is left exactly as the operator left it.
  2193. """
  2194. logger = logging.getLogger(__name__)
  2195. target_extruder = extruder_for_inlet(inlet)
  2196. if target_extruder is None:
  2197. return
  2198. client = printer_manager.get_client(printer_id)
  2199. state = printer_manager.get_status(printer_id)
  2200. if not client or not state or not state.raw_data:
  2201. return
  2202. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2203. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2204. # the nozzle width, which changes both the K profile to select and the
  2205. # preset the slot should carry.
  2206. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2207. ams_raw = state.raw_data.get("ams")
  2208. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2209. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2210. if not unit:
  2211. return
  2212. try:
  2213. async with async_session() as db:
  2214. for tray in unit.get("tray", []):
  2215. tray_id = int(tray.get("id", -1))
  2216. if tray_id < 0 or not tray.get("tray_type"):
  2217. continue
  2218. current_idx = tray.get("cali_idx")
  2219. profile = await find_slot_kprofile_for_extruder(
  2220. db,
  2221. printer_id,
  2222. ams_id,
  2223. tray_id,
  2224. target_extruder,
  2225. nozzle_diameter,
  2226. printer_manager.get_model(printer_id),
  2227. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2228. )
  2229. if profile is None or profile.cali_idx is None:
  2230. continue
  2231. if current_idx == profile.cali_idx:
  2232. continue # Already on the right one.
  2233. logger.info(
  2234. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2235. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2236. printer_id,
  2237. ams_id,
  2238. tray_id,
  2239. inlet,
  2240. target_extruder,
  2241. profile.name,
  2242. current_idx,
  2243. profile.cali_idx,
  2244. profile.k_value,
  2245. )
  2246. client.extrusion_cali_sel(
  2247. ams_id=ams_id,
  2248. tray_id=tray_id,
  2249. cali_idx=profile.cali_idx,
  2250. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2251. nozzle_diameter=nozzle_diameter,
  2252. )
  2253. except Exception as e:
  2254. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2255. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2256. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2257. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2258. from the delayed re-check -- which is why it takes the AMS data and print
  2259. state as arguments instead of reading them from the push (#3186).
  2260. """
  2261. logger = logging.getLogger(__name__)
  2262. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2263. # Auto-unlink spool assignments with stale fingerprints. Under the
  2264. # per-printer assignment lock since #3186: the held-removal re-check runs
  2265. # this outside any MQTT push, so it can now overlap one.
  2266. try:
  2267. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2268. from sqlalchemy.orm import selectinload
  2269. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2270. from backend.app.models.spool import Spool as _Spool
  2271. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2272. from backend.app.services.ams_slot_presence import spool_present
  2273. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2274. # Built-in assignments only. Since #2812 they survive a switch to
  2275. # Spoolman mode rather than being deleted by it, and this pass ends
  2276. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2277. # time as the AMS contents changed under the other mode, undoing the
  2278. # preservation more slowly but just as completely.
  2279. assignments = []
  2280. if not await spoolman_owns_assignments(db):
  2281. result = await db.execute(
  2282. select(SA)
  2283. .where(SA.printer_id == printer_id)
  2284. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2285. )
  2286. assignments = result.scalars().all()
  2287. # ``printing_now`` (top of this function) keeps a runout from
  2288. # unlinking the spool that fed the print — the next idle-time pass
  2289. # unlinks it if the user really did take it out.
  2290. stale = []
  2291. # Removals this pass is holding rather than unlinking (#3186).
  2292. held: set[tuple] = set()
  2293. for assignment in assignments:
  2294. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2295. if assignment.ams_id == 255:
  2296. ps = printer_manager.get_status(printer_id)
  2297. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2298. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2299. current_tray = None
  2300. for vt in vt_tray_raw:
  2301. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2302. current_tray = vt
  2303. break
  2304. if not current_tray:
  2305. # vt_tray data may not have arrived yet — keep assignment
  2306. continue
  2307. else:
  2308. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2309. if not current_tray:
  2310. if printing_now:
  2311. logger.info(
  2312. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2313. assignment.spool_id,
  2314. assignment.ams_id,
  2315. assignment.tray_id,
  2316. )
  2317. continue
  2318. # A whole AMS unit can drop out of one push and come back in
  2319. # the next; only a slot that stays gone is a removal (#3186).
  2320. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2321. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2322. held.add(hold_key)
  2323. logger.info(
  2324. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2325. "unlinking if it is still gone in %ds",
  2326. assignment.spool_id,
  2327. assignment.ams_id,
  2328. assignment.tray_id,
  2329. int(slot_unlink_grace.GRACE_SECONDS),
  2330. )
  2331. continue
  2332. logger.info(
  2333. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2334. assignment.spool_id,
  2335. assignment.ams_id,
  2336. assignment.tray_id,
  2337. )
  2338. stale.append(assignment) # Slot empty
  2339. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2340. # A Bambu Lab spool is in this slot — check if it's the same spool
  2341. # that's currently assigned. If yes, keep the assignment (avoids
  2342. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2343. # the printer's filament preset on every startup).
  2344. tray_uuid = current_tray.get("tray_uuid", "")
  2345. tag_uid = current_tray.get("tag_uid", "")
  2346. spool = assignment.spool
  2347. spool_matches = False
  2348. if spool:
  2349. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2350. spool.tag_uid
  2351. and tag_uid
  2352. and tag_uid != "0000000000000000"
  2353. and spool.tag_uid.upper() == tag_uid.upper()
  2354. ):
  2355. spool_matches = True
  2356. if spool_matches:
  2357. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2358. cur_color = current_tray.get("tray_color", "")
  2359. cur_type = current_tray.get("tray_type", "")
  2360. fp_color = assignment.fingerprint_color or ""
  2361. fp_type = assignment.fingerprint_type or ""
  2362. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2363. assignment.fingerprint_color = cur_color
  2364. assignment.fingerprint_type = cur_type
  2365. logger.debug(
  2366. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2367. assignment.spool_id,
  2368. assignment.ams_id,
  2369. assignment.tray_id,
  2370. )
  2371. continue
  2372. # Different BL spool or unrecognized — unlink so auto-assign can match
  2373. logger.info(
  2374. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2375. assignment.spool_id,
  2376. assignment.ams_id,
  2377. assignment.tray_id,
  2378. tray_uuid,
  2379. )
  2380. stale.append(assignment)
  2381. else:
  2382. cur_color = current_tray.get("tray_color", "")
  2383. cur_type = current_tray.get("tray_type", "")
  2384. cur_state = current_tray.get("state")
  2385. fp_color = assignment.fingerprint_color or ""
  2386. fp_type = assignment.fingerprint_type or ""
  2387. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2388. # the slot was empty when the user pre-assigned via SpoolBuddy
  2389. # (the firmware drops ams_filament_setting on empty slots, so
  2390. # MQTT was deferred). The moment any filament gets inserted
  2391. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2392. # reconfigured spool — fire the deferred configuration.
  2393. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2394. # extruder" code) OR, on firmwares that don't use the state
  2395. # enum meaningfully, a non-empty tray_type when state is
  2396. # NOT one of the firmware's explicit empty signals (9, 10).
  2397. # state-only was wrong for firmwares that never set 11 — A1
  2398. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2399. # always report state=3 — so the replay never fired for them
  2400. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2401. # explicit "empty" signals authoritative over any stale
  2402. # tray_type that might survive the relay's auto-clearing.
  2403. #
  2404. # tray_exist_bits comes first because that guard cannot tell
  2405. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2406. # writes state=9 when the bit is 0 and leaves it there when the
  2407. # bit returns. A non-RFID spool inserted into a pre-assigned
  2408. # slot brings no tray_type with it, so the stale 9 made this
  2409. # expression false forever and the deferred config never fired
  2410. # — the deadlock #1322 removed from the assign path, still in
  2411. # place here (#3084, #3100).
  2412. loaded = spool_present(current_tray) is True or (
  2413. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2414. )
  2415. if not fp_type.strip() and loaded and assignment.spool:
  2416. # The fingerprint ends this replay. Not recorded when nothing
  2417. # could be sent (no MQTT client while the printer reconnects),
  2418. # so the next AMS change tries again. An attempt that raised is
  2419. # recorded as before: it may have sent part of the commands and
  2420. # would raise again on every change, remain% steps included.
  2421. configured: bool | None = False
  2422. try:
  2423. from backend.app.api.routes.inventory import (
  2424. apply_spool_to_slot_via_mqtt,
  2425. )
  2426. configured = await apply_spool_to_slot_via_mqtt(
  2427. db=db,
  2428. current_user=None,
  2429. spool=assignment.spool,
  2430. printer_id=printer_id,
  2431. ams_id=assignment.ams_id,
  2432. tray_id=assignment.tray_id,
  2433. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2434. current_tray_type=cur_type,
  2435. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2436. )
  2437. except Exception:
  2438. logger.exception(
  2439. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2440. assignment.spool_id,
  2441. printer_id,
  2442. assignment.ams_id,
  2443. assignment.tray_id,
  2444. )
  2445. configured = None
  2446. if configured is False:
  2447. logger.warning(
  2448. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2449. "retrying on the next AMS change",
  2450. assignment.spool_id,
  2451. printer_id,
  2452. assignment.ams_id,
  2453. assignment.tray_id,
  2454. )
  2455. else:
  2456. if configured:
  2457. logger.info(
  2458. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2459. assignment.spool_id,
  2460. printer_id,
  2461. assignment.ams_id,
  2462. assignment.tray_id,
  2463. )
  2464. assignment.fingerprint_color = cur_color
  2465. assignment.fingerprint_type = cur_type
  2466. continue
  2467. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2468. # Blank tray data mid-print is a runout, not a swap: the
  2469. # firmware clears colour and type when it unloads a spool
  2470. # it just emptied. Unlinking here would erase the record
  2471. # of which spool fed the print so far.
  2472. if printing_now and not cur_color.strip() and not cur_type.strip():
  2473. logger.info(
  2474. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2475. "(runout?)",
  2476. assignment.spool_id,
  2477. assignment.ams_id,
  2478. assignment.tray_id,
  2479. )
  2480. continue
  2481. # Same reasoning off the print, on firmware's own say-so:
  2482. # a blank tray report from a slot whose tray_exist_bits
  2483. # bit is set describes a spool the AMS cannot identify —
  2484. # a non-RFID one, or one whose slot was reset — not a
  2485. # spool that was taken out. Deleting the assignment there
  2486. # threw away the identity the user had supplied, which is
  2487. # the only place it existed (#3100). A slot the bit calls
  2488. # empty, or one that carries no bit at all, still unlinks.
  2489. #
  2490. # Unless the slot was reported empty first: a removal
  2491. # already held means a spool came out and another went
  2492. # in, so the blank report keeps the hold running below
  2493. # rather than cancelling it (#3186).
  2494. if (
  2495. spool_present(current_tray) is True
  2496. and not cur_color.strip()
  2497. and not cur_type.strip()
  2498. and not slot_unlink_grace.is_held(
  2499. printer_id,
  2500. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2501. )
  2502. ):
  2503. logger.info(
  2504. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2505. "tray reports no filament data yet",
  2506. assignment.spool_id,
  2507. assignment.ams_id,
  2508. assignment.tray_id,
  2509. )
  2510. continue
  2511. # A blank report the presence bit does not vouch for is
  2512. # still only one push. An idle X1C cleared a whole AMS
  2513. # unit's bits, colour and type for a moment and lost
  2514. # four saved assignments that way (#3186); unlink only
  2515. # if the slot is still blank after the grace period.
  2516. if not cur_color.strip() and not cur_type.strip():
  2517. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2518. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2519. held.add(hold_key)
  2520. logger.info(
  2521. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2522. "unlinking if it is still blank in %ds",
  2523. assignment.spool_id,
  2524. assignment.ams_id,
  2525. assignment.tray_id,
  2526. int(slot_unlink_grace.GRACE_SECONDS),
  2527. )
  2528. continue
  2529. # Fingerprint mismatch — but check if tray now matches the
  2530. # assigned spool (e.g. auto-configure changed the tray).
  2531. # Both sides are reduced to the type the slot can carry
  2532. # before comparing: the assign path writes that rather
  2533. # than the spool's raw material (#2902), so a spool whose
  2534. # material is a product line — "PLA+", "HTPLA" — reports
  2535. # back as "PLA" and would otherwise fail this check and
  2536. # be auto-unlinked from the slot it was just assigned to.
  2537. # Reducing the printer's side too keeps slots configured
  2538. # by an older Bambuddy, still reporting "PLA+", matching.
  2539. spool = assignment.spool
  2540. if spool:
  2541. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2542. # Two ways the assign path can have arrived at the
  2543. # slot's type, so both count as "we wrote this".
  2544. # The material column is one; the spool's preset is
  2545. # the other, and it outranks the material when the
  2546. # spool has one -- a spool whose material says PLA
  2547. # and whose preset is "Bambu PLA Aero" puts
  2548. # PLA-AERO in the slot (#2902). Read from the stored
  2549. # preset name rather than resolving the preset,
  2550. # because this runs on every AMS push and a cloud
  2551. # lookup here would be both slow and unavailable on
  2552. # the unauthenticated replay path.
  2553. spool_types = {printer_filament_type(spool.material).upper()}
  2554. if spool.slicer_filament_name:
  2555. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2556. # An imported local preset stores its type outright,
  2557. # which is what the assign path used -- and the name
  2558. # above may be unset. One keyed read, and only on a
  2559. # mismatch, which is rare.
  2560. #
  2561. # slicer_filament is free text up to fifty characters,
  2562. # so the digits have to be checked against the range
  2563. # of the integer primary key they are about to be
  2564. # compared with. Postgres raises on an out-of-range
  2565. # integer rather than simply not matching, and that
  2566. # would poison this session and abandon the rest of
  2567. # the cleanup pass.
  2568. lp_ref = (spool.slicer_filament or "").strip()
  2569. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2570. from backend.app.models.local_preset import LocalPreset as _LP
  2571. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2572. if lp_type:
  2573. spool_types.add(printer_filament_type(lp_type).upper())
  2574. if (
  2575. _colors_similar(cur_color, spool_color)
  2576. and printer_filament_type(cur_type).upper() in spool_types
  2577. ):
  2578. logger.info(
  2579. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2580. assignment.spool_id,
  2581. assignment.ams_id,
  2582. assignment.tray_id,
  2583. )
  2584. assignment.fingerprint_color = cur_color
  2585. assignment.fingerprint_type = cur_type
  2586. continue
  2587. logger.info(
  2588. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2589. assignment.spool_id,
  2590. assignment.ams_id,
  2591. assignment.tray_id,
  2592. cur_color,
  2593. cur_type,
  2594. fp_color,
  2595. fp_type,
  2596. spool.rgba if spool else "?",
  2597. spool.material if spool else "?",
  2598. )
  2599. stale.append(assignment) # Spool changed
  2600. slot_unlink_grace.settle(printer_id, "inventory", held)
  2601. # Snapshot slots before delete — ORM attribute access after the
  2602. # commit would refresh against a deleted row.
  2603. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2604. for a in stale:
  2605. await db.delete(a)
  2606. if stale:
  2607. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2608. # Commit any changes (stale deletions and/or fingerprint updates)
  2609. await db.commit()
  2610. # Tell open browsers the assignment is gone (#2575). Only the manual
  2611. # REST assign/unassign endpoints broadcast this event; without it the
  2612. # frontend's spool-assignments cache keeps rendering the unlinked
  2613. # spool on the slot until an unrelated refetch — which reads exactly
  2614. # like "the fix didn't work" (reporter verified: a browser refresh
  2615. # after the swap showed the correct state all along).
  2616. for ams_id, tray_id in unlinked_slots:
  2617. await ws_manager.broadcast(
  2618. {
  2619. "type": "spool_assignment_changed",
  2620. "printer_id": printer_id,
  2621. "ams_id": ams_id,
  2622. "tray_id": tray_id,
  2623. }
  2624. )
  2625. except Exception as e:
  2626. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2627. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2628. """Delete Spoolman slot rows whose held removal has run its grace period.
  2629. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2630. talks to Spoolman for every tray; this only needs the local rows, so it
  2631. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2632. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2633. not in a slot the presence bit calls occupied -- and nothing else.
  2634. """
  2635. logger = logging.getLogger(__name__)
  2636. try:
  2637. async with async_session() as db:
  2638. from backend.app.api.routes.settings import get_setting
  2639. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2640. from backend.app.services.ams_slot_presence import spool_present
  2641. enabled = await get_setting(db, "spoolman_enabled")
  2642. if not enabled or enabled.lower() != "true":
  2643. return
  2644. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2645. if sync_mode and sync_mode != "auto":
  2646. return
  2647. trays: dict[tuple[int, int], dict] = {}
  2648. for ams_unit in ams_data or []:
  2649. if not isinstance(ams_unit, dict):
  2650. continue
  2651. for tray in ams_unit.get("tray", []):
  2652. if isinstance(tray, dict):
  2653. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2654. rows = (
  2655. (
  2656. await db.execute(
  2657. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2658. )
  2659. )
  2660. .scalars()
  2661. .all()
  2662. )
  2663. held: set[tuple] = set()
  2664. expired: list[tuple[int, int]] = []
  2665. for row in rows:
  2666. tray = trays.get((row.ams_id, row.tray_id))
  2667. if tray is None or printing_now:
  2668. continue
  2669. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2670. continue
  2671. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2672. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2673. continue
  2674. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2675. expired.append((row.ams_id, row.tray_id))
  2676. else:
  2677. held.add(hold_key)
  2678. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2679. if not expired:
  2680. return
  2681. # A statement rather than ORM deletes, like the sync pass: the two
  2682. # can overlap, and a row the other already removed must not fail
  2683. # this commit.
  2684. for ams_id, tray_id in expired:
  2685. await db.execute(
  2686. delete(SpoolmanSlotAssignment).where(
  2687. SpoolmanSlotAssignment.printer_id == printer_id,
  2688. SpoolmanSlotAssignment.ams_id == ams_id,
  2689. SpoolmanSlotAssignment.tray_id == tray_id,
  2690. )
  2691. )
  2692. await db.commit()
  2693. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2694. for ams_id, tray_id in expired:
  2695. await ws_manager.broadcast(
  2696. {
  2697. "type": "spool_assignment_changed",
  2698. "printer_id": printer_id,
  2699. "ams_id": ams_id,
  2700. "tray_id": tray_id,
  2701. }
  2702. )
  2703. except Exception as e:
  2704. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2705. async def _recheck_held_unlinks(printer_id: int) -> None:
  2706. """Re-run just the slot cleanup against the printer's current AMS state.
  2707. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2708. passes otherwise run only when the AMS hash changes, and a slot that went
  2709. empty and stayed empty may never change it again.
  2710. """
  2711. status = printer_manager.get_status(printer_id)
  2712. # A disconnected printer's state is its last report, not a new one: acting
  2713. # on it would "confirm" a removal nobody has seen for the whole grace
  2714. # period. Leave the holds; the first push after reconnecting decides.
  2715. if status is None or not status.connected:
  2716. return
  2717. ams_raw = status.raw_data.get("ams")
  2718. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2719. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2720. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2721. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2722. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2723. async def on_ams_change(printer_id: int, ams_data: list):
  2724. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2725. logger = logging.getLogger(__name__)
  2726. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2727. # still being charged, skip weight sync later. on_print_complete may pop
  2728. # _active_sessions during our awaits (#880).
  2729. from backend.app.services.usage_tracker import printer_is_charging
  2730. _print_active = printer_is_charging(printer_id)
  2731. # A slot that reports empty while a print is running is a filament runout,
  2732. # not a spool swap: the spool is still physically in the AMS, just
  2733. # consumed. Dropping either inventory backend's slot link there loses the
  2734. # only record of which spool fed the print, so the completion path can't
  2735. # charge the runout segment to anything. Both cleanup passes below consult
  2736. # this; computed once, up front, so neither depends on the other having run.
  2737. _unlink_state = printer_manager.get_status(printer_id)
  2738. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2739. # The session alone is not enough: a restart that finds a stale persisted
  2740. # session registers none for the print that is running.
  2741. _print_active = _print_active or printing_now
  2742. # MQTT relay - publish AMS change
  2743. try:
  2744. printer_info = printer_manager.get_printer(printer_id)
  2745. if printer_info:
  2746. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2747. except Exception:
  2748. pass # Don't fail AMS callback if MQTT fails
  2749. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2750. # This ensures frontend gets immediate updates when AMS slots are configured
  2751. try:
  2752. state = printer_manager.get_status(printer_id)
  2753. if state:
  2754. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2755. await ws_manager.send_printer_status(
  2756. printer_id,
  2757. printer_state_to_dict(
  2758. state,
  2759. printer_id,
  2760. printer_manager.get_model(printer_id),
  2761. printer_manager.get_drying_targets(printer_id),
  2762. ),
  2763. )
  2764. except Exception as e:
  2765. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2766. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2767. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2768. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2769. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2770. # "no existing assignment" for the same (printer, ams, tray) and race to
  2771. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2772. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2773. # bug stayed latent there. See services/ams_assignment_lock for details.
  2774. try:
  2775. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2776. from sqlalchemy.orm import selectinload
  2777. from backend.app.api.routes.settings import get_setting
  2778. from backend.app.models.spool import Spool
  2779. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2780. from backend.app.services.spool_tag_matcher import (
  2781. auto_assign_spool,
  2782. create_spool_from_tray,
  2783. find_matching_untagged_spool,
  2784. get_spool_by_tag,
  2785. is_bambu_tag,
  2786. is_valid_tag,
  2787. link_tag_to_inventory_spool,
  2788. tag_belongs_to_archived_spool,
  2789. )
  2790. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2791. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2792. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2793. if not _spoolman_on or _spoolman_on.lower() != "true":
  2794. for ams_unit in ams_data:
  2795. if not isinstance(ams_unit, dict):
  2796. continue
  2797. ams_id = int(ams_unit.get("id", 0))
  2798. for tray in ams_unit.get("tray", []):
  2799. if not isinstance(tray, dict):
  2800. continue
  2801. tray_id = int(tray.get("id", 0))
  2802. tag_uid = tray.get("tag_uid", "")
  2803. tray_uuid = tray.get("tray_uuid", "")
  2804. tray_info_idx = tray.get("tray_info_idx", "")
  2805. if not tray.get("tray_type"):
  2806. # Slot reported empty — drop any cached unknown-tag
  2807. # broadcast so reinserting the same spool re-prompts.
  2808. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2809. continue # Empty slot
  2810. # Check if assignment already exists for this slot
  2811. existing = await db.execute(
  2812. select(SA)
  2813. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2814. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2815. )
  2816. existing_assignment = existing.scalar_one_or_none()
  2817. if existing_assignment:
  2818. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2819. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2820. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2821. # Skip during active prints: the usage tracker handles deduction
  2822. # precisely via 3MF data on print completion. Without this guard the
  2823. # AMS remain% SET and the usage tracker ADD both fire from the same
  2824. # MQTT message, doubling the deduction (#880).
  2825. if _print_active:
  2826. continue
  2827. remain_raw = tray.get("remain")
  2828. if (
  2829. remain_raw is not None
  2830. and existing_assignment.spool
  2831. and not existing_assignment.spool.weight_locked
  2832. ):
  2833. try:
  2834. remain_val = int(remain_raw)
  2835. except (TypeError, ValueError):
  2836. remain_val = -1
  2837. if 1 <= remain_val <= 100:
  2838. lw = existing_assignment.spool.label_weight or 1000
  2839. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2840. current_used = existing_assignment.spool.weight_used or 0
  2841. if new_used > current_used + 1:
  2842. # Rechecked in the statement: the spool was loaded
  2843. # before this, and a weight set by hand (or weighed)
  2844. # and locked since then must stay (WL-6).
  2845. result = cast(
  2846. CursorResult,
  2847. await db.execute(
  2848. update(Spool)
  2849. .where(
  2850. Spool.id == existing_assignment.spool_id,
  2851. Spool.weight_locked.is_not(True),
  2852. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2853. )
  2854. .values(weight_used=new_used)
  2855. ),
  2856. )
  2857. await db.commit()
  2858. if result.rowcount:
  2859. logger.info(
  2860. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2861. existing_assignment.spool_id,
  2862. current_used,
  2863. new_used,
  2864. remain_val,
  2865. )
  2866. await ws_manager.broadcast({"type": "inventory_changed"})
  2867. # A K-profile the slot lost (the default K after a reset or
  2868. # power cycle) is put back by kprofile_drift on the next idle
  2869. # push; a different real profile was picked on purpose and
  2870. # stays (#3219, item 44).
  2871. continue
  2872. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2873. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2874. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2875. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2876. # An archived spool still in the AMS: the slot
  2877. # stays free rather than adopting its tag.
  2878. continue
  2879. if not spool:
  2880. # Try matching an untagged inventory spool (same material/color)
  2881. spool = await find_matching_untagged_spool(db, tray)
  2882. if spool:
  2883. await link_tag_to_inventory_spool(db, spool, tray)
  2884. elif _auto_add_unknown:
  2885. spool = await create_spool_from_tray(db, tray)
  2886. else:
  2887. # Auto-add disabled: surface the slot so the
  2888. # user can add it manually via the UI.
  2889. await _broadcast_unknown_tag(
  2890. printer_id=printer_id,
  2891. ams_id=ams_id,
  2892. tray_id=tray_id,
  2893. tag_uid=tag_uid,
  2894. tray_uuid=tray_uuid,
  2895. tray_type=tray.get("tray_type"),
  2896. tray_color=tray.get("tray_color"),
  2897. tray_sub_brands=tray.get("tray_sub_brands"),
  2898. tray_count=len(ams_unit.get("tray", [])),
  2899. )
  2900. continue
  2901. # Slot matched (existing tag, untagged inventory
  2902. # match, or freshly auto-created spool) — drop any
  2903. # stale dedup so a future tag swap re-prompts.
  2904. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2905. await auto_assign_spool(
  2906. printer_id,
  2907. ams_id,
  2908. tray_id,
  2909. spool,
  2910. printer_manager,
  2911. db,
  2912. tray_info_idx=tray_info_idx,
  2913. )
  2914. await db.commit()
  2915. await ws_manager.broadcast(
  2916. {
  2917. "type": "spool_auto_assigned",
  2918. "printer_id": printer_id,
  2919. "ams_id": ams_id,
  2920. "tray_id": tray_id,
  2921. "spool_id": spool.id,
  2922. }
  2923. )
  2924. logger.info(
  2925. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2926. spool.id,
  2927. printer_id,
  2928. ams_id,
  2929. tray_id,
  2930. )
  2931. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2932. db, tag_uid, tray_uuid
  2933. ):
  2934. # Non-BL spool with some tag — let user choose (not
  2935. # an archived one's, whose slot stays free)
  2936. await _broadcast_unknown_tag(
  2937. printer_id=printer_id,
  2938. ams_id=ams_id,
  2939. tray_id=tray_id,
  2940. tag_uid=tag_uid,
  2941. tray_uuid=tray_uuid,
  2942. tray_type=tray.get("tray_type"),
  2943. tray_color=tray.get("tray_color"),
  2944. tray_sub_brands=tray.get("tray_sub_brands"),
  2945. tray_count=len(ams_unit.get("tray", [])),
  2946. )
  2947. # No-tag slots (generic non-RFID filament) are left alone:
  2948. # nothing to identify, prompting "+ Add" would just create
  2949. # ghost spools with empty tags on every confirm.
  2950. except Exception as e:
  2951. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2952. try:
  2953. async with async_session() as db:
  2954. from backend.app.api.routes.settings import get_setting
  2955. from backend.app.models.printer import Printer
  2956. # Check if Spoolman is enabled
  2957. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2958. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2959. return
  2960. # Check sync mode
  2961. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2962. if sync_mode and sync_mode != "auto":
  2963. return # Only sync on auto mode
  2964. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2965. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2966. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2967. # always owned by per-print tracking, never by AMS auto-sync. The
  2968. # setting is still read by the settings UI for backwards compat but
  2969. # has no effect on the sync path here.
  2970. # Get Spoolman URL
  2971. spoolman_url = await get_setting(db, "spoolman_url")
  2972. if not spoolman_url:
  2973. return
  2974. # Get or create Spoolman client
  2975. client = await get_spoolman_client()
  2976. if not client:
  2977. try:
  2978. client = await init_spoolman_client(spoolman_url)
  2979. except ValueError as exc:
  2980. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2981. return
  2982. # Check if Spoolman is reachable
  2983. if not await client.health_check():
  2984. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2985. return
  2986. # Get printer name for location
  2987. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2988. printer = result.scalar_one_or_none()
  2989. printer_name = printer.name if printer else f"Printer {printer_id}"
  2990. # OPTIMIZATION: Fetch all spools once before processing trays
  2991. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2992. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2993. try:
  2994. cached_spools = await client.get_spools()
  2995. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2996. except Exception as e:
  2997. logger.error(
  2998. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2999. printer_id,
  3000. e,
  3001. )
  3002. return
  3003. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3004. from sqlalchemy.orm import selectinload
  3005. from backend.app.models.spool_assignment import SpoolAssignment
  3006. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3007. from backend.app.services.ams_slot_presence import spool_present
  3008. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3009. # Built-in remaining weight, used by sync_ams_tray only when the
  3010. # firmware reports an unusable remain%/tray_weight for a slot.
  3011. #
  3012. # Left empty since #2812. This block runs in Spoolman mode only,
  3013. # and until then the built-in table was emptied on the switch, so
  3014. # there was never anything here to read and the fallback was inert.
  3015. # Preserving those rows makes it live again, and it is keyed by slot
  3016. # rather than by spool: after a mode switch the tray may well hold
  3017. # different filament, and ``create_spool`` writes ``remaining_weight``
  3018. # unconditionally, so a stale figure would be seeded into a brand new
  3019. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3020. # intent survives for whoever revisits the cross-mode fallback.
  3021. inventory_weights: dict[tuple[int, int], float] = {}
  3022. if not await spoolman_owns_assignments(db):
  3023. try:
  3024. assign_result = await db.execute(
  3025. select(SpoolAssignment)
  3026. .options(selectinload(SpoolAssignment.spool))
  3027. .where(SpoolAssignment.printer_id == printer_id)
  3028. )
  3029. for assignment in assign_result.scalars().all():
  3030. spool = assignment.spool
  3031. if spool and spool.label_weight > 0:
  3032. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3033. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3034. except Exception as e:
  3035. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3036. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3037. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3038. slot_map_read = False
  3039. try:
  3040. slot_result = await db.execute(
  3041. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3042. )
  3043. for slot in slot_result.scalars().all():
  3044. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3045. slot_map_read = True
  3046. except Exception as e:
  3047. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3048. # Sync each AMS tray and collect slot changes for DB persistence
  3049. synced = 0
  3050. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3051. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3052. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3053. for ams_unit in ams_data:
  3054. if not isinstance(ams_unit, dict):
  3055. continue
  3056. ams_id = int(ams_unit.get("id", 0))
  3057. trays = ams_unit.get("tray", [])
  3058. for tray_data in trays:
  3059. if not isinstance(tray_data, dict):
  3060. continue
  3061. tray_id_raw = int(tray_data.get("id", 0))
  3062. tray = client.parse_ams_tray(ams_id, tray_data)
  3063. if not tray:
  3064. # Empty tray slot — record for local assignment cleanup
  3065. # and drop any cached unknown-tag broadcast so a
  3066. # reinserted spool re-prompts.
  3067. #
  3068. # Not during a running print: a slot that empties there
  3069. # is a filament runout, and the spool is still in the
  3070. # AMS. `spoolman_slot_assignments` is how a tag-less
  3071. # spool assigned through the Bambuddy UI is resolved at
  3072. # completion (#1459), so deleting the row mid-print
  3073. # loses the runout segment's usage — the same failure
  3074. # the internal inventory's auto-unlink had.
  3075. #
  3076. # Nor when firmware's presence bit says the slot is
  3077. # occupied. parse_ams_tray calls a tray with no type or
  3078. # no colour empty, and a spool the AMS cannot read has
  3079. # neither until something configures it — so a tag-less
  3080. # spool assigned through the UI had its row deleted by
  3081. # the first idle push after it was inserted. Same
  3082. # deletion as the internal inventory's in #3100, same
  3083. # answer, so the two modes stay in step.
  3084. #
  3085. # And only once the slot has stayed empty for the grace
  3086. # period -- the internal inventory's #3186 answer, for
  3087. # the same one-push blank.
  3088. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3089. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3090. if not printing_now and (
  3091. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3092. ):
  3093. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3094. empty_slots.append((ams_id, tray_id_raw))
  3095. else:
  3096. spoolman_held.add(hold_key)
  3097. logger.info(
  3098. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3099. "unlinking if it is still empty in %ds",
  3100. ams_id,
  3101. tray_id_raw,
  3102. linked_spool,
  3103. int(slot_unlink_grace.GRACE_SECONDS),
  3104. )
  3105. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3106. continue
  3107. spool_tag = (
  3108. tray.tray_uuid
  3109. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3110. else tray.tag_uid
  3111. )
  3112. # Provide the hint only when no RFID is available
  3113. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3114. try:
  3115. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3116. result = await client.sync_ams_tray(
  3117. tray,
  3118. printer_name,
  3119. db,
  3120. # Per-print tracking is the only weight writer (#1119).
  3121. # AMS auto-sync still maintains spool metadata / slot
  3122. # assignments but no longer touches remaining_weight.
  3123. disable_weight_sync=True,
  3124. cached_spools=cached_spools,
  3125. inventory_remaining=inv_remaining,
  3126. spoolman_spool_id_hint=hint,
  3127. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3128. )
  3129. if result is None and spool_tag and not auto_add_unknown_rfid:
  3130. # Spoolman skipped auto-create per user setting — surface
  3131. # the slot so the UI can offer "+ Add to inventory".
  3132. await _broadcast_unknown_tag(
  3133. printer_id=printer_id,
  3134. ams_id=ams_id,
  3135. tray_id=tray.tray_id,
  3136. tag_uid=tray.tag_uid or "",
  3137. tray_uuid=tray.tray_uuid or "",
  3138. tray_type=tray.tray_type,
  3139. tray_color=tray.tray_color,
  3140. tray_sub_brands=tray.tray_sub_brands,
  3141. tray_count=len(trays),
  3142. )
  3143. elif result:
  3144. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3145. if result:
  3146. synced += 1
  3147. if result.get("id"):
  3148. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3149. # If a new spool was created, add it to the cache
  3150. # so subsequent trays can find it if they reference the same tag
  3151. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3152. if not spool_exists:
  3153. cached_spools.append(result)
  3154. logger.debug(
  3155. "[Printer %s] Added newly created spool %s to cache",
  3156. printer_id,
  3157. result["id"],
  3158. )
  3159. # Reconcile slot_preset_mappings (the same row internal
  3160. # mode keeps in sync via inventory + spool_tag_matcher).
  3161. # Without this the slot card surfaces the previous spool's
  3162. # preset name — same bug shape, different inventory mode.
  3163. from backend.app.services.slot_preset_writer import (
  3164. upsert_slot_preset_for_spoolman_spool,
  3165. )
  3166. await upsert_slot_preset_for_spoolman_spool(
  3167. db=db,
  3168. spoolman_spool=result,
  3169. tray_info_idx=tray.tray_info_idx or "",
  3170. tray_sub_brands=tray.tray_sub_brands or "",
  3171. tray_type=tray.tray_type or "",
  3172. printer_id=printer_id,
  3173. ams_id=ams_id,
  3174. tray_id=tray.tray_id,
  3175. )
  3176. except Exception as e:
  3177. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3178. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3179. if synced > 0:
  3180. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3181. # Persist slot assignment changes to the local table: only slots
  3182. # whose spool this pass changed, and only while they still hold what
  3183. # it read before awaiting Spoolman, so a spool assigned by hand in
  3184. # between stays (SSA-3). The changed slots are announced: the slot
  3185. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3186. # tray, so with no event it kept the previous spool's preset name.
  3187. if slot_changes or empty_slots:
  3188. from backend.app.services.spoolman_slot_sync import write_slot_results
  3189. try:
  3190. await write_slot_results(
  3191. db,
  3192. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3193. if slot_map_read
  3194. else None,
  3195. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3196. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3197. )
  3198. except Exception as e:
  3199. await db.rollback()
  3200. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3201. except Exception as e:
  3202. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3203. # Largest finish photo attached to a notification; a bigger one is still linked.
  3204. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3205. async def _finish_photo_for_notification(
  3206. db, archive, archive_id: int, filename: str
  3207. ) -> tuple[str | None, bytes | None]:
  3208. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3209. With authentication off the link is the archive's own photo route, as it
  3210. always was: it opens without a login and doesn't expire. With
  3211. authentication on that route needs a media token, which nothing tapping a
  3212. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3213. link only ever answered 401. The photo is then saved as a notification
  3214. photo as well (utils/notification_photos.py) and the link points there: an
  3215. unguessable name that opens this one photo and nothing else, for 3 days.
  3216. The link is relative when no External URL is set. Bytes over
  3217. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3218. ``(None, None)`` when the photo can't be found.
  3219. """
  3220. from backend.app.api.routes.settings import get_setting
  3221. from backend.app.core.auth import is_auth_enabled
  3222. from backend.app.utils.archive_paths import find_archive_photo
  3223. from backend.app.utils.notification_photos import save_notification_photo
  3224. log = logging.getLogger(__name__)
  3225. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3226. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3227. photo_bytes: bytes | None = None
  3228. try:
  3229. photo_path = find_archive_photo(archive, filename)
  3230. if photo_path is not None:
  3231. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3232. except Exception as e:
  3233. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3234. try:
  3235. auth_on = await is_auth_enabled(db)
  3236. except Exception:
  3237. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3238. if auth_on:
  3239. url = None
  3240. if photo_bytes:
  3241. try:
  3242. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3243. url = f"{base}/api/v1/notifications/photos/{name}"
  3244. except Exception as e:
  3245. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3246. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3247. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3248. return url, None
  3249. if photo_bytes:
  3250. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3251. return url, photo_bytes
  3252. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3253. """Capture a camera snapshot for notification image attachment.
  3254. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3255. Uses: external camera > buffered frame > fresh capture.
  3256. Turns the chamber light on for the picture when the printer asks for it
  3257. (#1655). ``light=False`` is for callers that capture all through a print,
  3258. where the light would flash with every frame.
  3259. """
  3260. if not printer:
  3261. return None
  3262. async with camera_light(printer if light else None):
  3263. return await _capture_snapshot_frame(printer_id, printer, logger)
  3264. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3265. """The capture behind ``_capture_snapshot_for_notification``."""
  3266. try:
  3267. from backend.app.api.routes.settings import get_setting
  3268. async with async_session() as db:
  3269. capture_enabled = await get_setting(db, "capture_finish_photo")
  3270. if capture_enabled is not None and capture_enabled.lower() != "true":
  3271. return None
  3272. # Try external camera first
  3273. if printer.external_camera_enabled and printer.external_camera_url:
  3274. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3275. from backend.app.api.routes.camera import live_frame_for_capture
  3276. from backend.app.services.external_camera import capture_frame
  3277. # An external camera allows one reader, so capturing while a viewer
  3278. # is attached fails (#2707). A None here falls through to the paths
  3279. # below exactly as a failed capture did.
  3280. defer, buffered = live_frame_for_capture(printer_id)
  3281. if defer:
  3282. frame_data = buffered
  3283. else:
  3284. frame_data = await capture_frame(
  3285. printer.external_camera_url,
  3286. printer.external_camera_type or "mjpeg",
  3287. snapshot_url=printer.external_camera_snapshot_url,
  3288. )
  3289. if frame_data and len(frame_data) <= 2_500_000:
  3290. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3291. return _apply_camera_rotation(frame_data, printer, logger)
  3292. # Try buffered frame from active stream
  3293. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3294. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3295. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3296. buffered_frame = get_buffered_frame(printer_id)
  3297. if (active_for_printer or active_chamber) and buffered_frame:
  3298. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3299. if len(buffered_frame) <= 2_500_000:
  3300. return _apply_camera_rotation(buffered_frame, printer, logger)
  3301. # Fresh capture from printer camera
  3302. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3303. from backend.app.services.camera import capture_camera_frame_bytes
  3304. frame_data = await capture_camera_frame_bytes(
  3305. printer.ip_address, printer.access_code, printer.model, timeout=15
  3306. )
  3307. if frame_data and len(frame_data) <= 2_500_000:
  3308. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3309. return _apply_camera_rotation(frame_data, printer, logger)
  3310. except Exception as e:
  3311. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3312. return None
  3313. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3314. """#1867: bank a recent in-print camera frame for the finish photo.
  3315. Called on every layer change and (#2547) on every print-progress advance.
  3316. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3317. path has a pre-End-G-code image for prints that end with a plate swap.
  3318. Both drivers are print telemetry that stops the instant printing ends: no
  3319. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3320. plate swap) executes. So the last banked frame is always the finished print,
  3321. never the swapped plate — that property is what the #1867 path relies on and
  3322. it must survive any change to the throttle below.
  3323. Layer changes alone were not enough: they stop when the *final* layer
  3324. begins, which on a three-minute last layer left the bank stale by the whole
  3325. length of that layer (#2547). Progress keeps ticking through it.
  3326. Best-effort: any failure just leaves the previous banked frame.
  3327. """
  3328. logger = logging.getLogger(__name__)
  3329. client = printer_manager.get_client(printer_id)
  3330. state = client.state if client else None
  3331. if not state or state.state != "RUNNING":
  3332. return
  3333. # Only during actual extrusion — firmware ticks layer_num during the
  3334. # pre-print calibration sequence, whose sub-stages are non-zero.
  3335. if state.mc_print_sub_stage not in (None, 0):
  3336. return
  3337. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3338. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3339. # now that progress advances also drive banking, that exemption would fire a
  3340. # camera grab on every percent tick of the last layer. Bambu printers accept
  3341. # one RTSP client at a time, so each grab contends with the live view.
  3342. now = time.monotonic()
  3343. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3344. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3345. return
  3346. total = state.total_layers or 0
  3347. try:
  3348. async with async_session() as db:
  3349. from backend.app.models.printer import Printer
  3350. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3351. printer = result.scalar_one_or_none()
  3352. if not printer:
  3353. return
  3354. # Reuses the notification snapshot path, which honours the
  3355. # `capture_finish_photo` setting (returns None when disabled) so we
  3356. # don't bank frames the user never asked for. Without the chamber light
  3357. # (#1655): this runs every 25 seconds for the whole print.
  3358. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3359. if frame:
  3360. _inprint_frame_bank[printer_id] = frame
  3361. _inprint_frame_bank_ts[printer_id] = now
  3362. logger.debug(
  3363. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3364. printer_id,
  3365. layer_num,
  3366. total,
  3367. len(frame),
  3368. )
  3369. except Exception as e:
  3370. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3371. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3372. """Apply camera rotation to snapshot image if configured."""
  3373. from backend.app.services.camera import apply_camera_rotation
  3374. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3375. async def _send_print_start_notification(
  3376. printer_id: int,
  3377. data: dict,
  3378. archive_data: dict | None = None,
  3379. logger=None,
  3380. ):
  3381. """Helper to send print start notification with optional archive data."""
  3382. if logger is None:
  3383. logger = logging.getLogger(__name__)
  3384. try:
  3385. async with async_session() as db:
  3386. from backend.app.models.printer import Printer
  3387. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3388. printer = result.scalar_one_or_none()
  3389. printer_name = printer.name if printer else f"Printer {printer_id}"
  3390. # Capture camera snapshot for notification image attachment
  3391. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3392. if image_data:
  3393. if archive_data is None:
  3394. archive_data = {}
  3395. archive_data["image_data"] = image_data
  3396. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3397. # Send user-specific email notification for print start
  3398. if archive_data and archive_data.get("created_by_id"):
  3399. await notification_service.send_user_print_email(
  3400. event_type="user_print_start",
  3401. created_by_id=archive_data["created_by_id"],
  3402. printer_name=printer_name,
  3403. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3404. db=db,
  3405. )
  3406. except Exception as e:
  3407. logger.warning("Notification on_print_start failed: %s", e)
  3408. async def _dispatch_user_print_email(
  3409. status: str,
  3410. created_by_id: int | None,
  3411. printer_name: str,
  3412. filename: str,
  3413. db,
  3414. image_data: bytes | None = None,
  3415. finish_photo_url: str | None = None,
  3416. ) -> None:
  3417. """Send a user-specific print-completion email based on print status.
  3418. Maps the normalised print status to the correct event type and delegates
  3419. to :meth:`NotificationService.send_user_print_email`. A single helper
  3420. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3421. "stopped"`` dispatch block at every call site.
  3422. Does nothing if *created_by_id* is ``None``.
  3423. """
  3424. if created_by_id is None:
  3425. return
  3426. if status == "completed":
  3427. event_type = "user_print_complete"
  3428. elif status == "failed":
  3429. event_type = "user_print_failed"
  3430. elif status in ("stopped", "aborted", "cancelled"):
  3431. event_type = "user_print_stopped"
  3432. else:
  3433. return
  3434. await notification_service.send_user_print_email(
  3435. event_type=event_type,
  3436. created_by_id=created_by_id,
  3437. printer_name=printer_name,
  3438. filename=filename,
  3439. db=db,
  3440. image_data=image_data,
  3441. finish_photo_url=finish_photo_url,
  3442. )
  3443. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3444. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3445. try:
  3446. from backend.app.services.archive import extract_printable_objects_from_archive
  3447. client = printer_manager.get_client(printer_id)
  3448. if not client:
  3449. return
  3450. # Extract with positions for UI overlay, scoped to the plate that
  3451. # is printing — resolve_plate_id is the same resolver /cover uses,
  3452. # so the object list can't disagree with the thumbnail it is drawn
  3453. # over (#2522).
  3454. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3455. app_settings.base_dir / archive.file_path,
  3456. plate_number=resolve_plate_id(client.state),
  3457. )
  3458. if printable_objects:
  3459. client.state.printable_objects = printable_objects
  3460. client.state.printable_objects_bbox_all = bbox_all
  3461. client.state.skipped_objects = []
  3462. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3463. except Exception as e:
  3464. logger.debug("Failed to extract printable objects from archive: %s", e)
  3465. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3466. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3467. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3468. handler must not wait for it. Kept only while the printer is still on
  3469. the print they were read for: a new print replaces the list.
  3470. ``warned_layers``: pauses this print was already warned about, kept on its
  3471. archive, so a restart does not send the heads-up again.
  3472. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3473. is on. Its pauses up to there are behind it, though the printer's layer
  3474. reads 0 until it reports the next one.
  3475. """
  3476. client = printer_manager.get_client(printer_id)
  3477. if not client:
  3478. return
  3479. state = client.state
  3480. read_for = state.pause_points
  3481. try:
  3482. plate_id = resolve_plate_id(state)
  3483. except Exception:
  3484. # Never at the cost of the print-start handler this runs inside.
  3485. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3486. return
  3487. async def _load() -> None:
  3488. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3489. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3490. if state.pause_points is not read_for:
  3491. return
  3492. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3493. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3494. if points:
  3495. logging.getLogger(__name__).info(
  3496. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3497. len(points),
  3498. printer_id,
  3499. [p.layer for p in points],
  3500. )
  3501. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3502. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3503. """Pauses for a print start taken as the resumption of a running print.
  3504. A restart while the print was paused makes its resume look like a new
  3505. print (#2984): the pauses warned about and passed are kept from before.
  3506. """
  3507. client = printer_manager.get_client(printer_id)
  3508. state = client.state if client else None
  3509. _load_pauses_from_3mf(
  3510. app_settings.base_dir / archive.file_path,
  3511. printer_id,
  3512. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3513. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3514. )
  3515. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3516. """Put the skip-objects list back after a restart mid-print.
  3517. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3518. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3519. which the #1304 guard suppresses on the first RUNNING push after startup.
  3520. Everything else this hook restores (the archive, the usage-tracking session,
  3521. the timelapse baseline) was already handled; the object list was not, so a
  3522. restart mid-print took skip-objects away for the rest of that print.
  3523. Nothing recovered it either: the printer card gates its Skip button on the
  3524. object count, and the one endpoint that can rebuild the list is reachable
  3525. only from the modal that button opens.
  3526. The archive is the running print's as ``running_print_archive`` finds it:
  3527. by subtask_id, or for a print that reports none by the archive bound to it
  3528. (#3327), never by name: a leftover ``status="printing"`` row from a
  3529. completion we never saw must not hand this print someone else's objects.
  3530. After a restart that binding exists only for Bambuddy's own prints, so a
  3531. print that reports no subtask_id loads nothing rather than a guess; the
  3532. reload path on ``GET /print/objects`` covers that case on demand.
  3533. """
  3534. client = printer_manager.get_client(printer_id)
  3535. if client is None or (client.state.printable_objects and client.state.pause_points):
  3536. return
  3537. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3538. if archive is not None and archive.file_path:
  3539. if not client.state.printable_objects:
  3540. _load_objects_from_archive(archive, printer_id, logger)
  3541. # The slicer's pauses are in-memory only as well (#2984).
  3542. if not client.state.pause_points:
  3543. _load_pauses_from_3mf(
  3544. app_settings.base_dir / archive.file_path,
  3545. printer_id,
  3546. warned_layers=pause_eta.warned_layers_of(archive, state),
  3547. )
  3548. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3549. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3550. # past it; the second covers a handshake that failed again on the way back and
  3551. # armed a fresh one. Module-level so tests can shrink them.
  3552. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3553. # Retry ladder for the other temporary give-up: the file service answered and
  3554. # the transfer still did not finish, which at print start is usually the printer
  3555. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3556. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3557. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3558. # two cover a printer that stays busy well into the print.
  3559. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3560. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3561. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3562. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3563. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3564. # by view, so two views race), the cool-off retry task, and print completion.
  3565. # Without this they each read file_path == "" and each run a full copy, so the row
  3566. # ends up pointing at one timestamped directory while the others sit orphaned.
  3567. #
  3568. # Keyed by printer rather than archive because a printer runs one print at a time,
  3569. # which makes the two equally strong here — and it bounds the dict by printer
  3570. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3571. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3572. # resuming, so "no waiters" is not a question this API can answer.
  3573. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3574. # How many of a printer's newest archives a touchscreen reprint is compared
  3575. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3576. # print start from reading a long history's extra_data.
  3577. _REPEAT_LOOKBACK = 200
  3578. async def _archived_3mf_for_repeat(
  3579. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3580. ):
  3581. """The newest archive of the job this printer is running again, with its 3MF.
  3582. A "Print again" on the printer's screen never names the file on the card:
  3583. it reports its own history copy under a generic name
  3584. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3585. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3586. not the card file's name, so every lookup built from it misses (#3307).
  3587. An earlier run that was archived recorded that same title and plate in its
  3588. ``_print_data``, and holds the 3MF.
  3589. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3590. known on both sides must agree: the same title and plate re-sliced is
  3591. another job. None when nothing matches.
  3592. """
  3593. from backend.app.models.archive import PrintArchive
  3594. if not subtask_name or not gcode_file:
  3595. return None
  3596. rows = (
  3597. (
  3598. await db.execute(
  3599. select(PrintArchive)
  3600. .where(
  3601. PrintArchive.printer_id == printer_id,
  3602. PrintArchive.deleted_at.is_(None),
  3603. PrintArchive.file_path.isnot(None),
  3604. PrintArchive.file_path != "",
  3605. )
  3606. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3607. .limit(_REPEAT_LOOKBACK)
  3608. )
  3609. )
  3610. .scalars()
  3611. .all()
  3612. )
  3613. for archive in rows:
  3614. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3615. run = extra.get("_print_data")
  3616. if not isinstance(run, dict):
  3617. continue
  3618. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3619. continue
  3620. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3621. continue
  3622. if not (app_settings.base_dir / archive.file_path).is_file():
  3623. continue
  3624. return archive
  3625. return None
  3626. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3627. """Fill in a no-3MF archive from a 3MF that turned up later.
  3628. Returns True when the row was upgraded. Safe to call speculatively: it
  3629. verifies the archive still exists, is still a fallback, and that the file
  3630. is a readable 3MF before touching anything.
  3631. Serialised per printer — see ``_fallback_recovery_locks``.
  3632. """
  3633. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3634. async with lock:
  3635. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3636. async def _recover_fallback_archive_locked(
  3637. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3638. ) -> bool:
  3639. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3640. ``price`` is False when the print's end is being handled: the archive
  3641. still reads "printing" then, and its end prices it.
  3642. """
  3643. import zipfile
  3644. from backend.app.models.archive import PrintArchive
  3645. from backend.app.services.archive import ArchiveService
  3646. logger = logging.getLogger(__name__)
  3647. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3648. return False
  3649. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3650. # A truncated or half-written download is worse than no download: it
  3651. # would replace an honest empty archive with wrong metadata.
  3652. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3653. return False
  3654. async with async_session() as db:
  3655. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3656. if archive is None or archive.deleted_at is not None:
  3657. return False
  3658. if archive.file_path:
  3659. # Already recovered, or never was a fallback. Either way there is a
  3660. # real 3MF attached and overwriting it is not this function's job.
  3661. return False
  3662. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3663. service = ArchiveService(db)
  3664. recovered = await service.archive_print(
  3665. printer_id=printer_id,
  3666. source_file=source_3mf,
  3667. print_data={**print_data, "status": archive.status or "printing"},
  3668. subtask_id=archive.subtask_id,
  3669. update_archive_id=archive.id,
  3670. )
  3671. if recovered is None:
  3672. return False
  3673. logger.info(
  3674. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3675. archive_id,
  3676. source_3mf,
  3677. recovered.file_size,
  3678. )
  3679. # Spoolman's tracking stored no 3MF usage at print start and would
  3680. # charge the AMS remain% change; the built-in tracker reads the archive
  3681. # at completion and needs nothing. Also at the print's end (``price``
  3682. # False): that recovery runs inside the close-out, before the charge.
  3683. try:
  3684. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3685. from backend.app.services.usage_tracker import is_completing
  3686. await attach_recovered_3mf(
  3687. printer_id,
  3688. recovered.id,
  3689. recovered.file_path,
  3690. db,
  3691. printer_manager,
  3692. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3693. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3694. )
  3695. except Exception:
  3696. logger.warning(
  3697. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3698. )
  3699. if price and recovered.status == "printing" and recovered.file_path:
  3700. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3701. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3702. if price and recovered.status == "printing":
  3703. # Print start priced it from the default rate, having no 3MF to
  3704. # estimate from; now it has one. An ended print is left alone: its
  3705. # end prices it. A print Bambuddy didn't dispatch has no start
  3706. # plate; the one the archive just read from the 3MF stands in.
  3707. _schedule_archive_cost_estimate(
  3708. printer_id,
  3709. recovered.id,
  3710. printer_manager,
  3711. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3712. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3713. session_factory=async_session,
  3714. )
  3715. # `archive_updated`, not `archive_created` — the row was already on the
  3716. # Archives page as an empty card and is now filled in, not new.
  3717. await ws_manager.send_archive_updated(
  3718. {
  3719. "id": recovered.id,
  3720. "printer_id": recovered.printer_id,
  3721. "filename": recovered.filename,
  3722. "print_name": recovered.print_name,
  3723. "status": recovered.status,
  3724. }
  3725. )
  3726. return True
  3727. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3728. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3729. Called from the paths that pull a 3MF for a print that is already under way
  3730. — chiefly the cover endpoint, which downloads the very file the archive flow
  3731. could not get and, before #2957, used it for a thumbnail and nothing else.
  3732. The bytes are already local, so this costs a parse and a row update.
  3733. No-op when the running print has a real archive, which is the common case.
  3734. """
  3735. from backend.app.models.archive import PrintArchive
  3736. logger = logging.getLogger(__name__)
  3737. # `_active_prints` is keyed on the raw names seen at print start — the
  3738. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3739. # Callers here arrive with whichever variant their own path produced, so
  3740. # match on the same normalization the download cache uses rather than on an
  3741. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3742. # endpoint find an archive registered under "Desktop_Goose".
  3743. wanted = normalize_3mf_name(name)
  3744. archive_id = None
  3745. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3746. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3747. archive_id = value
  3748. break
  3749. if archive_id is None:
  3750. return False
  3751. async with async_session() as db:
  3752. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3753. # Cheap pre-check so the common case (a normal archive) does no work.
  3754. if archive is None or archive.file_path or archive.deleted_at is not None:
  3755. return False
  3756. try:
  3757. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3758. except Exception as e:
  3759. # Recovery is opportunistic. A failure here must never take down the
  3760. # caller, which is usually just trying to render a thumbnail.
  3761. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3762. return False
  3763. def _schedule_fallback_3mf_retry(
  3764. printer_id: int,
  3765. archive_id: int,
  3766. filenames: list[str],
  3767. delays: tuple[float, ...] | None = None,
  3768. reason: str = REASON_FTPS_COOLOFF,
  3769. ) -> None:
  3770. """Re-attempt the 3MF download after a temporary give-up.
  3771. ``reason`` says which give-up this is, and picks the default ladder: an
  3772. FTPS cool-off has to be waited out, while a transfer that timed out under
  3773. contention is worth asking about again straight away (#3063). It is only
  3774. read for the ladder and the log line -- the retry itself is identical, since
  3775. in both cases the file is on the printer and the last attempt at it failed
  3776. for a reason that does not last.
  3777. """
  3778. logger = logging.getLogger(__name__)
  3779. if delays is None:
  3780. delays = (
  3781. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3782. if reason == REASON_FTP_TRANSFER_FAILED
  3783. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3784. )
  3785. async def _retry() -> None:
  3786. from backend.app.models.archive import PrintArchive
  3787. from backend.app.models.printer import Printer
  3788. for delay in delays:
  3789. await asyncio.sleep(delay)
  3790. async with async_session() as db:
  3791. archive = (
  3792. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3793. ).scalar_one_or_none()
  3794. if archive is None or archive.deleted_at is not None or archive.file_path:
  3795. return
  3796. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3797. if printer is None:
  3798. return
  3799. # Read the fields while the session is open rather than touching
  3800. # a detached instance minutes later, mid-download.
  3801. printer_ip = printer.ip_address
  3802. printer_code = printer.access_code
  3803. printer_model = printer.model
  3804. # Someone else may have fetched it in the meantime — the cover
  3805. # endpoint routinely does, and its copy is the same bytes.
  3806. for name in filenames:
  3807. cached = get_cached_3mf(printer_id, name)
  3808. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3809. return
  3810. if ftps_handshake_blocked(printer_ip):
  3811. logger.info(
  3812. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3813. printer_id,
  3814. archive_id,
  3815. )
  3816. continue
  3817. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3818. for candidate in filenames:
  3819. # Bare name only. These come from the print-start flow, which
  3820. # already strips the path, but the local temp write must not
  3821. # depend on that holding for every future caller — a name that
  3822. # is absolute or contains ".." would otherwise escape the data
  3823. # volume via the `/` operator.
  3824. name = Path(candidate).name
  3825. if not name or name in (".", ".."):
  3826. continue
  3827. if not name.endswith(".3mf"):
  3828. name = f"{name}.3mf"
  3829. temp_path = app_settings.archive_dir / "temp" / name
  3830. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3831. try:
  3832. hit = await download_file_try_paths_async(
  3833. printer_ip,
  3834. printer_code,
  3835. ftp_probe_paths(name),
  3836. temp_path,
  3837. socket_timeout=ftp_timeout,
  3838. printer_model=printer_model,
  3839. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3840. )
  3841. except Exception as e:
  3842. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3843. continue
  3844. if not hit:
  3845. continue
  3846. cache_3mf_download(printer_id, name, temp_path)
  3847. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3848. return
  3849. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3850. async def _guarded() -> None:
  3851. try:
  3852. await _retry()
  3853. except asyncio.CancelledError:
  3854. raise
  3855. except Exception as e:
  3856. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3857. finally:
  3858. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3859. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3860. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3861. if existing and not existing.done():
  3862. existing.cancel()
  3863. task = asyncio.create_task(_guarded())
  3864. _fallback_3mf_retry_tasks[printer_id] = task
  3865. logger.info(
  3866. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3867. archive_id,
  3868. reason,
  3869. printer_id,
  3870. ", ".join(f"{d:g}s" for d in delays),
  3871. )
  3872. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3873. """Whether an archive created here should ask for the print's outcome (#1898).
  3874. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3875. branches below: a queued job already has its archive and takes the
  3876. expected-print branch, where the queue item's own ``confirm_outcome``
  3877. decides. The queue is still consulted, because a restart mid-print empties
  3878. ``_expected_prints`` — without the check the setting could override a queue
  3879. item that deliberately has the flag off. Any failure answers "don't ask":
  3880. an unwanted prompt is worse than a missing one, and this must never be the
  3881. reason a print goes unarchived.
  3882. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3883. leaves one behind when a completion cannot be matched to it
  3884. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3885. only takes it back once the printer has sat connected and terminal for
  3886. minutes. Until then every screen-started print on that printer would
  3887. silently lose its prompt, so the row is held against ``observed_name`` by
  3888. the same comparison a completion uses: a positive disagreement means the row
  3889. is about some other run and this print is external after all.
  3890. """
  3891. logger = logging.getLogger(__name__)
  3892. try:
  3893. # A savepoint rather than a rollback of the caller's transaction on
  3894. # failure: a failed statement leaves the transaction unusable, but a
  3895. # full rollback also expires every object the caller has loaded (the
  3896. # printer, the archive it just created), and on an async session the
  3897. # next attribute read then raises instead of reloading. Everything here
  3898. # is a read, so undoing the savepoint loses nothing.
  3899. async with db.begin_nested():
  3900. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3901. except Exception as e:
  3902. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3903. return False
  3904. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3905. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3906. from backend.app.api.routes.settings import get_setting, setting_is_true
  3907. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3908. return False
  3909. from backend.app.models.print_queue import PrintQueueItem
  3910. dispatched_here = await db.scalar(
  3911. select(PrintQueueItem)
  3912. .where(
  3913. PrintQueueItem.printer_id == printer_id,
  3914. PrintQueueItem.status == "printing",
  3915. )
  3916. .limit(1)
  3917. )
  3918. if dispatched_here is None:
  3919. return True
  3920. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3921. observed = (observed_name or "").strip()
  3922. if not expected or not observed or _subtask_names_match(expected, observed):
  3923. logger.info(
  3924. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3925. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3926. printer_id,
  3927. dispatched_here.id,
  3928. )
  3929. return False
  3930. logger.info(
  3931. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3932. "%r; treating this as an externally started print.",
  3933. dispatched_here.id,
  3934. printer_id,
  3935. expected,
  3936. observed,
  3937. )
  3938. return True
  3939. async def _dispatch_outcome_confirmation_safely(
  3940. db,
  3941. printer_id: int,
  3942. printer_name: str,
  3943. data: dict,
  3944. archive_id: int,
  3945. archive_data: dict | None = None,
  3946. ) -> None:
  3947. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3948. The completion task sends the per-user print email on the same session
  3949. right after the prompt. A failed statement in the prompt leaves that
  3950. session needing a rollback, and without one the email step fails with
  3951. PendingRollbackError; the prompt is the optional part, so it must not be
  3952. the reason the email never goes out.
  3953. """
  3954. try:
  3955. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3956. except Exception as e:
  3957. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3958. try:
  3959. await db.rollback()
  3960. except Exception:
  3961. pass
  3962. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  3963. """Who may answer a print's outcome prompt in the app: its owner and anyone
  3964. who may change everyone's archives. None (everyone on the printer) with auth
  3965. off, or for a print nobody owns."""
  3966. from sqlalchemy.orm import selectinload
  3967. from backend.app.core.auth import is_auth_enabled
  3968. from backend.app.core.permissions import Permission
  3969. from backend.app.models.user import User
  3970. if owner_id is None or not await is_auth_enabled(db):
  3971. return None
  3972. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  3973. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  3974. async def dispatch_outcome_confirmation(
  3975. db,
  3976. printer_id: int,
  3977. printer_name: str,
  3978. data: dict,
  3979. archive_id: int,
  3980. archive_data: dict | None = None,
  3981. ) -> bool:
  3982. """Emit the post-print outcome prompt for a completed archive (#1898).
  3983. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3984. queue item, or from ``confirm_outcome_external_prints`` for a print
  3985. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3986. question still open. Mints the per-archive capability token the one-tap
  3987. verdict links carry.
  3988. Lives here rather than inline in ``on_print_complete``'s notification task
  3989. because that task swallows every exception: extracted, the gate and the two
  3990. emissions can be driven by a test, which is the only thing standing between
  3991. a regression here and a farm that quietly stops asking.
  3992. Returns whether a prompt was sent.
  3993. """
  3994. logger = logging.getLogger(__name__)
  3995. from backend.app.models.archive import PrintArchive
  3996. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3997. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3998. return False
  3999. import secrets as _secrets
  4000. # A spent token stays on the row so the one-tap route can recognise it, so
  4001. # "has a token" no longer means "answerable". A prompt going out now needs a
  4002. # live one: mint a new token whenever the stored one is already spent, or
  4003. # every button in the new message would land on the already-answered page.
  4004. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  4005. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  4006. confirm_archive.confirm_token_used_at = None
  4007. await db.commit()
  4008. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4009. base = await get_external_base_url(db)
  4010. if not await get_setting(db, "external_url"):
  4011. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4012. # absolute URL, so an unconfigured install used to get a message body
  4013. # with two unusable relative paths and no buttons at all. The shared
  4014. # fallback at least produces tappable links; say which setting makes
  4015. # them resolve from a phone.
  4016. logger.warning(
  4017. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4018. "Set Settings → External URL so they resolve away from this host.",
  4019. base,
  4020. )
  4021. token = confirm_archive.confirm_token
  4022. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4023. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4024. confirm_url = f"{base}/archives?confirm={archive_id}"
  4025. await ws_manager.send_print_confirm_request(
  4026. printer_id,
  4027. {
  4028. "archive_id": archive_id,
  4029. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4030. },
  4031. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4032. )
  4033. await notification_service.on_print_confirm_request(
  4034. printer_id,
  4035. printer_name,
  4036. data,
  4037. db,
  4038. archive_data=archive_data,
  4039. good_url=good_url,
  4040. reject_url=reject_url,
  4041. confirm_url=confirm_url,
  4042. archive_id=archive_id,
  4043. )
  4044. return True
  4045. async def _printer_gone(db, printer_id: int) -> bool:
  4046. """Whether the printer was deleted. A column read: the session's loaded
  4047. Printer would otherwise answer for the database."""
  4048. from backend.app.models.printer import Printer
  4049. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4050. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4051. """Remove the archive just written if its printer was deleted meanwhile.
  4052. The delete route sweeps the printer's archives before it commits, so a row
  4053. committed after that sweep (the check before writing passed while the
  4054. delete was still uncommitted) is left for a printer that will never report
  4055. the print's end. A row the sweep reached is the route's: deleted with the
  4056. printer's archives, or detached (printer_id NULL) when the user kept them,
  4057. and then left as it is. Either way nothing is registered for it. Run after
  4058. the archive's commit, before anything is registered for it.
  4059. """
  4060. from backend.app.models.archive import PrintArchive
  4061. if not await _printer_gone(db, printer_id):
  4062. return False
  4063. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4064. if owner == printer_id:
  4065. logging.getLogger(__name__).info(
  4066. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4067. )
  4068. await ArchiveService(db).delete_archive(archive_id)
  4069. await forget_printer(printer_id)
  4070. return True
  4071. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4072. """After an IntegrityError on a print start's archive write: whether it was
  4073. the printer being deleted, forgotten then (the caller returns).
  4074. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4075. commit, so an archive written or adopted for it meanwhile (one that sets
  4076. printer_id) waits and the printer's foreign key then refuses it. That is
  4077. the printer being deleted, not an error; anything else is re-raised by the
  4078. caller.
  4079. """
  4080. await db.rollback()
  4081. if not await _printer_gone(db, printer_id):
  4082. return False
  4083. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4084. await forget_printer(printer_id)
  4085. return True
  4086. async def _forget_if_printer_gone(printer_id: int) -> None:
  4087. """At the end of a print start: the slow steps after the last check (smart
  4088. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4089. printer's delete and its forget_printer, and then wrote state back.
  4090. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4091. SQLite; PostgreSQL refuses it.)
  4092. Its own session: those steps can leave the handler's needing a rollback (a
  4093. write to the archive the delete removed). Never raises: it runs inside the
  4094. fallback branch's try, whose except reports the archive as failed.
  4095. """
  4096. try:
  4097. async with async_session() as db:
  4098. gone = await _printer_gone(db, printer_id)
  4099. if gone:
  4100. await forget_printer(printer_id)
  4101. except Exception:
  4102. logging.getLogger(__name__).warning(
  4103. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4104. )
  4105. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4106. """Tell the UI a plate check could not run. It does not block the print,
  4107. but an unchecked plate is not an empty one."""
  4108. try:
  4109. await ws_manager.broadcast(
  4110. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4111. )
  4112. except Exception as e:
  4113. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4114. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4115. """The ``_expected_prints`` keys a print start may be registered under."""
  4116. keys: list[tuple[int, str]] = []
  4117. if subtask_name:
  4118. keys.append((printer_id, subtask_name))
  4119. keys.append((printer_id, f"{subtask_name}.3mf"))
  4120. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4121. if filename:
  4122. fname = filename.split("/")[-1] if "/" in filename else filename
  4123. keys.append((printer_id, fname))
  4124. # Strip extensions to match
  4125. base = fname.replace(".gcode", "").replace(".3mf", "")
  4126. keys.append((printer_id, base))
  4127. keys.append((printer_id, f"{base}.3mf"))
  4128. return keys
  4129. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4130. """Whether this print start is one Bambuddy sent to the printer."""
  4131. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4132. return True
  4133. from backend.app.models.archive import PrintArchive
  4134. from backend.app.models.print_queue import PrintQueueItem
  4135. # The queue row the scheduler sets to printing before it sends -- but only
  4136. # when it was sent as this print: a row left printing by a run whose end
  4137. # was missed names another file.
  4138. dispatched_names = (
  4139. await db.execute(
  4140. select(PrintArchive.filename)
  4141. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4142. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4143. )
  4144. ).scalars()
  4145. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4146. return any(
  4147. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4148. for dispatched in dispatched_names
  4149. if dispatched
  4150. for seen in observed
  4151. )
  4152. async def on_print_start(printer_id: int, data: dict):
  4153. """Handle print start - archive the 3MF file immediately."""
  4154. logger = logging.getLogger(__name__)
  4155. # The print's start, before the 3MF download that the archive waits for
  4156. # (#3327): a minute of it would otherwise be missing from the print time.
  4157. detected_at = datetime.now(timezone.utc)
  4158. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4159. try:
  4160. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4161. except Exception:
  4162. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4163. # Clear any stale user-stopped flag from previous print cycles
  4164. _user_stopped_printers.discard(printer_id)
  4165. _kill_switch_stopped.discard(printer_id)
  4166. # A new print starts its milestones from zero (#3211). The status path only
  4167. # resets on progress below 5 while not printing, which a printer that goes
  4168. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4169. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4170. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4171. _last_progress_milestone[printer_id] = 0
  4172. _kill_switch_notification_tasks.pop(printer_id, None)
  4173. # #1721: drop any leftover pre-captured finish frame from a prior print
  4174. # so a never-consumed cache entry can't bleed into the new print's photo.
  4175. _stage22_finish_frames.pop(printer_id, None)
  4176. # #1867: same for the in-print frame bank — a queued print must not reuse
  4177. # the previous job's banked frame.
  4178. _inprint_frame_bank.pop(printer_id, None)
  4179. _inprint_frame_bank_ts.pop(printer_id, None)
  4180. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4181. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4182. # print's flag instead of inheriting it.
  4183. print_dispatch_context.adopt(printer_id)
  4184. # Cancel any active bed cooldown waiter for this printer
  4185. if _bed_cool_waiters.pop(printer_id, None):
  4186. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4187. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4188. from backend.app.api.routes.printers import clear_cover_cache
  4189. clear_cover_cache(printer_id)
  4190. await ws_manager.send_print_start(printer_id, data)
  4191. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4192. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4193. # MQTT relay - publish print start
  4194. try:
  4195. printer_info = printer_manager.get_printer(printer_id)
  4196. if printer_info:
  4197. await mqtt_relay.on_print_start(
  4198. printer_id,
  4199. printer_info.name,
  4200. printer_info.serial_number,
  4201. data.get("filename", ""),
  4202. data.get("subtask_name", ""),
  4203. )
  4204. except Exception:
  4205. pass # Don't fail print start callback if MQTT fails
  4206. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4207. # and mapping, and the seeded tray-change log.
  4208. #
  4209. # Unconditional, for both inventory backends. This only *captures* — the
  4210. # writing is still split, with the internal tracker skipped at completion
  4211. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4212. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4213. # tray-change log, and that log is the only record of which spool fed
  4214. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4215. # it on one side only would leave Spoolman users with the mid-print
  4216. # restart bug this fixes for everyone else.
  4217. try:
  4218. async with async_session() as db:
  4219. from backend.app.api.routes.settings import get_setting
  4220. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4221. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4222. await usage_on_print_start(
  4223. printer_id,
  4224. data,
  4225. printer_manager,
  4226. db=db,
  4227. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4228. )
  4229. except Exception as e:
  4230. logger.warning("Usage tracker on_print_start failed: %s", e)
  4231. # Track if notification was sent (to avoid sending twice)
  4232. notification_sent = False
  4233. # Smart plug automation: turn on plug when print starts
  4234. try:
  4235. async with async_session() as db:
  4236. await smart_plug_manager.on_print_start(printer_id, db)
  4237. except Exception as e:
  4238. logger.warning("Smart plug on_print_start failed: %s", e)
  4239. async with async_session() as db:
  4240. from backend.app.models.printer import Printer
  4241. from backend.app.services.bambu_ftp import list_files_async
  4242. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4243. printer = result.scalar_one_or_none()
  4244. # Plate detection check - pause if objects detected on build plate
  4245. logger.info(
  4246. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4247. )
  4248. if printer and printer.plate_detection_enabled:
  4249. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4250. # Release the pooled DB connection before the plate-detection camera
  4251. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4252. # printer SELECT has run so far — nothing to persist — so this commit
  4253. # is a data-noop that ends the read transaction and returns the
  4254. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4255. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4256. # archive lookups below re-acquire a fresh connection on next execute.
  4257. await db.commit()
  4258. try:
  4259. from backend.app.services.plate_detection import check_plate_empty
  4260. # Build ROI tuple from printer settings if available
  4261. roi = None
  4262. if all(
  4263. [
  4264. printer.plate_detection_roi_x is not None,
  4265. printer.plate_detection_roi_y is not None,
  4266. printer.plate_detection_roi_w is not None,
  4267. printer.plate_detection_roi_h is not None,
  4268. ]
  4269. ):
  4270. roi = (
  4271. printer.plate_detection_roi_x,
  4272. printer.plate_detection_roi_y,
  4273. printer.plate_detection_roi_w,
  4274. printer.plate_detection_roi_h,
  4275. )
  4276. # The light is held, not switched, so a live view opened
  4277. # meanwhile keeps it when the check lets go (SP-C11). Every
  4278. # printer, whatever the camera light mode: detection needs it.
  4279. plate_photo_data = None
  4280. objects_detected = False
  4281. check_failure: str | None = None
  4282. async with camera_light(printer, any_mode=True, settle=2.5):
  4283. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4284. plate_result = await check_plate_empty(
  4285. printer_id=printer_id,
  4286. ip_address=printer.ip_address,
  4287. access_code=printer.access_code,
  4288. model=printer.model,
  4289. include_debug_image=False,
  4290. external_camera_url=printer.external_camera_url,
  4291. external_camera_type=printer.external_camera_type,
  4292. use_external=printer.external_camera_enabled,
  4293. roi=roi,
  4294. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4295. )
  4296. # No reference to compare against is a check that did not
  4297. # run either: say so rather than call the plate empty.
  4298. check_failure = getattr(plate_result, "failure_reason", None) or (
  4299. "not_calibrated" if plate_result.needs_calibration else None
  4300. )
  4301. objects_detected = not check_failure and not plate_result.is_empty
  4302. if objects_detected:
  4303. # Objects detected - pause the print!
  4304. logger.warning(
  4305. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4306. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4307. )
  4308. pause_client = printer_manager.get_client(printer_id)
  4309. if pause_client:
  4310. pause_client.pause_print()
  4311. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4312. # Snapshot while the light's still on — restoring it first
  4313. # would leave the notification with a dark photo.
  4314. try:
  4315. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4316. except Exception as snap_err:
  4317. logger.warning(
  4318. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4319. )
  4320. if objects_detected:
  4321. # Send notification about plate not empty
  4322. await ws_manager.broadcast(
  4323. {
  4324. "type": "plate_not_empty",
  4325. "printer_id": printer_id,
  4326. "printer_name": printer.name,
  4327. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4328. }
  4329. )
  4330. # Also send push notification
  4331. try:
  4332. await notification_service.on_plate_not_empty(
  4333. printer_id=printer_id,
  4334. printer_name=printer.name,
  4335. db=db,
  4336. difference_percent=plate_result.difference_percent,
  4337. image_data=plate_photo_data,
  4338. )
  4339. except Exception as notif_err:
  4340. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4341. elif check_failure:
  4342. logger.warning(
  4343. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4344. printer_id,
  4345. check_failure,
  4346. plate_result.message,
  4347. )
  4348. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4349. else:
  4350. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4351. except Exception as plate_err:
  4352. # Don't block print on plate detection errors
  4353. logger.warning(
  4354. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4355. printer_id,
  4356. plate_err,
  4357. )
  4358. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4359. if not printer:
  4360. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4361. if not notification_sent:
  4362. await _send_print_start_notification(printer_id, data, logger=logger)
  4363. return
  4364. # Skip the printer's own jobs — a calibration run is not a user's print.
  4365. # See is_internal_printer_job for what counts and why both fields are
  4366. # tested; the pressure-advance line reports as a subtask name with no
  4367. # /usr/ path, which the old prefix-only test here missed entirely.
  4368. #
  4369. # No notification either. The event describes the printer calibrating
  4370. # itself, so "Print started" is as wrong as the archive was, and the
  4371. # matching completion is suppressed in on_print_complete for the same
  4372. # reason. Checked before the auto-archive switches, whose "off" path
  4373. # still notifies.
  4374. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4375. # print Bambuddy dispatched is never one, whatever it is called.
  4376. # Dispatched = an expected print, or, after a restart that lost those,
  4377. # a queue job printing on the printer.
  4378. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4379. (data.get("filename") or "").startswith("/usr/")
  4380. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4381. ):
  4382. logger.info(
  4383. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4384. data.get("filename", ""),
  4385. data.get("subtask_name", ""),
  4386. )
  4387. return
  4388. # The global switch is the master: off, no printer archives prints
  4389. # started outside Bambuddy; on, each printer's own switch decides.
  4390. from backend.app.api.routes.settings import get_setting
  4391. _global_auto_archive = await get_setting(db, "auto_archive")
  4392. archives_prints = printer.auto_archive and (
  4393. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4394. )
  4395. if not archives_prints:
  4396. # auto-archive disabled — check if there's an expected print (dispatched
  4397. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4398. # If so, fall through to the expected-print handling below so the archive
  4399. # is tracked in _active_prints and usage tracking works at completion.
  4400. _fn = data.get("filename", "")
  4401. _sn = data.get("subtask_name", "")
  4402. _check_keys: list[tuple[int, str]] = []
  4403. if _sn:
  4404. _check_keys += [
  4405. (printer_id, _sn),
  4406. (printer_id, f"{_sn}.3mf"),
  4407. (printer_id, f"{_sn}.gcode.3mf"),
  4408. ]
  4409. if _fn:
  4410. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4411. _check_keys.append((printer_id, _base_fn))
  4412. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4413. _check_keys += [
  4414. (printer_id, _no_archive_base),
  4415. (printer_id, f"{_no_archive_base}.3mf"),
  4416. ]
  4417. _has_expected = any(k in _expected_prints for k in _check_keys)
  4418. if not _has_expected:
  4419. # No expected print — truly external print (started from slicer/touchscreen)
  4420. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4421. if not notification_sent:
  4422. _no_archive_creator: int | None = None
  4423. for _key in _check_keys:
  4424. _expected_prints.pop(_key, None)
  4425. _expected_print_registered_at.pop(_key, None)
  4426. popped_creator = _expected_print_creators.pop(_key, None)
  4427. if _no_archive_creator is None:
  4428. _no_archive_creator = popped_creator
  4429. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4430. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4431. return
  4432. else:
  4433. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4434. # Get the filename and subtask_name
  4435. filename = data.get("filename", "")
  4436. subtask_name = data.get("subtask_name", "")
  4437. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4438. # present, it lets us match an archive across a backend restart (#972):
  4439. # same id → same print → resume the existing row instead of cancelling
  4440. # it and recreating from scratch (which loses started_at). Treat "0"
  4441. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4442. raw_mqtt = data.get("raw_data") or {}
  4443. subtask_id = raw_mqtt.get("subtask_id")
  4444. if subtask_id is not None:
  4445. subtask_id = str(subtask_id).strip()
  4446. if subtask_id in ("", "0"):
  4447. subtask_id = None
  4448. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4449. if not filename and not subtask_name:
  4450. # Send notification without archive data (no filename)
  4451. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4452. if not notification_sent:
  4453. await _send_print_start_notification(printer_id, data, logger=logger)
  4454. return
  4455. # Check if this is an expected print from reprint/scheduled
  4456. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4457. expected_archive_id = None
  4458. # Who queued it, taken with the entries it was registered beside: left
  4459. # behind once those are gone (the archive deleted mid-dispatch, or the
  4460. # start notification already sent), the expiry never saw it, and an
  4461. # unrelated later print of that name was attributed to that user (EP-2).
  4462. fallback_creator = None
  4463. for key in expected_keys:
  4464. expected_archive_id = _expected_prints.pop(key, None)
  4465. _expected_print_registered_at.pop(key, None)
  4466. if expected_archive_id:
  4467. # Clean up other possible keys for this print
  4468. for other_key in expected_keys:
  4469. _expected_prints.pop(other_key, None)
  4470. _expected_print_registered_at.pop(other_key, None)
  4471. creator = _expected_print_creators.pop(other_key, None)
  4472. if fallback_creator is None:
  4473. fallback_creator = creator
  4474. break
  4475. if expected_archive_id:
  4476. # This is a reprint/scheduled print - use existing archive, don't create new one
  4477. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4478. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4479. # Bambuddy's once the expected entry is consumed here.
  4480. _owned_print_archive_ids.add(expected_archive_id)
  4481. from backend.app.models.archive import PrintArchive
  4482. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4483. archive = result.scalar_one_or_none()
  4484. # Deleted after this handler loaded it (the plate check waits
  4485. # seconds) but before the route forgot the expected print: the
  4486. # archive the route kept or deleted is left as the route left it.
  4487. if archive and await _printer_gone(db, printer_id):
  4488. logger.info(
  4489. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4490. )
  4491. await forget_printer(printer_id)
  4492. return
  4493. if archive:
  4494. # As it was before this adoption: put back if the printer turns
  4495. # out to have been deleted while it was adopted (below).
  4496. before_adoption = {
  4497. attr.columns[0].name: getattr(archive, attr.key)
  4498. for attr in sa_inspect(PrintArchive).column_attrs
  4499. if attr.key != "id"
  4500. }
  4501. # Update archive status to printing
  4502. archive.status = "printing"
  4503. archive.started_at = datetime.now(timezone.utc)
  4504. # The previous run's outcome is not this one's: a reprint that
  4505. # completes must not keep showing why the last one failed.
  4506. archive.failure_reason = None
  4507. archive.completed_at = None
  4508. # The previous run's answer is still on this row and the
  4509. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4510. # so without a reset the second run inherits the first run's
  4511. # verdict: no prompt at all, and a green "good" badge on a run
  4512. # nobody ever judged.
  4513. if archive.confirm_requested:
  4514. archive.user_verdict = None
  4515. archive.user_verdict_source = None
  4516. archive.user_verdict_at = None
  4517. archive.confirm_token = None
  4518. archive.confirm_token_used_at = None
  4519. # Reprint of an archive reuses the source row. Without resetting
  4520. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4521. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4522. # extracts the *original* print's last frame, which then ships in
  4523. # the completion notification (#1707). Clear the path so the
  4524. # scanner runs fresh; also unlink the old video file so reprints
  4525. # don't accumulate orphans in the archive directory. Photos list
  4526. # is left alone — accumulating one finish photo per run is fine.
  4527. # The print-start baseline (#2704) is stale for the same reason:
  4528. # it describes the printer before the previous run. The capture
  4529. # below overwrites it, but clear it here too so an early failure
  4530. # can't leave the scan diffing against the wrong snapshot.
  4531. #
  4532. # Unlinked only when it is the same plate printing again. Every
  4533. # plate of a Send All shares this archive, and the video on it
  4534. # can be the only copy of another plate's run -- the printer's
  4535. # was deleted once it attached (#3275). That one is left in the
  4536. # archive directory, which goes with the archive. A video whose
  4537. # plate is not on record (attached by hand, or before the
  4538. # column existed) is kept too where the 3MF has other plates,
  4539. # or cannot be read: nothing tells it apart from another plate's,
  4540. # and keeping costs one file where deleting can cost the only
  4541. # copy. On an archive with exactly one plate it is that plate's.
  4542. archive.timelapse_baseline = None
  4543. stale_timelapse_relpath = archive.timelapse_path
  4544. stale_timelapse_plate_id = archive.timelapse_plate_id
  4545. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4546. if stale_timelapse_relpath:
  4547. archive.timelapse_path = None
  4548. archive.timelapse_plate_id = None
  4549. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4550. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4551. from backend.app.services.archive import plate_indexes_in_3mf
  4552. plates = await asyncio.to_thread(
  4553. plate_indexes_in_3mf,
  4554. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4555. )
  4556. stale_is_this_plates = len(plates) == 1
  4557. if stale_timelapse_relpath and not stale_is_this_plates:
  4558. logger.info(
  4559. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4560. stale_timelapse_relpath,
  4561. stale_timelapse_plate_id,
  4562. expected_archive_id,
  4563. starting_plate_id,
  4564. )
  4565. # The video is deleted once the adoption stands (below).
  4566. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4567. # Persist a restart-stable id so a later restart resumes this
  4568. # archive by subtask_id instead of name-matching + duplicating
  4569. # it (#1485). The printer often hasn't echoed subtask_id back
  4570. # this soon after dispatch, so fall back to the id Bambuddy
  4571. # minted when it sent the print command. Scoped to this
  4572. # expected-print branch on purpose: an expected match means
  4573. # Bambuddy dispatched this exact print in this process, so the
  4574. # client's last-dispatch id genuinely belongs to it — using it
  4575. # for an externally-started print could mis-tag the archive.
  4576. effective_subtask_id = subtask_id
  4577. if not effective_subtask_id:
  4578. _client = printer_manager.get_client(printer_id)
  4579. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4580. if _dispatched:
  4581. effective_subtask_id = str(_dispatched).strip() or None
  4582. # Update on first-set OR on reprint (the queue dispatcher mints
  4583. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4584. # the rewrite for reprints leaves the archive holding the FIRST
  4585. # run's id; if MQTT then reconnects mid-print, the reconciler
  4586. # (#1542) compares the stale stored id against the printer's
  4587. # live id, sees a mismatch, and synthesises a bogus PRINT
  4588. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4589. # in #1807. Inequality check preserves the noop-on-stable-push
  4590. # behaviour the earlier `not archive.subtask_id` guard provided.
  4591. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4592. archive.subtask_id = effective_subtask_id
  4593. # #1403 follow-up: VP-queue archives are created with
  4594. # printer_id=None at queue-add time (we don't know which
  4595. # printer will run the job yet). When the print actually
  4596. # starts on a specific printer the expected-archive lookup
  4597. # used to skip this assignment, leaving printer_id=None
  4598. # forever — which then disables the "Scan for timelapse"
  4599. # button in ArchivesPage (gated on !archive.printer_id).
  4600. if archive.printer_id != printer_id:
  4601. archive.printer_id = printer_id
  4602. adopting_id = archive.id # a rollback expires the object
  4603. try:
  4604. await db.commit()
  4605. except (IntegrityError, StaleDataError):
  4606. # The archive stays unchanged, or is gone: "delete archives"
  4607. # removed the row under the adoption, which then matched no
  4608. # row (StaleDataError) rather than being refused.
  4609. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4610. return
  4611. raise
  4612. # The printer can be deleted between the check above and this
  4613. # commit (the route's transaction lasts seconds), and the commit
  4614. # then adopted the archive anyway: status, verdict and timelapse
  4615. # changed, and the deleted printer's id written on a row the
  4616. # route had detached or never touched. Undo the adoption.
  4617. if await _printer_gone(db, printer_id):
  4618. logger.info(
  4619. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4620. printer_id,
  4621. archive.id,
  4622. )
  4623. # Everything as before this adoption. The printer it had
  4624. # then stays, unless it was the deleted one: the route
  4625. # detached that row (kept) or deleted it (no row matches).
  4626. previous_printer = before_adoption["printer_id"]
  4627. await db.execute(
  4628. update(PrintArchive)
  4629. .where(PrintArchive.id == archive.id)
  4630. .values(
  4631. {
  4632. **before_adoption,
  4633. "printer_id": None if previous_printer == printer_id else previous_printer,
  4634. }
  4635. )
  4636. )
  4637. await db.commit()
  4638. await forget_printer(printer_id)
  4639. return
  4640. if delete_stale_video and stale_timelapse_relpath:
  4641. try:
  4642. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4643. if stale_path.is_file():
  4644. stale_path.unlink()
  4645. logger.info(
  4646. "Deleted stale timelapse %s on reprint of archive %s",
  4647. stale_timelapse_relpath,
  4648. expected_archive_id,
  4649. )
  4650. except OSError as e:
  4651. logger.warning(
  4652. "Failed to delete stale timelapse %s on reprint: %s",
  4653. stale_timelapse_relpath,
  4654. e,
  4655. )
  4656. # Track as active print
  4657. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4658. await _open_run_for(archive.id, printer_id)
  4659. # Start timelapse session if external camera is enabled (#1353).
  4660. # Queue / VP-dispatched prints land here in the expected-archive
  4661. # branch and used to skip start_session entirely — frames were
  4662. # never captured and the post-print stitch silently returned None.
  4663. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4664. # Inject ams_mapping into usage tracker session — the session was created
  4665. # before expected-print promotion, so it may have ams_mapping=None when
  4666. # the MQTT request topic subscription failed (common on P1S/A1).
  4667. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4668. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4669. if _stored_map or _stored_plate_id is not None:
  4670. try:
  4671. from backend.app.services.usage_tracker import _active_sessions
  4672. _ut_session = _active_sessions.get(printer_id)
  4673. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4674. _ut_session.ams_mapping = _stored_map
  4675. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4676. # plate_id injection covers direct-Print of plate N of a multi-plate
  4677. # 3MF — queue prints already capture it via the on_print_start queue
  4678. # lookup, but direct-Print never goes through the queue (#1697).
  4679. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4680. _ut_session.plate_id = _stored_plate_id
  4681. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4682. except Exception:
  4683. pass
  4684. # Set up energy tracking (#941: persist start on archive row)
  4685. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4686. await ws_manager.send_archive_updated(
  4687. {
  4688. "id": archive.id,
  4689. "status": "printing",
  4690. }
  4691. )
  4692. # Send notification with archive data (reprint/scheduled)
  4693. if not notification_sent:
  4694. # Use archive's created_by_id; fall back to the creator registered via
  4695. # register_expected_print (handles library-file-based queue items where
  4696. # the freshly-created archive has no created_by_id yet), taken above.
  4697. archive_data = {
  4698. "print_time_seconds": archive.print_time_seconds,
  4699. "created_by_id": archive.created_by_id or fallback_creator,
  4700. }
  4701. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4702. # Extract printable objects from the archived 3MF file
  4703. _load_objects_from_archive(archive, printer_id, logger)
  4704. if archive.file_path:
  4705. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4706. # Store Spoolman tracking data for per-filament usage reporting
  4707. try:
  4708. await _store_spoolman_print_data(
  4709. printer_id,
  4710. archive.id,
  4711. archive.file_path,
  4712. db,
  4713. printer_manager,
  4714. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4715. plate_id=_get_start_plate_id(archive.id),
  4716. )
  4717. except Exception as e:
  4718. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4719. # Price the print from its spools now rather than only at completion (#3261)
  4720. _schedule_archive_cost_estimate(
  4721. printer_id,
  4722. archive.id,
  4723. printer_manager,
  4724. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4725. plate_id=_get_start_plate_id(archive.id),
  4726. session_factory=async_session,
  4727. )
  4728. # Capture timelapse file baseline for snapshot-diff on completion
  4729. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4730. # hit this branch — without the baseline the completion-time scan
  4731. # falls into its "take baseline now" fallback, which snapshots
  4732. # AFTER the new MP4 already exists and never matches a diff
  4733. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4734. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4735. await _forget_if_printer_gone(printer_id)
  4736. return # Skip creating a new archive
  4737. # The archive was deleted after the job was queued.
  4738. if not archives_prints:
  4739. # Only the expected print brought a printer that does not
  4740. # archive this far; with it gone, nothing is archived.
  4741. return
  4742. # Otherwise archive the print anew rather than drop it, so it still
  4743. # gets its notification, usage tracking and history.
  4744. logger.warning(
  4745. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4746. expected_archive_id,
  4747. printer_id,
  4748. )
  4749. # Check if there's already a "printing" archive for this printer/file
  4750. # This prevents duplicates when backend restarts during an active print
  4751. from backend.app.models.archive import PrintArchive
  4752. existing_archive: PrintArchive | None = None
  4753. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4754. # across a backend restart for the same print, so this is the most
  4755. # reliable way to reattach. Only a row still printing: a cancelled one
  4756. # has been through completion (usage, history, notifications) already,
  4757. # and reopening it would count the print twice.
  4758. if subtask_id:
  4759. by_id = await db.execute(
  4760. select(PrintArchive)
  4761. .where(PrintArchive.printer_id == printer_id)
  4762. .where(PrintArchive.subtask_id == subtask_id)
  4763. .where(PrintArchive.status == "printing")
  4764. .order_by(PrintArchive.created_at.desc())
  4765. .limit(1)
  4766. )
  4767. existing_archive = by_id.scalar_one_or_none()
  4768. # Fallback match: name-based lookup. Kept as-is for prints whose
  4769. # subtask_id is missing ("0" / local / non-cloud prints).
  4770. if existing_archive is None:
  4771. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4772. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4773. # A print started from the printer's screen names its file in full,
  4774. # so the forms above double its extension. The file itself is the
  4775. # one exact match, and nothing looser is added (#3009).
  4776. if _subtask_is_the_file(subtask_name, filename):
  4777. archive_filenames.append(subtask_name)
  4778. existing = await db.execute(
  4779. select(PrintArchive)
  4780. .where(PrintArchive.printer_id == printer_id)
  4781. .where(PrintArchive.status == "printing")
  4782. .where(
  4783. or_(
  4784. PrintArchive.print_name == check_name,
  4785. PrintArchive.filename.in_(archive_filenames),
  4786. )
  4787. )
  4788. .order_by(PrintArchive.created_at.desc())
  4789. .limit(1)
  4790. )
  4791. existing_archive = existing.scalar_one_or_none()
  4792. if existing_archive:
  4793. # subtask_id match → always resume, regardless of age. Same print,
  4794. # just a backend restart.
  4795. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4796. if subtask_match:
  4797. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4798. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4799. await _open_run_for(existing_archive.id, printer_id)
  4800. _mark_owned_if_dispatched(existing_archive)
  4801. if existing_archive.energy_start_kwh is None:
  4802. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4803. if not notification_sent:
  4804. archive_data = {
  4805. "print_time_seconds": existing_archive.print_time_seconds,
  4806. "created_by_id": existing_archive.created_by_id,
  4807. }
  4808. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4809. _load_objects_from_archive(existing_archive, printer_id, logger)
  4810. if existing_archive.file_path:
  4811. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4812. return
  4813. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4814. # stale from the printer's *current* progress, not wall-clock age.
  4815. # A genuinely long print used to trip a blind 4h cutoff and have its
  4816. # live archive cancelled + duplicated on every backend restart
  4817. # (#1485). If the printer reports real progress, this name-matched
  4818. # 'printing' archive IS that ongoing print — resume it whatever its
  4819. # age. Only treat it as a stale leftover when the printer clearly
  4820. # shows a different, freshly-started print: near-0% progress on an
  4821. # archive far too old to still be at 0%. Unknown progress (printer
  4822. # not connected) never cancels — resuming is the safe default.
  4823. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4824. live_status = printer_manager.get_status(printer_id)
  4825. live_progress = getattr(live_status, "progress", None) if live_status else None
  4826. looks_stale = (
  4827. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4828. )
  4829. # Two subtask ids are two prints, however young the archive: one
  4830. # whose completion was missed must not swallow the next print of
  4831. # the same file. Except Bambuddy's own reprint, which reuses the
  4832. # row and mints a fresh id (#1807): the id it last sent says so,
  4833. # and after a restart, which forgets it, this printer's queue job
  4834. # running the archive.
  4835. if (
  4836. not looks_stale
  4837. and subtask_id
  4838. and existing_archive.subtask_id
  4839. and existing_archive.subtask_id != subtask_id
  4840. ):
  4841. _client = printer_manager.get_client(printer_id)
  4842. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4843. if _dispatched:
  4844. looks_stale = _dispatched != subtask_id
  4845. else:
  4846. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4847. queue_run = await db.scalar(
  4848. select(_PQI.id)
  4849. .where(_PQI.archive_id == existing_archive.id)
  4850. .where(_PQI.printer_id == printer_id)
  4851. .where(_PQI.status == "printing")
  4852. .limit(1)
  4853. )
  4854. looks_stale = queue_run is None
  4855. if looks_stale:
  4856. logger.warning(
  4857. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4858. " — marking cancelled and creating new archive",
  4859. existing_archive.id,
  4860. archive_age,
  4861. live_progress,
  4862. existing_archive.subtask_id,
  4863. subtask_id,
  4864. )
  4865. existing_archive.status = "cancelled"
  4866. # Canonical key, not a sentence (issue #2974). "No status update
  4867. # received" is what both stale paths actually observed; which of
  4868. # the two it was is already carried by ``status`` -- cancelled
  4869. # here, the reconciled outcome at the reconnect site -- so one
  4870. # key loses no information and gives the Statistics breakdown a
  4871. # single bucket instead of two untranslatable prose strings.
  4872. existing_archive.failure_reason = "noStatusUpdate"
  4873. await db.commit()
  4874. # Its print keys go with it; the new archive registers its own.
  4875. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4876. del _active_prints[_key]
  4877. # Fall through to create new archive (don't return)
  4878. else:
  4879. logger.info(
  4880. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4881. )
  4882. # Track this as the active print
  4883. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4884. _mark_owned_if_dispatched(existing_archive)
  4885. # Attach subtask_id retroactively so future restarts can resume.
  4886. # Compare for inequality (not "is empty") to also pick up reprint
  4887. # dispatches that mint a fresh id — see #1807 for the bogus
  4888. # "Print Stopped" the strict-empty guard caused on reconnect.
  4889. if subtask_id and existing_archive.subtask_id != subtask_id:
  4890. existing_archive.subtask_id = subtask_id
  4891. await db.commit()
  4892. await _open_run_for(existing_archive.id, printer_id)
  4893. # Also set up energy tracking if not already tracked (#941: persisted column)
  4894. if existing_archive.energy_start_kwh is None:
  4895. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4896. # Send notification with archive data (existing archive)
  4897. if not notification_sent:
  4898. archive_data = {
  4899. "print_time_seconds": existing_archive.print_time_seconds,
  4900. "created_by_id": existing_archive.created_by_id,
  4901. }
  4902. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4903. # Extract printable objects from the archived 3MF file
  4904. _load_objects_from_archive(existing_archive, printer_id, logger)
  4905. if existing_archive.file_path:
  4906. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4907. return
  4908. # Build list of possible 3MF filenames to try
  4909. possible_names = []
  4910. # Bambu printers typically store files as "Name.gcode.3mf"
  4911. # The subtask_name is usually the best source for the filename
  4912. if subtask_name:
  4913. if _subtask_is_the_file(subtask_name, filename):
  4914. # A print started from the printer's own screen reports the
  4915. # file's full name, extension included. That is the file, so
  4916. # no extension is appended to it (#3009).
  4917. possible_names.append(subtask_name)
  4918. else:
  4919. # Try common Bambu naming patterns
  4920. possible_names.append(f"{subtask_name}.gcode.3mf")
  4921. possible_names.append(f"{subtask_name}.3mf")
  4922. # Try original filename with .3mf extension
  4923. if filename:
  4924. # Extract just the filename part, not the full path
  4925. fname = filename.split("/")[-1] if "/" in filename else filename
  4926. if fname.endswith(".3mf"):
  4927. possible_names.append(fname)
  4928. elif fname.endswith(".gcode"):
  4929. base = fname.rsplit(".", 1)[0]
  4930. possible_names.append(f"{base}.gcode.3mf")
  4931. possible_names.append(f"{base}.3mf")
  4932. else:
  4933. possible_names.append(f"{fname}.gcode.3mf")
  4934. possible_names.append(f"{fname}.3mf")
  4935. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4936. space_variants = []
  4937. for name in possible_names:
  4938. if " " in name:
  4939. space_variants.append(name.replace(" ", "_"))
  4940. possible_names.extend(space_variants)
  4941. # Remove duplicates while preserving order
  4942. seen = set()
  4943. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4944. logger.info("Trying filenames: %s", possible_names)
  4945. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4946. # here means none of the expected-/existing-archive write branches ran
  4947. # (they all return earlier) — only SELECTs have executed on this path, so
  4948. # this commit persists nothing; it ends the read transaction so the
  4949. # connection returns to the pool during the download. That download tries
  4950. # up to five remote paths per candidate filename with retry/backoff and
  4951. # can run for minutes under FTP contention; holding the session across it
  4952. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4953. # work runs during the download — the new-archive writes below re-acquire
  4954. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4955. await db.commit()
  4956. # Try to find and download the 3MF file
  4957. temp_path = None
  4958. downloaded_filename = None
  4959. # Cache check: cover endpoint may have already pulled this 3MF during
  4960. # the print (frontend opens the card and shows the thumbnail) — reuse
  4961. # that file instead of re-downloading 36MB over the same FTP link that
  4962. # just served it (#972). The cache keys on a normalized filename so
  4963. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4964. for try_filename in possible_names:
  4965. if not try_filename.endswith(".3mf"):
  4966. continue
  4967. cached = get_cached_3mf(printer_id, try_filename)
  4968. if cached:
  4969. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4970. temp_path = cached
  4971. downloaded_filename = try_filename
  4972. break
  4973. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4974. # H2-series and P2S the answer is routinely no — the file stays on
  4975. # internal eMMC and port 990 only ever serves external storage — and
  4976. # then the whole sweep below (six filenames x five directories x four
  4977. # retries, then the directory walk) is ~110 connections that cannot
  4978. # succeed. Skip it and say why (#2780).
  4979. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4980. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4981. # running rather than because the file is somewhere unreachable. The
  4982. # distinction is the whole of #2957: one is permanent, the other clears
  4983. # in minutes with the file still sitting on the printer.
  4984. blocked_by_ftps_cooloff = False
  4985. # Set when a probe reached the printer and still came back without the
  4986. # file -- a timeout mid-transfer, a refused connection, anything that is
  4987. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4988. # caught by name below, so a file that genuinely is not on the card
  4989. # leaves this False and schedules nothing. Anything else means the
  4990. # transfer, not the file, is what failed, and that does not last (#3063).
  4991. ftp_transfer_failed = False
  4992. # The narrower case of the above: the directory walk *listed* a file
  4993. # for this print and could not fetch it, so the file is on the card
  4994. # under a name that matches. The only failure that rules out an
  4995. # earlier run's 3MF standing in for it (#3307).
  4996. walk_transfer_failed = False
  4997. # Paths the sweep reached and could not transfer -- a timeout, not a
  4998. # 550. The directory walk lists the same folders and would download
  4999. # the same file again: on a slow A1 that was a second 300 s on the
  5000. # printer's one FTPS slot, at print start, for a file the recovery
  5001. # retry fetches with a deadline twice as long (#3308).
  5002. sweep_failed_paths: set[str] = set()
  5003. # The print's name, for a fallback archive whose `subtask_name` the
  5004. # plate guard below had to disown. Display only, and deliberately kept
  5005. # apart from `subtask_name`: that variable is what every file lookup
  5006. # here is built from, and once a name has been shown to fetch another
  5007. # plate's 3MF it must not key `_active_prints` either, or the cover
  5008. # endpoint hands the same contradicted file to
  5009. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5010. display_name_after_plate_reject: str | None = None
  5011. # Get FTP retry settings
  5012. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5013. # ...but "the printer put it on eMMC" is where it went, not whether we
  5014. # can read it. An H2D with a card in mirrors the job to /cache and
  5015. # serves it happily, and skipping on the URL alone cost that reporter
  5016. # every archive for two days (#2856). So ask the printer instead of
  5017. # guessing: the dispatch named the exact file, which is one connection
  5018. # walking five paths rather than the sweep's ~110. Only when the probe
  5019. # comes back empty does the verdict's reason stand.
  5020. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5021. if ftps_handshake_blocked(printer.ip_address):
  5022. # Deliberately NOT recorded as a cool-off give-up. This branch
  5023. # only runs on an unreachable verdict, and that verdict is the
  5024. # honest, permanent reason the archive is empty — the probe was
  5025. # a long shot on top of it. Blaming the cool-off here would
  5026. # schedule a retry for a file sitting on internal eMMC, which is
  5027. # the sweep #2780 removed (#2957).
  5028. logger.debug(
  5029. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5030. storage.probe_filename,
  5031. printer_id,
  5032. )
  5033. else:
  5034. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5035. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5036. try:
  5037. probe_hit = await download_file_try_paths_async(
  5038. printer.ip_address,
  5039. printer.access_code,
  5040. ftp_probe_paths(storage.probe_filename),
  5041. probe_path,
  5042. socket_timeout=ftp_timeout,
  5043. printer_model=printer.model,
  5044. )
  5045. except Exception as e:
  5046. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5047. probe_hit = False
  5048. if probe_hit:
  5049. downloaded_filename = storage.probe_filename
  5050. temp_path = probe_path
  5051. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5052. # Naming the path, not just the file: a printer that keeps
  5053. # uploads around for weeks can serve a same-named copy of an
  5054. # earlier slice, and without the directory in the log that
  5055. # mismatch is invisible rather than merely rare (#1820).
  5056. logger.info(
  5057. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5058. downloaded_filename,
  5059. probe_hit,
  5060. printer_id,
  5061. storage.reason,
  5062. )
  5063. if not storage.reachable and not downloaded_filename:
  5064. # Same opening words whether or not a probe ran, because that is
  5065. # the phrase support asks people to grep for — only the tail says
  5066. # which of the two happened.
  5067. logger.info(
  5068. "Skipping the 3MF lookup for printer %s: %s — %s",
  5069. printer_id,
  5070. storage.reason,
  5071. "no copy of it on external storage either"
  5072. if storage.probe_filename
  5073. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5074. )
  5075. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5076. if not try_filename.endswith(".3mf"):
  5077. continue
  5078. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5079. # printers, so try it first — deferring it to last cost #972's reporter
  5080. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5081. # landing on the path that actually had the file.
  5082. remote_paths = [
  5083. f"/{try_filename}",
  5084. f"/cache/{try_filename}",
  5085. f"/model/{try_filename}",
  5086. f"/data/{try_filename}",
  5087. f"/data/Metadata/{try_filename}",
  5088. ]
  5089. temp_path = app_settings.archive_dir / "temp" / try_filename
  5090. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5091. for remote_path in remote_paths:
  5092. if ftps_handshake_blocked(printer.ip_address):
  5093. # The printer's FTPS service is not completing a TLS
  5094. # handshake, so it has no path we could reach — walking the
  5095. # remaining candidates only re-runs the same failure
  5096. # (#2780). Fall through to the no-3MF archive now.
  5097. #
  5098. # Remember *why*, though. This is the one give-up that is
  5099. # temporary: the cool-off clears in minutes and the file was
  5100. # on the printer the whole time. The fallback archive is
  5101. # stamped with it so a retry can be scheduled, and so the
  5102. # Archives banner stops blaming storage (#2957).
  5103. blocked_by_ftps_cooloff = True
  5104. logger.warning(
  5105. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5106. printer_id,
  5107. )
  5108. break
  5109. logger.debug("Trying FTP download: %s", remote_path)
  5110. try:
  5111. if ftp_retry_enabled:
  5112. downloaded = await with_ftp_retry(
  5113. download_file_async,
  5114. printer.ip_address,
  5115. printer.access_code,
  5116. remote_path,
  5117. temp_path,
  5118. timeout=ftp_timeout,
  5119. socket_timeout=ftp_timeout,
  5120. printer_model=printer.model,
  5121. max_retries=ftp_retry_count,
  5122. retry_delay=ftp_retry_delay,
  5123. operation_name=f"Download 3MF from {remote_path}",
  5124. cooloff_ip=printer.ip_address,
  5125. non_retry_exceptions=(FileNotOnPrinterError,),
  5126. )
  5127. else:
  5128. downloaded = await download_file_async(
  5129. printer.ip_address,
  5130. printer.access_code,
  5131. remote_path,
  5132. temp_path,
  5133. timeout=ftp_timeout,
  5134. socket_timeout=ftp_timeout,
  5135. printer_model=printer.model,
  5136. )
  5137. if downloaded:
  5138. downloaded_filename = try_filename
  5139. logger.info("Downloaded: %s", remote_path)
  5140. # Populate shared cache so the cover endpoint (if it
  5141. # runs next) doesn't refetch the same 36MB over FTP.
  5142. cache_3mf_download(printer_id, try_filename, temp_path)
  5143. break
  5144. # with_ftp_retry returns None once it has spent its budget,
  5145. # and download_file_async returns False on a timeout, so an
  5146. # exhausted transfer arrives here rather than as an
  5147. # exception (#3063).
  5148. ftp_transfer_failed = True
  5149. sweep_failed_paths.add(remote_path)
  5150. except FileNotOnPrinterError:
  5151. # 550 — file isn't at this path. Advance to next candidate
  5152. # without burning the retry budget.
  5153. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5154. except Exception as e:
  5155. ftp_transfer_failed = True
  5156. sweep_failed_paths.add(remote_path)
  5157. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5158. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5159. break
  5160. # If still not found, try listing directories to find matching file
  5161. # Different printer models use different directory structures. Skipped
  5162. # when the printer's FTPS handshake is failing — the directory walk is
  5163. # five more connections that cannot get further than the download did.
  5164. if (
  5165. not downloaded_filename
  5166. and storage.reachable
  5167. and (filename or subtask_name)
  5168. and not ftps_handshake_blocked(printer.ip_address)
  5169. ):
  5170. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5171. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5172. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5173. # Every folder is listed before one file is picked, so a file named
  5174. # for the print in a later folder wins over one that merely
  5175. # contains the name in an earlier folder.
  5176. listed_paths: list[str] = []
  5177. for search_dir in search_dirs:
  5178. try:
  5179. dir_files = await list_files_async(
  5180. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5181. )
  5182. except Exception as e:
  5183. logger.debug("Failed to list %s: %s", search_dir, e)
  5184. continue
  5185. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5186. if threemf_files:
  5187. logger.info(
  5188. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5189. )
  5190. listed_paths += [
  5191. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5192. ]
  5193. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5194. if remote_full_path in sweep_failed_paths:
  5195. # Listed for this print, and its transfer already failed:
  5196. # the same as a failed walk download, without spending a
  5197. # second deadline on it. Skipping it cannot hand the walk a
  5198. # look-alike: while a file of the print's own name is
  5199. # listed, files that merely contain the name are not.
  5200. logger.info(
  5201. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5202. remote_full_path,
  5203. )
  5204. walk_transfer_failed = True
  5205. continue
  5206. fname = posixpath.basename(remote_full_path)
  5207. logger.info("Found matching file: %s", remote_full_path)
  5208. temp_path = app_settings.archive_dir / "temp" / fname
  5209. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5210. try:
  5211. if ftp_retry_enabled:
  5212. downloaded = await with_ftp_retry(
  5213. download_file_async,
  5214. printer.ip_address,
  5215. printer.access_code,
  5216. remote_full_path,
  5217. temp_path,
  5218. timeout=ftp_timeout,
  5219. socket_timeout=ftp_timeout,
  5220. printer_model=printer.model,
  5221. max_retries=ftp_retry_count,
  5222. retry_delay=ftp_retry_delay,
  5223. operation_name=f"Download 3MF from {remote_full_path}",
  5224. cooloff_ip=printer.ip_address,
  5225. )
  5226. else:
  5227. downloaded = await download_file_async(
  5228. printer.ip_address,
  5229. printer.access_code,
  5230. remote_full_path,
  5231. temp_path,
  5232. timeout=ftp_timeout,
  5233. socket_timeout=ftp_timeout,
  5234. printer_model=printer.model,
  5235. )
  5236. except Exception as e:
  5237. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5238. continue
  5239. if downloaded:
  5240. downloaded_filename = fname
  5241. logger.info("Found and downloaded: %s", remote_full_path)
  5242. cache_3mf_download(printer_id, fname, temp_path)
  5243. break
  5244. # The listing named the file, so it is on the card;
  5245. # only the transfer failed (#3063).
  5246. ftp_transfer_failed = True
  5247. walk_transfer_failed = True
  5248. # A "Print again" on the printer's screen names no file Bambuddy can
  5249. # find: only its history copy under a generic name, and the 3MF's
  5250. # internal title (#3307). When an earlier run of the same job was
  5251. # archived, its 3MF is the one being printed again. Not when the
  5252. # directory walk listed a file for this print and only its transfer
  5253. # failed: that file is on the card, and the retry fetches it. A
  5254. # cool-off or a failed sweep path is no such evidence -- the retry
  5255. # tries the same names, which this print's file never had.
  5256. reused_3mf_from: int | None = None
  5257. if not downloaded_filename and not walk_transfer_failed:
  5258. reported_layers = raw_mqtt.get("total_layer_num")
  5259. earlier = await _archived_3mf_for_repeat(
  5260. db,
  5261. printer_id,
  5262. subtask_name,
  5263. filename,
  5264. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5265. )
  5266. if earlier is not None:
  5267. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5268. # Per printer: two printers reprinting the same job at once
  5269. # must not write one temp file (archive_print names the
  5270. # archive after original_filename, not this path).
  5271. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5272. try:
  5273. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5274. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5275. except OSError as e:
  5276. # A copy that fails leaves the print the fallback archive
  5277. # it would have had, not no archive at all.
  5278. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5279. else:
  5280. temp_path = reuse_path
  5281. downloaded_filename = reuse_name
  5282. reused_3mf_from = earlier.id
  5283. cache_3mf_download(printer_id, reuse_name, temp_path)
  5284. logger.info(
  5285. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5286. printer_id,
  5287. subtask_name,
  5288. filename,
  5289. earlier.id,
  5290. )
  5291. # Validate the downloaded 3MF actually matches the plate that's running
  5292. # (#1204): subtask_name lags across consecutive plates of the same model,
  5293. # so the first FTP candidate (built from subtask_name) can land on the
  5294. # previous plate's still-resident upload. Cross-check the slice_info
  5295. # plate index against the plate parsed from gcode_file (always fresh —
  5296. # it's the field whose change triggered this callback).
  5297. if downloaded_filename and temp_path:
  5298. expected_plate = parse_plate_id(filename)
  5299. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5300. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5301. logger.warning(
  5302. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5303. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5304. downloaded_filename,
  5305. actual_plate,
  5306. expected_plate,
  5307. subtask_name,
  5308. )
  5309. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5310. retry_succeeded = False
  5311. if corrected_subtask and corrected_subtask != subtask_name:
  5312. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5313. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5314. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5315. for remote_path in (
  5316. f"/{try_filename}",
  5317. f"/cache/{try_filename}",
  5318. f"/model/{try_filename}",
  5319. f"/data/{try_filename}",
  5320. f"/data/Metadata/{try_filename}",
  5321. ):
  5322. try:
  5323. if ftp_retry_enabled:
  5324. downloaded = await with_ftp_retry(
  5325. download_file_async,
  5326. printer.ip_address,
  5327. printer.access_code,
  5328. remote_path,
  5329. retry_temp_path,
  5330. timeout=ftp_timeout,
  5331. socket_timeout=ftp_timeout,
  5332. printer_model=printer.model,
  5333. max_retries=ftp_retry_count,
  5334. retry_delay=ftp_retry_delay,
  5335. operation_name=f"Re-download 3MF from {remote_path}",
  5336. cooloff_ip=printer.ip_address,
  5337. non_retry_exceptions=(FileNotOnPrinterError,),
  5338. )
  5339. else:
  5340. downloaded = await download_file_async(
  5341. printer.ip_address,
  5342. printer.access_code,
  5343. remote_path,
  5344. retry_temp_path,
  5345. timeout=ftp_timeout,
  5346. socket_timeout=ftp_timeout,
  5347. printer_model=printer.model,
  5348. )
  5349. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5350. logger.info(
  5351. "[CALLBACK] Re-download succeeded with corrected name %s "
  5352. "(plate %s) — replacing wrong file",
  5353. try_filename,
  5354. expected_plate,
  5355. )
  5356. try:
  5357. temp_path.unlink(missing_ok=True)
  5358. except OSError:
  5359. pass
  5360. temp_path = retry_temp_path
  5361. downloaded_filename = try_filename
  5362. subtask_name = corrected_subtask
  5363. cache_3mf_download(printer_id, try_filename, temp_path)
  5364. retry_succeeded = True
  5365. break
  5366. elif downloaded:
  5367. # Wrong plate again — discard and keep trying
  5368. try:
  5369. retry_temp_path.unlink(missing_ok=True)
  5370. except OSError:
  5371. pass
  5372. except FileNotOnPrinterError:
  5373. continue
  5374. except Exception as e:
  5375. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5376. if retry_succeeded:
  5377. break
  5378. # If the retry didn't find a matching file, drop the wrong 3MF
  5379. # so the no-3MF fallback below creates an archive whose name
  5380. # at least reflects the right plate.
  5381. if not retry_succeeded:
  5382. logger.warning(
  5383. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5384. expected_plate,
  5385. )
  5386. try:
  5387. temp_path.unlink(missing_ok=True)
  5388. except OSError:
  5389. pass
  5390. temp_path = None
  5391. downloaded_filename = None
  5392. # Whatever the sweep's transport did earlier, it is not why
  5393. # this archive ends up empty: a 3MF downloaded fine, it was
  5394. # just the wrong plate. Retrying would re-fetch that same
  5395. # contradicted file under the same stale names and hand it
  5396. # to _recover_fallback_archive, which checks that a
  5397. # candidate is a readable 3MF but not which plate it is --
  5398. # so the row would be filled in with another plate's
  5399. # filament and cost, the exact swap #2957 removed (#3063).
  5400. ftp_transfer_failed = False
  5401. # Disown the name for *lookups*: it has just been shown to
  5402. # fetch another plate's 3MF, and it keys `_active_prints`
  5403. # below, where the cover endpoint's own download of that
  5404. # same name would find this archive and fill it in with the
  5405. # file we are discarding here.
  5406. #
  5407. # Keep it for the *title*, which is a separate question.
  5408. # ``swap_plate_suffix`` returns None both for a name that
  5409. # carries no "- Plate N" / "_plate_N" suffix and for no
  5410. # name at all, and those are not the same situation: a name
  5411. # without a suffix holds no stale plate number to be wrong
  5412. # about. Blanking both uses at once dropped the project
  5413. # name too, and the row fell through to the gcode_file path
  5414. # titled "plate_1" though the real name was in hand.
  5415. # #1204's own premise is consecutive plates *of the same
  5416. # model*, so the project part is right either way (#3126).
  5417. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5418. subtask_name = corrected_subtask or ""
  5419. # Deleted while the 3MF was being fetched (that can take minutes): no
  5420. # archive, timelapse or tracking for a printer that will never report
  5421. # the print's end. forget_printer again: the download registered its
  5422. # 3MF cache entry after the delete cleared the id. (A delete committing
  5423. # while the archive is written is caught after its commit.)
  5424. if await _printer_gone(db, printer_id):
  5425. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5426. await forget_printer(printer_id)
  5427. return
  5428. if not downloaded_filename or not temp_path:
  5429. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5430. # Create a fallback archive without 3MF data so the print is still tracked
  5431. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5432. try:
  5433. from backend.app.models.archive import PrintArchive
  5434. # Why the card is empty. The two temporary causes outrank the
  5435. # storage verdict because they say the sweep never got a fair
  5436. # answer: a cool-off skipped it at the transport, and a failed
  5437. # transfer reached the printer but never finished. Either way
  5438. # the file is still on the card, so reporting where the printer
  5439. # files its jobs would describe a setting that is not the
  5440. # problem (#2957, #3063).
  5441. if blocked_by_ftps_cooloff:
  5442. no_3mf_reason = REASON_FTPS_COOLOFF
  5443. elif storage.reachable and ftp_transfer_failed:
  5444. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5445. else:
  5446. no_3mf_reason = storage.reason
  5447. # Derive print name from subtask_name or filename. The
  5448. # plate guard's disowned name comes second: it is a real name
  5449. # for a real print, and only the gcode_file path is left
  5450. # otherwise -- which titles the row "plate_1" (#3126).
  5451. print_name = subtask_name or display_name_after_plate_reject or filename
  5452. if print_name:
  5453. # Clean up the name (remove extensions, path parts)
  5454. print_name = print_name.split("/")[-1]
  5455. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5456. else:
  5457. print_name = "Unknown Print"
  5458. # Recover estimated print time from MQTT (best-effort for notifications)
  5459. fallback_print_time = None
  5460. mqtt_remaining = data.get("remaining_time")
  5461. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5462. fallback_print_time = int(mqtt_remaining)
  5463. if fallback_print_time is None:
  5464. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5465. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5466. fallback_print_time = int(mc_remaining * 60)
  5467. # Best-effort filament metadata from MQTT — see
  5468. # _extract_filament_data_from_mqtt. Without this the fallback
  5469. # archive's filament fields stayed NULL even though the AMS
  5470. # state at print start was sitting right there in `data`.
  5471. # The slicer's ams_mapping (when present) narrows the result
  5472. # to slots actually used by the print (#1533).
  5473. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5474. # Create minimal archive entry
  5475. fallback_archive = PrintArchive(
  5476. printer_id=printer_id,
  5477. filename=filename or f"{print_name}.3mf",
  5478. file_path="", # Empty - no 3MF file available
  5479. file_size=0,
  5480. print_name=print_name,
  5481. print_time_seconds=fallback_print_time,
  5482. status="printing",
  5483. started_at=detected_at,
  5484. subtask_id=subtask_id,
  5485. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5486. filament_type=mqtt_filament_meta.get("filament_type"),
  5487. filament_color=mqtt_filament_meta.get("filament_color"),
  5488. extra_data={
  5489. "no_3mf_available": True,
  5490. # Why the card is empty, when we know -- see above. The
  5491. # banner reads this to stop telling H2/P2 owners to
  5492. # switch on a setting that is already on and would not
  5493. # have helped (#2780).
  5494. "no_3mf_reason": no_3mf_reason,
  5495. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5496. "_print_data": data,
  5497. },
  5498. )
  5499. db.add(fallback_archive)
  5500. try:
  5501. await db.commit()
  5502. except IntegrityError:
  5503. # Not "Failed to create fallback archive" below, and no
  5504. # start notification for a printer that is gone.
  5505. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5506. return
  5507. raise
  5508. await db.refresh(fallback_archive)
  5509. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5510. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5511. return
  5512. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5513. # Track as active print
  5514. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5515. await _open_run_for(fallback_archive.id, printer_id)
  5516. # Record starting energy if smart plug available (#941: persisted column)
  5517. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5518. # Send WebSocket notification
  5519. await ws_manager.send_archive_created(
  5520. {
  5521. "id": fallback_archive.id,
  5522. "printer_id": fallback_archive.printer_id,
  5523. "filename": fallback_archive.filename,
  5524. "print_name": fallback_archive.print_name,
  5525. "status": fallback_archive.status,
  5526. }
  5527. )
  5528. # MQTT relay - publish archive created
  5529. try:
  5530. await mqtt_relay.on_archive_created(
  5531. archive_id=fallback_archive.id,
  5532. print_name=fallback_archive.print_name,
  5533. printer_name=printer.name,
  5534. status=fallback_archive.status,
  5535. )
  5536. except Exception:
  5537. pass # Don't fail if MQTT fails
  5538. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5539. try:
  5540. await _store_spoolman_print_data(
  5541. printer_id,
  5542. fallback_archive.id,
  5543. fallback_archive.file_path,
  5544. db,
  5545. printer_manager,
  5546. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5547. plate_id=_get_start_plate_id(fallback_archive.id),
  5548. )
  5549. except Exception as e:
  5550. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5551. # Both temporary give-ups are worth coming back for, and for
  5552. # the same reason: the file is on the printer and the last look
  5553. # failed at the transport rather than finding nothing. One waits
  5554. # out the handshake block (#2957), the other waits for the
  5555. # printer to stop being busy (#3063). Deliberately not scheduled
  5556. # for a storage verdict: a file on internal eMMC will not appear
  5557. # at any FTPS path however long we wait, and retrying it is
  5558. # exactly the sweep #2780 removed.
  5559. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5560. # `possible_names`, not the raw MQTT strings: it is the exact
  5561. # list this flow just tried, already stripped of any path
  5562. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5563. # some firmware) and deduped.
  5564. _schedule_fallback_3mf_retry(
  5565. printer_id=printer_id,
  5566. archive_id=fallback_archive.id,
  5567. filenames=list(possible_names),
  5568. reason=no_3mf_reason,
  5569. )
  5570. # Send notification without archive data (file not found)
  5571. if not notification_sent:
  5572. await _send_print_start_notification(printer_id, data, logger=logger)
  5573. # The same baseline the other two on_print_start branches take
  5574. # (#2704), and last for the same reason they are: it lists the
  5575. # printer's timelapse directory, so a slow card must not delay
  5576. # the _active_prints registration, the energy reading, the
  5577. # archive-created event or the start notification above it.
  5578. #
  5579. # This branch never took one, so every no-3MF archive reached
  5580. # completion with no baseline in memory and none on the row, and
  5581. # the completion scan fell into its "snapshot now" fallback --
  5582. # which runs after the printer has written the video, so the new
  5583. # file landed inside the baseline and no diff ever matched
  5584. # (#2957 follow-up).
  5585. #
  5586. # Skipped when the FTPS cool-off is what produced this fallback:
  5587. # the listing needs the same connection that just failed, so it
  5588. # could only record that the card was unreadable. The scan
  5589. # handles that case by refusing to choose between candidates.
  5590. if not blocked_by_ftps_cooloff:
  5591. await _capture_timelapse_baseline_at_start(
  5592. printer, printer_id, logger, archive_id=fallback_archive.id
  5593. )
  5594. await _forget_if_printer_gone(printer_id)
  5595. return
  5596. except Exception as e:
  5597. logger.error("Failed to create fallback archive: %s", e)
  5598. # Send notification without archive data (file not found)
  5599. if not notification_sent:
  5600. await _send_print_start_notification(printer_id, data, logger=logger)
  5601. return
  5602. try:
  5603. # Archive the file with status "printing"
  5604. service = ArchiveService(db)
  5605. try:
  5606. archive = await service.archive_print(
  5607. printer_id=printer_id,
  5608. source_file=temp_path,
  5609. print_data={
  5610. **data,
  5611. "status": "printing",
  5612. # Where the 3MF came from when the printer had none to
  5613. # give (#3307), for whoever reads this archive later.
  5614. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5615. },
  5616. subtask_id=subtask_id,
  5617. started_at=detected_at,
  5618. # The reused copy's temp name carries the printer id; a
  5619. # download's is the file's own name, as before.
  5620. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5621. )
  5622. except IntegrityError:
  5623. # archive_print removed the folder it had copied the 3MF into.
  5624. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5625. return
  5626. raise
  5627. if archive:
  5628. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5629. # Set on the row rather than passed to archive_print, which also
  5630. # serves the queue dispatcher — there the queue item decides.
  5631. # Guarded because this branch has no ``except``: an unhandled
  5632. # write error would take the _active_prints registration, the
  5633. # start notification, the energy reading and the timelapse
  5634. # baseline below it with it, and a missing prompt is by far the
  5635. # cheaper failure.
  5636. archive_id = archive.id
  5637. try:
  5638. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5639. archive.confirm_requested = True
  5640. await db.commit()
  5641. except Exception as e:
  5642. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5643. # The rollback expires every loaded object, and on an async
  5644. # session reading one afterwards raises instead of
  5645. # reloading, so the two this branch goes on to use are
  5646. # fetched again. The archive itself was committed by
  5647. # archive_print; only the flag is lost.
  5648. try:
  5649. await db.rollback()
  5650. archive = await db.get(PrintArchive, archive_id)
  5651. printer = await db.get(Printer, printer_id)
  5652. except Exception as reload_error:
  5653. logger.warning(
  5654. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5655. )
  5656. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5657. return
  5658. # Track this active print (use both original filename and downloaded filename)
  5659. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5660. await _open_run_for(archive_id, printer_id)
  5661. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5662. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5663. # Record starting energy from smart plug if available (#941: persisted column)
  5664. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5665. await ws_manager.send_archive_created(
  5666. {
  5667. "id": archive.id,
  5668. "printer_id": archive.printer_id,
  5669. "filename": archive.filename,
  5670. "print_name": archive.print_name,
  5671. "status": archive.status,
  5672. }
  5673. )
  5674. # MQTT relay - publish archive created
  5675. try:
  5676. await mqtt_relay.on_archive_created(
  5677. archive_id=archive.id,
  5678. print_name=archive.print_name,
  5679. printer_name=printer.name,
  5680. status=archive.status,
  5681. )
  5682. except Exception:
  5683. pass # Don't fail if MQTT fails
  5684. # Send notification with archive data (new archive created)
  5685. if not notification_sent:
  5686. archive_data = {
  5687. "print_time_seconds": archive.print_time_seconds,
  5688. "created_by_id": archive.created_by_id,
  5689. }
  5690. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5691. # Extract printable objects for skip object functionality
  5692. try:
  5693. from backend.app.services.archive import extract_printable_objects_from_3mf
  5694. client = printer_manager.get_client(printer_id)
  5695. if client:
  5696. with open(temp_path, "rb") as f:
  5697. threemf_data = f.read()
  5698. # Extract with positions for UI overlay, scoped to the
  5699. # plate that is printing — an all-plates 3MF carries
  5700. # every plate's objects (#2522).
  5701. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5702. threemf_data,
  5703. plate_number=resolve_plate_id(client.state),
  5704. include_positions=True,
  5705. )
  5706. if printable_objects:
  5707. # Store objects in printer state
  5708. client.state.printable_objects = printable_objects
  5709. client.state.printable_objects_bbox_all = bbox_all
  5710. client.state.skipped_objects = [] # Reset skipped objects for new print
  5711. logger.info(
  5712. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5713. )
  5714. except Exception as e:
  5715. logger.debug("Failed to extract printable objects: %s", e)
  5716. # From the archived copy: the downloaded one may be removed
  5717. # below while the pauses are still being read.
  5718. if archive is not None and archive.file_path:
  5719. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5720. # Store Spoolman tracking data for per-filament usage reporting
  5721. try:
  5722. await _store_spoolman_print_data(
  5723. printer_id,
  5724. archive.id,
  5725. archive.file_path,
  5726. db,
  5727. printer_manager,
  5728. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5729. plate_id=_get_start_plate_id(archive.id),
  5730. )
  5731. except Exception as e:
  5732. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5733. # Price the print from its spools now rather than only at completion (#3261)
  5734. _schedule_archive_cost_estimate(
  5735. printer_id,
  5736. archive.id,
  5737. printer_manager,
  5738. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5739. plate_id=_get_start_plate_id(archive.id),
  5740. session_factory=async_session,
  5741. )
  5742. # Capture timelapse file baseline for snapshot-diff on completion
  5743. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5744. await _forget_if_printer_gone(printer_id)
  5745. finally:
  5746. # Keep temp_path around until print completes so the cover endpoint
  5747. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5748. # the file. If the cache entry was evicted early (file vanished),
  5749. # clean up any stragglers here to avoid leaking disk on retries.
  5750. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5751. if temp_path and temp_path.exists() and cached_now != temp_path:
  5752. temp_path.unlink()
  5753. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5754. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5755. # A baseline that could not be read at print start is read again on this
  5756. # schedule while the print runs (#3412). The printer writes the video only once
  5757. # the print has ended, so a reading taken mid-print is as good as one taken at
  5758. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5759. # which is what usually makes the card unreadable, so the first reading after
  5760. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5761. # no connection is opened. The cap bounds a print that never reports an end.
  5762. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5763. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5764. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5765. # tests can shrink them without waiting out real delays.
  5766. #
  5767. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5768. # looking. Across 247 support bundles the attempt that found the video was #1
  5769. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5770. # decaying one, which is the signature of a budget that expires while files are
  5771. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5772. # prints make big videos and the printer writes them after the print ends, so
  5773. # the poll now runs for minutes and costs one FTP LIST per round.
  5774. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5775. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5776. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5777. def _timelapse_scan_max_attempts() -> int:
  5778. """Round cap for the poll, derived from the wall-clock budget.
  5779. The deadline alone is not a sufficient bound: it assumes each round really
  5780. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5781. and an FTP list that fails immediately would otherwise spin against the
  5782. printer at full speed for the whole window. Whichever bound is reached
  5783. first ends the poll.
  5784. """
  5785. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5786. # A zero interval makes the wall-clock budget meaningless; fall back to
  5787. # the round count the production interval would have given.
  5788. return 32
  5789. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5790. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5791. """Video filenames already attached to some other archive of this printer.
  5792. Used to disambiguate when more than one file is new since the baseline —
  5793. which happens when a previous print's video landed after this print's
  5794. baseline was taken. Ordering the candidates would be the obvious fix and is
  5795. the wrong one: it can only be done on mtime or on the filename timestamp,
  5796. both of which come from the printer's own clock, and a LAN-only printer
  5797. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5798. ``attach_timelapse`` saves the video into the archive directory under the
  5799. printer's original filename, and the later MP4 conversion keeps the stem,
  5800. so the stem of ``timelapse_path`` recovers what was claimed.
  5801. """
  5802. from backend.app.models.archive import PrintArchive
  5803. rows = await db.execute(
  5804. select(PrintArchive.timelapse_path).where(
  5805. PrintArchive.printer_id == printer_id,
  5806. PrintArchive.id != exclude_archive_id,
  5807. PrintArchive.timelapse_path.is_not(None),
  5808. )
  5809. )
  5810. return {Path(p).stem for p in rows.scalars().all() if p}
  5811. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5812. """The video names on *printer*'s card, and whether the card was read.
  5813. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5814. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5815. listing timed out, is indistinguishable from one holding no videos.
  5816. Everywhere that only wants to know "is there a video yet" the difference
  5817. does not matter -- both mean "not yet, retry".
  5818. It matters where an empty listing is recorded as a *baseline*. Recording
  5819. "the card held nothing" for a card that was never read means every video on
  5820. it counts as new, and the completion scan then attaches a stale video to
  5821. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5822. empty listing is asked again here in a way that tells the two apart: the
  5823. card counts as read only when every directory walked answered, with a
  5824. listing or with "no such directory". One that failed may be the one
  5825. holding the videos.
  5826. """
  5827. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  5828. files, _ = await _list_timelapse_videos(printer)
  5829. if files:
  5830. return {f.get("name", "") for f in files}, True
  5831. ip_address = getattr(printer, "ip_address", None)
  5832. printer_id = getattr(printer, "id", None)
  5833. if not ip_address:
  5834. return set(), True
  5835. # No card in the slot: nothing to read, and nothing a video could land on.
  5836. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5837. return set(), True
  5838. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5839. if ftps_handshake_blocked(ip_address):
  5840. # Below any path: every remaining one would fail the same way.
  5841. return set(), False
  5842. listing = await list_files_result_async(
  5843. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5844. )
  5845. if not (listing.available or listing.missing):
  5846. return set(), False
  5847. videos = [
  5848. f
  5849. for f in listing.files
  5850. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5851. ]
  5852. if videos:
  5853. return {f.get("name", "") for f in videos}, True
  5854. return set(), True
  5855. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5856. """List video files from printer's timelapse directory.
  5857. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5858. Returns (video_files, found_path) where video_files is a list of file dicts
  5859. and found_path is the directory where they were found, or ([], None).
  5860. An empty return does not distinguish "no videos" from "could not read the
  5861. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  5862. callers use instead.
  5863. """
  5864. from backend.app.services.bambu_ftp import list_files_async
  5865. logger = logging.getLogger(__name__)
  5866. # No card in the slot means no /timelapse to walk — four connections that
  5867. # can only fail, on a path whose failures are swallowed and so would go on
  5868. # costing time silently forever (#2780).
  5869. #
  5870. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5871. # inside the loop's own try/except, so a caller that passed something
  5872. # unexpected used to get an empty listing rather than an exception. Keep
  5873. # that, instead of making this gate the first thing that can raise here.
  5874. printer_id = getattr(printer, "id", None)
  5875. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5876. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5877. return [], None
  5878. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5879. try:
  5880. found_files = await list_files_async(
  5881. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5882. )
  5883. if found_files:
  5884. video_files = [
  5885. f
  5886. for f in found_files
  5887. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5888. ]
  5889. if video_files:
  5890. return video_files, timelapse_path
  5891. except Exception as e:
  5892. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5893. continue
  5894. return [], None
  5895. async def _capture_timelapse_baseline_at_start(
  5896. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5897. ) -> None:
  5898. """Snapshot the printer's timelapse directory at print start so the
  5899. completion-time scan can pick the new file by set-difference.
  5900. Must be called from every on_print_start path that proceeds to a real
  5901. print — both the new-archive branch and the expected-archive branch (which
  5902. queue / VP-dispatched prints take). Without a baseline,
  5903. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5904. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5905. so the new file ends up in the "baseline" set and no diff ever matches.
  5906. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5907. unreliable — the snapshot-diff approach sidesteps that entirely.
  5908. When ``archive_id`` is known the baseline is also written to the archive
  5909. row, so it survives a restart and the manual "Scan for Timelapse" button
  5910. can run the same diff instead of falling back to clock-based matching
  5911. (#2704). Only baselines taken at print start are persisted — one taken at
  5912. completion already contains the new video and would poison a later scan.
  5913. """
  5914. names: set[str] | None = None
  5915. unread = False
  5916. _timelapse_baselines_unread.discard(printer_id)
  5917. try:
  5918. names, read = await _read_timelapse_baseline(printer)
  5919. unread = not read
  5920. _timelapse_baselines[printer_id] = names
  5921. if unread:
  5922. # Recorded anyway, deliberately, and marked. An empty baseline taken
  5923. # off a card we could not read is not evidence, but it is still the
  5924. # right *default*: Bambuddy deletes each video from the printer once
  5925. # it is attached, so the usual card holds exactly one video at
  5926. # completion and an empty baseline resolves it. Persisting NULL
  5927. # instead would send completion to take its own snapshot, by which
  5928. # point this print's video is on the card and would be swallowed by
  5929. # it. The mark keeps the scan from choosing between several videos
  5930. # (#3412), and the card is read again while the print runs.
  5931. _timelapse_baselines_unread.add(printer_id)
  5932. logger.warning(
  5933. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  5934. "treating it as empty for now and reading it again during the print",
  5935. printer_id,
  5936. )
  5937. logger.info(
  5938. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5939. len(names),
  5940. printer_id,
  5941. )
  5942. except Exception as e:
  5943. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5944. run_started_at: datetime | None = None
  5945. if archive_id is not None:
  5946. try:
  5947. async with async_session() as db:
  5948. from backend.app.models.archive import PrintArchive
  5949. archive = await db.get(PrintArchive, archive_id)
  5950. if archive is not None:
  5951. # Written even when the listing failed, and then as NULL. A
  5952. # reprint reuses the archive row, so leaving the previous
  5953. # run's baseline in place would have the scan diff this print
  5954. # against the state of the printer before the *last* one —
  5955. # and a stale baseline reads as authoritative, where NULL
  5956. # correctly falls back to a fresh snapshot.
  5957. archive.timelapse_baseline = sorted(names) if names is not None else None
  5958. archive.timelapse_baseline_unread = unread
  5959. run_started_at = archive.started_at
  5960. await db.commit()
  5961. except Exception as e:
  5962. # In-memory baseline still covers the normal completion path.
  5963. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5964. if unread and names is not None:
  5965. spawn_background_task(
  5966. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at),
  5967. name=f"reread-timelapse-baseline-{printer_id}",
  5968. )
  5969. # Before the print has ended there is no video yet: a long PREPARE (heating,
  5970. # levelling) counts as much as the print itself.
  5971. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  5972. def _schedule_timelapse_scan(archive_id: int, printer_id: int, *, plate_id: int | None) -> None:
  5973. """Start the completion scan with the print-start baseline: the names, and
  5974. whether they were taken off a card that could not be read. Taking them
  5975. ends any re-read still running for it."""
  5976. unread = printer_id in _timelapse_baselines_unread
  5977. _timelapse_baselines_unread.discard(printer_id)
  5978. baseline = _timelapse_baselines.pop(printer_id, None)
  5979. spawn_background_task(
  5980. _mark_run_finishing(
  5981. archive_id,
  5982. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=plate_id, baseline_unread=unread),
  5983. ),
  5984. name=f"scan-timelapse-{archive_id}",
  5985. )
  5986. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  5987. """Whether to read an unread baseline again now: True to read, None to
  5988. skip this round, False once it is over -- the print it was taken for is
  5989. no longer the one on the printer, has stopped printing, or the baseline
  5990. has been read.
  5991. ``names`` is the very set object recorded at print start: completion pops
  5992. it and the next print records a new one, so identity marks the run. A
  5993. printer that is momentarily disconnected says nothing about its print, so
  5994. that only skips the round.
  5995. """
  5996. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  5997. return False
  5998. state = printer_manager.get_status(printer_id)
  5999. if state is None or not state.connected:
  6000. return None
  6001. return state.state in _BASELINE_REREAD_STATES
  6002. async def _reread_unread_timelapse_baseline(
  6003. printer_id: int, names: set[str], archive_id: int | None, run_started_at: datetime | None
  6004. ) -> None:
  6005. """Read again a print-start baseline the card could not give (#3412).
  6006. The printer writes the video only once the print has ended, so the card
  6007. read at any point during the print holds exactly what it held at the
  6008. start. Each round stops once the print is no longer the one the baseline
  6009. was taken for or has stopped printing, and checks that again after the
  6010. listing returns, before anything is recorded.
  6011. """
  6012. from backend.app.models.archive import PrintArchive
  6013. from backend.app.models.printer import Printer
  6014. logger = logging.getLogger(__name__)
  6015. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6016. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6017. now = _unread_baseline_round(printer_id, names)
  6018. if now is False:
  6019. return
  6020. if now is None:
  6021. continue
  6022. try:
  6023. async with async_session() as db:
  6024. printer = await db.get(Printer, printer_id)
  6025. if printer is None:
  6026. return
  6027. fresh, read = await _read_timelapse_baseline(printer)
  6028. except Exception as e:
  6029. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6030. continue
  6031. if not read:
  6032. continue
  6033. now = _unread_baseline_round(printer_id, names)
  6034. if now is False:
  6035. return
  6036. if now is None:
  6037. # The printer dropped off while the listing was out, so nothing
  6038. # says it did not end meanwhile: keep the reading for a round that
  6039. # can vouch for it.
  6040. continue
  6041. names.update(fresh)
  6042. _timelapse_baselines_unread.discard(printer_id)
  6043. logger.info(
  6044. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6045. printer_id,
  6046. len(fresh),
  6047. )
  6048. if archive_id is None:
  6049. return
  6050. try:
  6051. async with async_session() as db:
  6052. archive = await db.get(PrintArchive, archive_id)
  6053. # Only the run it was taken for: by now the row can belong to a
  6054. # reprint, whose baseline is its own.
  6055. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6056. archive.timelapse_baseline = sorted(names)
  6057. archive.timelapse_baseline_unread = False
  6058. await db.commit()
  6059. except Exception as e:
  6060. # The in-memory baseline is read now, which covers completion
  6061. # unless Bambuddy restarts first.
  6062. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6063. return
  6064. async def _scan_for_timelapse_with_retries(
  6065. archive_id: int,
  6066. baseline_names: set[str] | None = None,
  6067. *,
  6068. plate_id: int | None = None,
  6069. baseline_unread: bool = False,
  6070. ):
  6071. """Poll the printer for this print's timelapse and attach it.
  6072. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6073. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6074. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6075. (#2704). Comparing the current listing against the set of filenames that
  6076. existed when the print started needs no clock at all, because the printer
  6077. writes the video only once the print has ended.
  6078. Baseline precedence: the caller's in-memory set, then the one persisted on
  6079. the archive at print start, then a snapshot taken now. The last of those is
  6080. a poor substitute — by completion the new video may already be on the card,
  6081. in which case it lands in the "baseline" and no diff can ever match — but it
  6082. is all that is available for a print that began before Bambuddy started.
  6083. On success the video is deleted from the printer, which keeps ``/timelapse``
  6084. down to the unclaimed files and makes the next diff unambiguous.
  6085. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6086. could not be read; a stored one carries the same mark on the archive.
  6087. """
  6088. logger = logging.getLogger(__name__)
  6089. # Cleared when the baseline was taken off a card we could not read, so the
  6090. # attach step refuses to choose between several candidates (#2957, #3412).
  6091. baseline_trusted = True
  6092. # --- Phase 1: establish the baseline -------------------------------------
  6093. try:
  6094. async with async_session() as db:
  6095. from backend.app.models.printer import Printer
  6096. service = ArchiveService(db)
  6097. archive = await service.get_archive(archive_id)
  6098. if not archive:
  6099. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6100. return
  6101. if archive.timelapse_path:
  6102. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6103. return
  6104. if not archive.printer_id:
  6105. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6106. return
  6107. # The run this scan is for. The archive row passes to a newer run
  6108. # when it prints again (the next plate, a reprint), and that run's
  6109. # video is its own.
  6110. run_started_at = archive.started_at
  6111. if (
  6112. baseline_names is not None
  6113. and baseline_unread
  6114. and archive.timelapse_baseline is not None
  6115. and not archive.timelapse_baseline_unread
  6116. ):
  6117. # The card was read at print start, and the in-memory copy is
  6118. # one Bambuddy took after a restart off a card it could not
  6119. # read: the stored one is this run's and is evidence.
  6120. baseline_names = set(archive.timelapse_baseline)
  6121. logger.info(
  6122. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6123. len(baseline_names),
  6124. archive_id,
  6125. )
  6126. elif baseline_names is not None:
  6127. baseline_trusted = not baseline_unread
  6128. logger.info(
  6129. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6130. len(baseline_names),
  6131. archive_id,
  6132. )
  6133. elif archive.timelapse_baseline is not None:
  6134. # Persisted at print start — survives a restart mid-print.
  6135. baseline_names = set(archive.timelapse_baseline)
  6136. baseline_trusted = not archive.timelapse_baseline_unread
  6137. logger.info(
  6138. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6139. len(baseline_names),
  6140. archive_id,
  6141. )
  6142. else:
  6143. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6144. printer = result.scalar_one_or_none()
  6145. if not printer:
  6146. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6147. return
  6148. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6149. if not baseline_trusted:
  6150. # The card is unreadable at the one moment a baseline has to
  6151. # be taken, so the empty listing means "we never looked",
  6152. # not "these are all new". Carry on with it anyway — the
  6153. # usual card holds exactly one video, which resolves
  6154. # correctly — but stop the poll from *choosing* between
  6155. # several, which is how a stale video got attached to this
  6156. # print and then deleted off the printer (#2957 follow-up).
  6157. logger.warning(
  6158. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6159. "read. A single new video still resolves; several will not be guessed between — "
  6160. "use Scan for Timelapse to pick one by hand",
  6161. archive_id,
  6162. archive.printer_id,
  6163. )
  6164. logger.info(
  6165. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6166. len(baseline_names),
  6167. archive_id,
  6168. )
  6169. except Exception as e:
  6170. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6171. return
  6172. # --- Phase 2: poll for a file that was not there when the print began -----
  6173. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6174. max_attempts = _timelapse_scan_max_attempts()
  6175. seen_names: set[str] = set()
  6176. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6177. attempt = 0
  6178. while True:
  6179. await asyncio.sleep(delay)
  6180. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6181. attempt += 1
  6182. try:
  6183. from backend.app.models.printer import Printer
  6184. # Read phase: fetch archive + printer in a short session and release
  6185. # the pooled connection BEFORE the FTP list/download below. Holding it
  6186. # across the FTP round-trips left one connection idle-in-transaction per
  6187. # in-flight scan (issue #2572).
  6188. async with async_session() as db:
  6189. service = ArchiveService(db)
  6190. archive = await service.get_archive(archive_id)
  6191. if not archive:
  6192. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6193. return
  6194. if archive.timelapse_path:
  6195. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  6196. return
  6197. if archive.started_at != run_started_at:
  6198. logger.info(
  6199. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  6200. )
  6201. return
  6202. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6203. printer = result.scalar_one_or_none()
  6204. if not printer:
  6205. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6206. return
  6207. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  6208. # I/O phase (no DB connection held): FTP list + download.
  6209. video_files, found_path = await _list_timelapse_videos(printer)
  6210. # The poll can run for dozens of rounds, so only narrate a round
  6211. # that saw something change. Repeating the whole listing every 30 s
  6212. # would bury the one interesting line in the support bundle.
  6213. names_now = {f.get("name", "") for f in video_files}
  6214. changed = attempt == 1 or names_now != seen_names
  6215. seen_names = names_now
  6216. speak = logger.info if changed else logger.debug
  6217. if video_files:
  6218. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6219. if changed:
  6220. for f in video_files[:5]:
  6221. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6222. attached = await _attach_first_unclaimed_timelapse(
  6223. archive_id,
  6224. printer,
  6225. video_files,
  6226. baseline_names,
  6227. claimed,
  6228. attempt,
  6229. logger,
  6230. quiet=not changed,
  6231. require_unambiguous=not baseline_trusted,
  6232. plate_id=plate_id,
  6233. run_started_at=run_started_at,
  6234. )
  6235. if attached:
  6236. return
  6237. else:
  6238. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6239. except Exception as e:
  6240. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6241. if attempt >= max_attempts or time.monotonic() >= deadline:
  6242. break
  6243. # No name-match fallback: it compared the print name against the filename,
  6244. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6245. # bundles it fired 159 times and matched zero times, so all it added was a
  6246. # misleading log line before giving up.
  6247. logger.warning(
  6248. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6249. archive_id,
  6250. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6251. )
  6252. async def _attach_layer_timelapse(
  6253. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  6254. ) -> None:
  6255. """Attach the external camera's stitched timelapse to the archive.
  6256. The camera's video is the one the user set up in Bambuddy, so it wins
  6257. over the printer's own when both are on: it replaces the printer's video
  6258. (usually there first; stitching takes minutes) and that file is deleted,
  6259. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6260. the run the frames were taken for: when the archive is printing again by
  6261. the time the stitch is done, the video is not the new run's and is
  6262. dropped. The stitched file is a temporary either way.
  6263. """
  6264. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6265. logger = logging.getLogger(__name__)
  6266. try:
  6267. async with async_session() as db:
  6268. service = ArchiveService(db)
  6269. archive = await service.get_archive(archive_id)
  6270. if archive is None:
  6271. return
  6272. if archive.started_at != run_started_at:
  6273. logger.info(
  6274. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6275. )
  6276. return
  6277. replaced = archive.timelapse_path
  6278. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6279. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6280. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  6281. return
  6282. attached = archive.timelapse_path
  6283. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6284. if replaced and replaced != attached:
  6285. try:
  6286. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6287. except PathTraversalError:
  6288. return
  6289. await asyncio.to_thread(old.unlink, missing_ok=True)
  6290. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6291. finally:
  6292. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6293. # ``run_started_at`` not given: attach whichever run the archive is on.
  6294. _ANY_RUN = object()
  6295. async def _attach_first_unclaimed_timelapse(
  6296. archive_id: int,
  6297. printer,
  6298. video_files: list[dict],
  6299. baseline_names: set[str],
  6300. claimed: set[str],
  6301. attempt: int,
  6302. logger: logging.Logger,
  6303. *,
  6304. quiet: bool = False,
  6305. require_unambiguous: bool = False,
  6306. plate_id: int | None = None,
  6307. run_started_at: datetime | None | object = _ANY_RUN,
  6308. ) -> bool:
  6309. """Download and attach the one video that belongs to this print.
  6310. A candidate is any file absent from the print-start baseline. More than one
  6311. can qualify when a previous print's video landed late, after this print's
  6312. baseline was taken — those are filtered out by name, because they are
  6313. already attached to another archive. Sorting the candidates instead would
  6314. mean sorting on mtime or on the filename timestamp, both of which come from
  6315. the printer's unsynced clock.
  6316. Returns True once a video is attached. The printer's copy is deleted only
  6317. after the attach succeeds on bytes whose length matched the listing.
  6318. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6319. already seen this exact listing — the poll runs for many rounds and only the
  6320. rounds where something changed are worth an INFO line.
  6321. """
  6322. from backend.app.services.bambu_ftp import (
  6323. DownloadDeadlineExceeded,
  6324. delete_archived_timelapse,
  6325. download_file_bytes_async,
  6326. remote_file_settled,
  6327. )
  6328. speak = logger.debug if quiet else logger.info
  6329. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6330. if not new_files:
  6331. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6332. return False
  6333. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6334. if not candidates:
  6335. speak(
  6336. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6337. attempt,
  6338. len(new_files),
  6339. )
  6340. return False
  6341. if len(candidates) > 1:
  6342. if require_unambiguous:
  6343. # The baseline is not evidence -- it was taken off a card that could
  6344. # not be read -- so "new since the baseline" does not narrow these
  6345. # down at all. Taking the first would attach an arbitrary video to
  6346. # this print and then delete it from the printer.
  6347. logger.warning(
  6348. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6349. "leaving all of them on the printer for manual selection",
  6350. attempt,
  6351. len(candidates),
  6352. ", ".join(str(f.get("name")) for f in candidates),
  6353. )
  6354. return False
  6355. logger.warning(
  6356. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6357. "the rest stay on the printer for manual selection",
  6358. attempt,
  6359. len(candidates),
  6360. ", ".join(str(f.get("name")) for f in candidates),
  6361. )
  6362. target = candidates[0]
  6363. file_name = str(target.get("name") or "") # every listed entry has one
  6364. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6365. logger.info(
  6366. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6367. attempt,
  6368. file_name,
  6369. archive_id,
  6370. )
  6371. # The listing always carries a size (`list_files` skips entries it can't
  6372. # parse), but read it explicitly: the delete below is destructive and must
  6373. # depend on a size we actually had, not on one we hoped was there.
  6374. expected_size = target.get("size")
  6375. try:
  6376. timelapse_data = await download_file_bytes_async(
  6377. printer.ip_address,
  6378. printer.access_code,
  6379. remote_path,
  6380. printer_model=printer.model,
  6381. expected_size=expected_size,
  6382. )
  6383. except DownloadDeadlineExceeded:
  6384. # Too slow for its size this round; the printer keeps its copy.
  6385. timelapse_data = None
  6386. if not timelapse_data:
  6387. # Short or failed transfer. The printer keeps its copy, so the next
  6388. # round can try again — which is exactly why the delete below is
  6389. # gated on a verified download.
  6390. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6391. return False
  6392. # The length check above proves we got what the listing said, not that the
  6393. # printer had finished writing. A video still being written can be listed
  6394. # short, served short, and pass — so confirm it has stopped growing before
  6395. # committing to it and deleting the original (#2704).
  6396. if not await remote_file_settled(
  6397. printer.ip_address,
  6398. printer.access_code,
  6399. remote_path,
  6400. len(timelapse_data),
  6401. printer_model=printer.model,
  6402. ):
  6403. return False
  6404. # Write phase: attach in a fresh short-lived session. The download took a
  6405. # while: by now the archive may have its video, or be printing again for a
  6406. # newer run, whose video this is not. Then nothing is attached or deleted,
  6407. # and the poll ends (True).
  6408. async with async_session() as db:
  6409. service = ArchiveService(db)
  6410. if run_started_at is not _ANY_RUN:
  6411. current = await service.get_archive(archive_id)
  6412. if current is None or current.timelapse_path or current.started_at != run_started_at:
  6413. logger.info(
  6414. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6415. "%s stays on the printer",
  6416. archive_id,
  6417. file_name,
  6418. )
  6419. return True
  6420. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  6421. if not success:
  6422. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6423. return False
  6424. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6425. await delete_archived_timelapse(
  6426. printer.ip_address,
  6427. printer.access_code,
  6428. remote_path,
  6429. verified=expected_size is not None,
  6430. printer_model=printer.model,
  6431. printer_name=printer.name,
  6432. )
  6433. return True
  6434. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6435. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6436. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6437. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6438. # How long the *background* upgrade keeps waiting after the notification has
  6439. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6440. # printer can't hold up the print-complete notification; this one exists so the
  6441. # archive still ends up with the better frame afterwards.
  6442. #
  6443. # Measured across 261 attaches in the support bundles, the video lands a median
  6444. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6445. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6446. # was 546s. Every other model was inside 26s. The long budget is therefore
  6447. # almost entirely for P1-series users; on everything else the short wait already
  6448. # wins and this task never runs.
  6449. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6450. async def _capture_finish_photo_from_timelapse(
  6451. archive_id: int,
  6452. archive_dir: Path,
  6453. timeout: float | None = None,
  6454. rotation: int = 0,
  6455. ) -> tuple[str | None, bool]:
  6456. """Wait for the per-print timelapse to land on the archive and extract its
  6457. last frame as the finish photo (#1397).
  6458. Bambu firmware stops timelapse recording after the toolhead parks but
  6459. before the bed-drop end-gcode runs, so the last frame frames the finished
  6460. print correctly. A live camera grab at gcode_state=FINISH captures the
  6461. bed already lowered.
  6462. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6463. ``archive.timelapse_path`` when the file lands. This function polls for
  6464. that field.
  6465. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6466. the wait ran out with no video on the archive yet — i.e. the video may
  6467. still be coming and a later attempt could succeed. It is False when the
  6468. video landed (whether or not extraction worked), because in that case
  6469. waiting longer changes nothing. The caller uses that to decide between
  6470. falling back permanently and scheduling a background upgrade.
  6471. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6472. still (#2708) so this source agrees with every other finish-photo source.
  6473. The archived video itself is the printer's own file and is left alone —
  6474. rotating it would mean re-encoding it.
  6475. """
  6476. import uuid
  6477. from backend.app.models.archive import PrintArchive
  6478. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6479. logger = logging.getLogger(__name__)
  6480. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6481. deadline = asyncio.get_event_loop().time() + budget
  6482. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6483. while True:
  6484. async with async_session() as db:
  6485. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6486. archive = result.scalar_one_or_none()
  6487. timelapse_relpath = archive.timelapse_path if archive else None
  6488. if timelapse_relpath:
  6489. video_path = app_settings.base_dir / timelapse_relpath
  6490. if video_path.exists() and video_path.stat().st_size > 0:
  6491. photos_dir = archive_dir / "photos"
  6492. photos_dir.mkdir(parents=True, exist_ok=True)
  6493. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6494. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6495. output_path = photos_dir / filename
  6496. if await extract_video_last_frame(video_path, output_path):
  6497. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6498. logger.info(
  6499. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6500. video_path.name,
  6501. archive_id,
  6502. )
  6503. return filename, False
  6504. logger.warning(
  6505. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6506. video_path.name,
  6507. archive_id,
  6508. )
  6509. return None, False
  6510. if asyncio.get_event_loop().time() >= deadline:
  6511. logger.info(
  6512. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6513. archive_id,
  6514. budget,
  6515. )
  6516. return None, True
  6517. await asyncio.sleep(poll_interval)
  6518. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6519. """Add the timelapse's last frame to an archive after the fact (#2704).
  6520. The print-complete notification waits only ~60s for the video, because
  6521. holding a notification for minutes is worse than sending it with a live
  6522. camera grab. On a P1-series printer the video often lands well after that,
  6523. so the archive used to be stuck with the live grab — which is taken at
  6524. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6525. the worse photo of the two.
  6526. This keeps waiting in the background and, when the video arrives, extracts
  6527. the frame and puts it *first* in the archive's photo list, so opening the
  6528. gallery shows it. The live grab is deliberately kept: the notification that
  6529. already went out links to that exact file, and deleting it would leave a
  6530. broken image in Discord or Telegram.
  6531. """
  6532. logger = logging.getLogger(__name__)
  6533. filename, _ = await _capture_finish_photo_from_timelapse(
  6534. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6535. )
  6536. if not filename:
  6537. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6538. return
  6539. try:
  6540. async with async_session() as db:
  6541. from backend.app.models.archive import PrintArchive
  6542. archive = await db.get(PrintArchive, archive_id)
  6543. if archive is None:
  6544. return
  6545. photos = list(archive.photos or [])
  6546. if filename in photos:
  6547. return
  6548. # Front of the list: PhotoGalleryModal opens at index 0.
  6549. archive.photos = [filename, *photos]
  6550. await db.commit()
  6551. except Exception as e:
  6552. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6553. return
  6554. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6555. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6556. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6557. """Put the filament-attribution context back after a restart mid-print.
  6558. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6559. both die with the process. The print keeps running, so at completion the
  6560. tracker would fall back to whatever the printer reports *now* — and AMS
  6561. filament backup makes "now" the substitute tray, charging the whole print
  6562. to the spool that only finished it.
  6563. The persisted row is only trusted when its print name still matches what
  6564. the printer says it is running: a row left behind by a completion we never
  6565. saw must not attach itself to the next print.
  6566. """
  6567. try:
  6568. from backend.app.api.routes.settings import get_setting
  6569. from backend.app.services.usage_tracker import (
  6570. clear_persisted_session,
  6571. get_persisted_ams_mapping,
  6572. get_persisted_print_name,
  6573. get_persisted_spool_change_log,
  6574. restore_session,
  6575. )
  6576. persisted_name = await get_persisted_print_name(db, printer_id)
  6577. current_name = (state.subtask_name or "").strip()
  6578. if persisted_name and current_name and persisted_name.strip() != current_name:
  6579. logger.info(
  6580. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6581. printer_id,
  6582. persisted_name,
  6583. current_name,
  6584. )
  6585. await clear_persisted_session(db, printer_id)
  6586. # Fall through to seeding: the print on the printer is real, it just
  6587. # isn't the one the row described.
  6588. persisted_log = None
  6589. else:
  6590. # Spoolman users get the tray-change log back but no in-memory
  6591. # session — see ``on_print_start`` on why that dict is load-bearing
  6592. # for the remain%-sync guard.
  6593. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6594. persisted_log = await restore_session(
  6595. db,
  6596. printer_id,
  6597. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6598. )
  6599. # The slot pills (#1762) read the mapping captured from the print
  6600. # command, which dies with the process as well. One this process
  6601. # has captured since is newer.
  6602. if state.print_ams_mapping is None:
  6603. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6604. # Spools swapped on a tray before the restart (#3325); anything this
  6605. # process has recorded since goes after them.
  6606. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6607. if persisted_swaps:
  6608. seen = getattr(state, "spool_change_log", None) or []
  6609. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6610. if persisted_log:
  6611. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6612. # Anything this process already observed goes after the persisted
  6613. # history — the log is ordered by layer, and a fresh process can
  6614. # only have seen changes from later in the print.
  6615. for entry in state.tray_change_log or []:
  6616. if tuple(entry) not in restored:
  6617. restored.append(tuple(entry))
  6618. state.tray_change_log = restored
  6619. tray_now = state.tray_now
  6620. if 0 <= tray_now <= 254:
  6621. if not state.tray_change_log:
  6622. # No persisted history — a print that started before this build,
  6623. # or before the row existed. Seed with the tray feeding right
  6624. # now so the remainder of the print is at least attributable to
  6625. # the right spool.
  6626. state.tray_change_log = [(tray_now, state.layer_num)]
  6627. logger.info(
  6628. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6629. printer_id,
  6630. tray_now,
  6631. state.layer_num,
  6632. )
  6633. # The tray handler updates ``last_loaded_tray`` on every push
  6634. # regardless of whether it logged a change, so re-align it to avoid
  6635. # a duplicate entry on the next push. Only ever with a real tray:
  6636. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6637. # 255" fallback, and writing 255 into it would defeat that.
  6638. state.last_loaded_tray = tray_now
  6639. except Exception:
  6640. # Never let attribution recovery cost the caller its timelapse
  6641. # baseline — that capture has to happen before the printer uploads
  6642. # the in-flight MP4 and there is no second chance at it.
  6643. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6644. async def on_print_running_observed(printer_id: int, data: dict):
  6645. """Restart-recovery for a print that started before Bambuddy came up.
  6646. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6647. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6648. creation). This hook restores the persisted archive into ``_active_prints``
  6649. and captures the timelapse baseline that normally hangs off print start.
  6650. Fires once per session, in lieu of on_print_start when restart-recovery
  6651. kicks in. The printer doesn't upload the timelapse until after PRINT
  6652. COMPLETE, so a baseline captured any time during the print is still
  6653. pre-upload.
  6654. """
  6655. logger = logging.getLogger(__name__)
  6656. async with async_session() as db:
  6657. from backend.app.models.printer import Printer
  6658. state = printer_manager.get_status(printer_id)
  6659. if state is not None:
  6660. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6661. if authorization is True:
  6662. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6663. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6664. await _restore_printable_objects(printer_id, state, db, logger)
  6665. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6666. printer = result.scalar_one_or_none()
  6667. if not printer:
  6668. logger.warning(
  6669. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6670. printer_id,
  6671. )
  6672. return
  6673. # Avoid double-capture: ownership reconciliation above must still run when
  6674. # a baseline already exists, but the camera work itself is one-shot.
  6675. if printer_id in _timelapse_baselines:
  6676. logger.debug(
  6677. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6678. printer_id,
  6679. )
  6680. return
  6681. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6682. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6683. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6684. against the printer's current MQTT state.
  6685. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6686. COMPLETE events, typically a print finishing during an MQTT disconnect
  6687. window followed by a smart-plug power cycle):
  6688. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6689. provably not running anymore — only branch that should fire under
  6690. normal disconnect-then-reconnect timing.
  6691. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6692. firmware mints a fresh ``subtask_id`` for each print, including the
  6693. ghost replay it runs after a power cycle from a leftover SD file —
  6694. so a mismatch unambiguously means the in-DB archive is no longer
  6695. the print on the printer.
  6696. 3. Printer is running but ``subtask_name`` is empty. The printer
  6697. doesn't know what it's running; the archive's reference to it is
  6698. already broken.
  6699. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6700. with matching subtask_id+subtask_name is left alone. The cost of a false
  6701. positive is a print closed while it still runs: the reconcile takes its
  6702. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6703. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6704. cost of a false negative is the ghost-print loop in #1542. What the
  6705. archive is closed as is ``_reconciled_outcome``'s call.
  6706. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6707. MQTT has connected but the first ``push_status`` response hasn't been
  6708. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6709. The reconcile caller in ``on_printer_status_change`` is already gated
  6710. on a real ``state.state``, so in normal operation this branch is
  6711. unreachable; it's kept as belt-and-braces for future callers and for
  6712. the narrow window where a partial state update could arrive
  6713. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6714. ``not stale`` on degenerate input is strictly conservative: a real
  6715. stale archive will still be caught by the next push_status arriving
  6716. with terminal state.
  6717. """
  6718. current_state = (state.state or "").upper()
  6719. if current_state in ("", "UNKNOWN"):
  6720. # No real push_status yet — PrinterState defaults are not evidence.
  6721. return False, ""
  6722. if current_state in ("IDLE", "FINISH", "FAILED"):
  6723. return True, f"printer state {current_state}"
  6724. # Below here the printer is in a running / pre-running state (RUNNING /
  6725. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6726. current_subtask_id = (state.subtask_id or "").strip()
  6727. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6728. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6729. current_subtask_name = (state.subtask_name or "").strip()
  6730. if not current_subtask_name:
  6731. return True, "printer subtask_name empty"
  6732. return False, ""
  6733. async def prime_kprofile_table(printer_id: int) -> int:
  6734. """Read the printer's calibration table once per connection.
  6735. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6736. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6737. report ``cali_idx`` and nothing else -- that number can only come from
  6738. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6739. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6740. backup, or the printer answering a query BambuStudio made on the report
  6741. topic we share. A Bambuddy that nobody visited showed a card with no K
  6742. values at all.
  6743. Only the diameters actually fitted are asked for, which is one request on a
  6744. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6745. what the backup does, and it is both wasteful and the thing that used to
  6746. blank the table.
  6747. Returns the number of nozzles whose table was read.
  6748. """
  6749. client = printer_manager.get_client(printer_id)
  6750. state = printer_manager.get_status(printer_id)
  6751. if client is None or state is None or not state.connected:
  6752. return 0
  6753. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6754. # ask once, and both entries are empty until the first push_status lands.
  6755. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6756. if not diameters:
  6757. logging.getLogger(__name__).debug(
  6758. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6759. printer_id,
  6760. )
  6761. return 0
  6762. primed = 0
  6763. for diameter in diameters:
  6764. try:
  6765. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6766. except Exception as exc: # noqa: BLE001
  6767. # A printer that won't answer costs the card its K values, nothing
  6768. # more — never the connection this runs on the back of.
  6769. logging.getLogger(__name__).warning(
  6770. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6771. )
  6772. continue
  6773. primed += 1
  6774. logging.getLogger(__name__).info(
  6775. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6776. )
  6777. return primed
  6778. def _sd_files_in_use(state) -> set[str]:
  6779. """Names of the SD-card files the printer may be printing right now (#3009).
  6780. The post-print cleanup works out what to delete from the finished archive,
  6781. not from the printer. When reconciliation closes an old archive because the
  6782. printer has moved on to a new job, and that job is the same file reprinted
  6783. from the printer's screen, the cleanup would delete the file mid-print.
  6784. Empty unless the printer is busy: on an ordinary completion the state is
  6785. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6786. name, a path or a URL depending on firmware, and some report only the
  6787. plate's G-code, so the job name is matched as well, in the same spellings
  6788. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6789. ignores case.
  6790. """
  6791. def _text(value) -> str:
  6792. return value.strip() if isinstance(value, str) else ""
  6793. if state is None:
  6794. return set()
  6795. current_state = _text(getattr(state, "state", None)).upper()
  6796. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6797. return set()
  6798. in_use: set[str] = set()
  6799. gcode_file = _text(getattr(state, "gcode_file", None))
  6800. if gcode_file:
  6801. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6802. # both legal in a file name, and raises on some inputs.
  6803. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6804. if name:
  6805. in_use.add(name.lower())
  6806. subtask_name = _text(getattr(state, "subtask_name", None))
  6807. if subtask_name:
  6808. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6809. for ext in (".3mf", ".gcode"):
  6810. in_use.add(f"{name}{ext}".lower())
  6811. return in_use
  6812. def _reconciled_outcome(archive, state) -> str:
  6813. """What a stale archive is closed as at reconnect (#3310).
  6814. A print that ends while Bambuddy restarts is never seen to end: the new
  6815. MQTT client's first status is already FINISH, which is not a transition.
  6816. The printer keeps reporting the finished job's ``subtask_id`` until the
  6817. next print, so a matching id proves the FINISH or FAILED is this
  6818. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  6819. started outside the cloud) or none -- says only that the print is over,
  6820. not how, and stays ``aborted``.
  6821. """
  6822. current_state = (state.state or "").upper()
  6823. if current_state not in ("FINISH", "FAILED"):
  6824. return "aborted"
  6825. archive_id = (archive.subtask_id or "").strip()
  6826. current_id = str(state.subtask_id or "").strip()
  6827. if archive_id in ("", "0") or archive_id != current_id:
  6828. return "aborted"
  6829. return "completed" if current_state == "FINISH" else "failed"
  6830. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  6831. """When a print reconciled as completed most likely ended, or None (#3310).
  6832. The printer does not say when it finished, and the reconnect can be hours
  6833. later. Its start plus the slicer's estimate for the plate it printed,
  6834. never later than now, is the best guess; None when either is missing,
  6835. and the run then keeps no duration, as an aborted one does.
  6836. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  6837. of another plate reuses the archive without changing ``archive.plate_id``.
  6838. """
  6839. started = archive.started_at
  6840. if not started:
  6841. return None
  6842. if started.tzinfo is None:
  6843. started = started.replace(tzinfo=timezone.utc)
  6844. plate = plate_id if plate_id is not None else archive.plate_id
  6845. estimate = None
  6846. if archive.file_path:
  6847. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  6848. full_path = (
  6849. app_settings.base_dir / archive.file_path
  6850. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6851. try:
  6852. estimate = extract_print_time_from_3mf(full_path, plate)
  6853. except Exception as exc: # noqa: BLE001
  6854. logging.getLogger(__name__).debug(
  6855. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  6856. )
  6857. if plate is None and estimate != archive.print_time_seconds:
  6858. # Without a plate the first plate's estimate is read. The archive
  6859. # carries the sum over all plates (#1593), so a difference means
  6860. # several plates and no telling which one printed.
  6861. estimate = None
  6862. elif plate is None:
  6863. # Nothing to read the plate from; the archive's own estimate, as for
  6864. # a single-plate file.
  6865. estimate = archive.print_time_seconds
  6866. if not estimate or estimate <= 0:
  6867. return None
  6868. return min(started + timedelta(seconds=int(estimate)), now)
  6869. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6870. """Synthesise ``on_print_complete`` for archives whose print can't be
  6871. running on the printer anymore.
  6872. Called once per MQTT (re)connection (from on_printer_status_change when
  6873. the connected edge flips False → True) and at Bambuddy startup (from
  6874. the FastAPI lifespan). Without this, a print that completes during a
  6875. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6876. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6877. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6878. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6879. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6880. closes the loop by faking the missed PRINT COMPLETE — the existing
  6881. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6882. and notifications.
  6883. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  6884. when the printer still reports the archive's own job as finished or
  6885. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  6886. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  6887. after a restart the printer's FINISH is not one (#3310).
  6888. Returns the number of archives reconciled.
  6889. """
  6890. state = printer_manager.get_status(printer_id)
  6891. if not state:
  6892. return 0
  6893. # Don't reconcile while disconnected — we'd be making a decision against
  6894. # stale cached state. The connected → reconcile edge handles this.
  6895. if not state.connected:
  6896. return 0
  6897. from backend.app.models.archive import PrintArchive
  6898. reconciled = 0
  6899. async with async_session() as db:
  6900. result = await db.execute(
  6901. select(PrintArchive).where(
  6902. PrintArchive.printer_id == printer_id,
  6903. PrintArchive.status == "printing",
  6904. )
  6905. )
  6906. active = list(result.scalars().all())
  6907. if not active:
  6908. return 0
  6909. # The plate each run printed, from its queue job (#3310).
  6910. from backend.app.models.print_queue import PrintQueueItem
  6911. async with async_session() as db:
  6912. plate_rows = await db.execute(
  6913. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  6914. PrintQueueItem.printer_id == printer_id,
  6915. PrintQueueItem.status == "printing",
  6916. PrintQueueItem.archive_id.in_([a.id for a in active]),
  6917. )
  6918. )
  6919. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  6920. logger = logging.getLogger(__name__)
  6921. for archive in active:
  6922. is_stale, reason = _is_active_archive_stale(archive, state)
  6923. if not is_stale:
  6924. continue
  6925. logger.info(
  6926. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6927. printer_id,
  6928. archive.id,
  6929. archive.filename,
  6930. reason,
  6931. )
  6932. # Synthesised payload: minimal fields the on_print_complete chain
  6933. # needs. `_reconciled` marker lets downstream code distinguish this
  6934. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6935. # metrics / debug logging). raw_data is the live printer state so
  6936. # the usage tracker can compare end-of-print remain% against the
  6937. # captured start values.
  6938. outcome = _reconciled_outcome(archive, state)
  6939. payload = {
  6940. "status": outcome,
  6941. "filename": archive.filename,
  6942. "subtask_name": archive.print_name or "",
  6943. "subtask_id": archive.subtask_id or "",
  6944. "raw_data": state.raw_data or {},
  6945. "_reconciled": True,
  6946. }
  6947. if outcome != "aborted":
  6948. # The printer's progress and layer are this job's, so a partial
  6949. # run is charged what it printed rather than nothing.
  6950. if state.progress:
  6951. payload["last_progress"] = state.progress
  6952. if state.layer_num:
  6953. payload["last_layer_num"] = state.layer_num
  6954. if outcome == "failed":
  6955. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  6956. if outcome == "completed":
  6957. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  6958. if ended:
  6959. payload["_reconciled_completed_at"] = ended
  6960. try:
  6961. await on_print_complete(printer_id, payload)
  6962. reconciled += 1
  6963. except Exception as e:
  6964. # Catch-all: a reconciliation failure must not block the
  6965. # printer's normal status flow. The archive stays in
  6966. # ``status="printing"`` and the next reconnect retries.
  6967. logger.warning(
  6968. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6969. archive.id,
  6970. e,
  6971. )
  6972. return reconciled
  6973. # #2547: clearance left between the nozzle and the top of the print when the
  6974. # plate is commanded back into camera framing. The nozzle is parked away from
  6975. # the part by then, so this is belt-and-braces against a max_z_height that
  6976. # under-reports (e.g. a slicer that excludes a final Z hop).
  6977. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6978. # How far below the restored position to drop the plate again afterwards, so
  6979. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6980. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6981. # on machines with less headroom.
  6982. _PLATE_PARK_DROP_MM = 100.0
  6983. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6984. # this axis, so it is a proven-safe speed for the full travel.
  6985. _PLATE_RESTORE_FEEDRATE = 600
  6986. # Time allowed for the plate to reach the restored position before the camera
  6987. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6988. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6989. # How long `_background_finish_photo` waits for this producer. Must cover the
  6990. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6991. # notification path's own photo wait so a slow producer degrades to a
  6992. # photo-less notification rather than a missed one. The chamber light's
  6993. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6994. # camera_light.MAX_DELAY_SECONDS stays below it.
  6995. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6996. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6997. """The ``_active_prints`` keys a finished print may be registered under.
  6998. Matching how they were registered in on_print_start. Shared by
  6999. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7000. to find the same binding.
  7001. """
  7002. possible_keys = []
  7003. # Try subtask_name variations first (most reliable for matching)
  7004. if subtask_name:
  7005. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7006. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7007. possible_keys.append((printer_id, subtask_name))
  7008. # Try filename variations
  7009. if filename:
  7010. # Extract just the filename if it's a path
  7011. fname = filename.split("/")[-1] if "/" in filename else filename
  7012. if fname.endswith(".3mf"):
  7013. possible_keys.append((printer_id, fname))
  7014. elif fname.endswith(".gcode"):
  7015. base_name = fname.rsplit(".", 1)[0]
  7016. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7017. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7018. possible_keys.append((printer_id, fname))
  7019. else:
  7020. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7021. possible_keys.append((printer_id, f"{fname}.3mf"))
  7022. possible_keys.append((printer_id, fname))
  7023. # Also try full path versions
  7024. if filename.endswith(".3mf"):
  7025. possible_keys.append((printer_id, filename))
  7026. elif filename.endswith(".gcode"):
  7027. base_name = filename.rsplit(".", 1)[0]
  7028. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7029. possible_keys.append((printer_id, filename))
  7030. else:
  7031. possible_keys.append((printer_id, f"{filename}.3mf"))
  7032. possible_keys.append((printer_id, filename))
  7033. return possible_keys
  7034. def _archive_name_forms(archive) -> set[str]:
  7035. """The names an archive could be echoed back as, in normalised form (#3240).
  7036. Its print name, and its filename with and without the 3MF extension.
  7037. """
  7038. forms = set()
  7039. if archive.print_name:
  7040. forms.add(_normalise_subtask_name(archive.print_name))
  7041. if archive.filename:
  7042. forms.add(_normalise_subtask_name(archive.filename))
  7043. for suffix in (".gcode.3mf", ".3mf"):
  7044. if archive.filename.lower().endswith(suffix):
  7045. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7046. forms.discard("")
  7047. return forms
  7048. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7049. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7050. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7051. from the plate recorded when the job was dispatched. Neither is touched:
  7052. ``on_print_complete`` pops both, which is why the finish-photo producer
  7053. calls this before its first await, while they are still there.
  7054. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7055. archive, or that it only knows by a name -- and on any error: the producer
  7056. calls this before the ``try`` that always releases the photo consumer, so
  7057. it must not raise.
  7058. """
  7059. try:
  7060. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7061. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7062. if archive_id is None:
  7063. return None, None
  7064. return archive_id, _print_plate_ids.get(archive_id)
  7065. except Exception:
  7066. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7067. return None, None
  7068. async def _max_z_for_current_print(
  7069. printer_id: int,
  7070. data: dict,
  7071. logger,
  7072. archive_id: int | None,
  7073. plate_id: int | None = None,
  7074. ) -> float | None:
  7075. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7076. This number becomes the target of a real Z move, so every step here refuses
  7077. rather than guesses. A height belonging to some *other* print is the one
  7078. failure that could drive the nozzle into the model: 20 mm carried onto a
  7079. 200 mm print would command the plate up through the part.
  7080. Three independent things therefore have to agree before a height is
  7081. returned:
  7082. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7083. when it started (see ``_bound_print``), never one found by name. A name
  7084. is not an identity: every plate of a multi-plate file shares one, and a
  7085. reprint reuses its archive row, so the newest archive with the right
  7086. name can be another plate of the same file. Support bundles show the
  7087. old name lookup doing exactly that (archive 288 for a print bound to
  7088. 169, 313 layers against 125), stopped only by the layer check below.
  7089. No binding, no move.
  7090. 2. **Identity.** The bound archive's name still has to be the finished
  7091. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7092. because the printer echoes spaces as underscores (#3240). Exact: not a
  7093. substring, and not the completion check's tolerance for a truncated
  7094. echo.
  7095. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7096. match the layer count the printer itself reported over MQTT for the print
  7097. that just ended. These come from genuinely different sources, so a
  7098. mismatch means the row is not this print, whatever its name says.
  7099. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7100. plate of a multi-plate file reuses the archive row without updating its
  7101. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7102. ``on_print_complete`` may already have flipped the status by the time we
  7103. run.
  7104. """
  7105. subtask_name = (data.get("subtask_name") or "").strip()
  7106. if not subtask_name:
  7107. # Nothing to identify the print by — refuse rather than fall back to
  7108. # "whatever ran last on this printer".
  7109. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7110. return None
  7111. if archive_id is None:
  7112. logger.info(
  7113. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7114. printer_id,
  7115. subtask_name,
  7116. )
  7117. return None
  7118. try:
  7119. from backend.app.models.archive import PrintArchive
  7120. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7121. async with async_session() as db:
  7122. result = await db.execute(
  7123. select(PrintArchive).where(
  7124. PrintArchive.id == archive_id,
  7125. PrintArchive.printer_id == printer_id,
  7126. PrintArchive.status.in_(("printing", "completed")),
  7127. PrintArchive.deleted_at.is_(None),
  7128. )
  7129. )
  7130. archive = result.scalar_one_or_none()
  7131. if archive is None or not archive.file_path:
  7132. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7133. return None
  7134. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7135. logger.warning(
  7136. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7137. printer_id,
  7138. archive_id,
  7139. subtask_name,
  7140. )
  7141. return None
  7142. client = printer_manager.get_client(printer_id)
  7143. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7144. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7145. logger.warning(
  7146. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7147. "— refusing to move the plate on a height that may not be this print's",
  7148. printer_id,
  7149. archive.id,
  7150. archive.total_layers,
  7151. reported_layers,
  7152. )
  7153. return None
  7154. # Stored relative to the data directory, like every other archive path
  7155. # (#3240: this read a `data_dir` setting that does not exist).
  7156. path = app_settings.base_dir / archive.file_path
  7157. plate = plate_id or archive.plate_id or 1
  7158. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7159. except Exception as e:
  7160. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7161. return None
  7162. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7163. """Raise the plate back into camera framing before the finish photo (#2547).
  7164. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7165. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7166. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7167. This commands an absolute ``G1 Z`` back to just above the last printed
  7168. layer.
  7169. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7170. clearance`` is a height the toolhead was physically at seconds earlier, so
  7171. it is inside the travel limits by construction and leaves the nozzle above
  7172. the part. It is also unambiguous across model families: Z is the
  7173. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7174. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7175. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7176. (#2579).
  7177. Returns True if the move was sent and waited out, False if it was skipped.
  7178. """
  7179. client = printer_manager.get_client(printer_id)
  7180. if client is None:
  7181. return False
  7182. # Re-read state immediately before commanding motion. If the queue has
  7183. # already started the next print, the printer is no longer ours to move.
  7184. state = getattr(client, "state", None)
  7185. if state is None or state.state != "FINISH":
  7186. logger.info(
  7187. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7188. printer_id,
  7189. getattr(state, "state", "unknown"),
  7190. )
  7191. return False
  7192. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7193. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7194. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7195. return False
  7196. logger.info(
  7197. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7198. printer_id,
  7199. target_z,
  7200. max_z_height,
  7201. _PLATE_RESTORE_CLEARANCE_MM,
  7202. _PLATE_RESTORE_SETTLE_SECONDS,
  7203. )
  7204. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7205. return True
  7206. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7207. """Drop the plate again after the finish photo (#2547).
  7208. Without this the user walks up to a finished print sitting just under the
  7209. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7210. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7211. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7212. print homes anyway.
  7213. """
  7214. client = printer_manager.get_client(printer_id)
  7215. state = getattr(client, "state", None) if client else None
  7216. if client is None or state is None or state.state != "FINISH":
  7217. return
  7218. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7219. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7220. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7221. """True if a queue item is about to take this printer (#2547).
  7222. The scheduler dispatches the next job the moment a print completes, and a
  7223. plate move interleaved with a print start is not a race worth having. The
  7224. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7225. this window; this closes the head of it.
  7226. """
  7227. try:
  7228. from backend.app.models.print_queue import PrintQueueItem
  7229. async with async_session() as db:
  7230. result = await db.execute(
  7231. select(PrintQueueItem.id)
  7232. .where(
  7233. PrintQueueItem.printer_id == printer_id,
  7234. PrintQueueItem.status.in_(("pending", "printing")),
  7235. )
  7236. .limit(1)
  7237. )
  7238. return result.scalar_one_or_none() is not None
  7239. except Exception as e:
  7240. # Fail closed: if we can't tell, don't move the plate.
  7241. logging.getLogger(__name__).debug(
  7242. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7243. )
  7244. return True
  7245. async def on_finish_photo_moment(printer_id: int, data: dict):
  7246. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7247. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7248. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7249. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7250. HMS halt, firmware variants). Grabs one frame via the same
  7251. external-camera / RTSP path the post-completion fallback uses, stores
  7252. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7253. ``_background_finish_photo`` consume the cached bytes when it runs.
  7254. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7255. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7256. set to Smooth (#1721). No force-on now means the user's explicit
  7257. timelapse=off in the slicer send dialog is respected.
  7258. """
  7259. logger = logging.getLogger(__name__)
  7260. trigger = data.get("trigger", "unknown")
  7261. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7262. logger.info(
  7263. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7264. printer_id,
  7265. trigger,
  7266. timelapse_was_active,
  7267. )
  7268. # If a timelapse is actively recording, skip the pre-capture — the
  7269. # post-completion path will extract the last frame from the recorded
  7270. # video, which still provides the best framing (toolhead parked,
  7271. # before bed drop) without the per-layer parking side effects.
  7272. if timelapse_was_active:
  7273. logger.info(
  7274. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7275. printer_id,
  7276. )
  7277. return
  7278. # #1790: register the producer-done event BEFORE the first await so the
  7279. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7280. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7281. # The `finally` below guarantees `set()` runs on every exit, including
  7282. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7283. producer_done = asyncio.Event()
  7284. _stage22_finish_in_flight[printer_id] = producer_done
  7285. # #3240: also before the first await. On the FINISH-state path
  7286. # `on_print_complete` is dispatched right behind us and pops both the
  7287. # print's archive binding and its plate; read here, they are still there.
  7288. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7289. # #2547: set once the plate has actually been raised, and read by the
  7290. # `finally` below. Declared out here so a failure anywhere after the move —
  7291. # a camera timeout, a DB error — still lowers the plate again.
  7292. restore_max_z: float | None = None
  7293. try:
  7294. async with async_session() as db:
  7295. from backend.app.api.routes.settings import get_setting
  7296. from backend.app.models.printer import Printer
  7297. capture_setting = await get_setting(db, "capture_finish_photo")
  7298. if capture_setting is not None and capture_setting.lower() != "true":
  7299. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7300. return
  7301. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7302. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7303. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7304. printer = result.scalar_one_or_none()
  7305. if printer is None:
  7306. logger.warning(
  7307. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7308. printer_id,
  7309. )
  7310. return
  7311. frame_bytes: bytes | None = None
  7312. # #2708: the banked frame arrives already rotated — it comes from
  7313. # `_capture_snapshot_for_notification`, which rotates before returning.
  7314. # Every other source below is a raw grab. Tracking which lets us store
  7315. # exactly one rotation in `_stage22_finish_frames` either way.
  7316. frame_already_rotated = False
  7317. # On the FINISH-state path the End G-code has already run, and two very
  7318. # different situations arrive here needing opposite answers.
  7319. #
  7320. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7321. # snippet may have ejected the plate — the scene in front of the camera
  7322. # is no longer the finished print, and no amount of moving the plate
  7323. # brings it back. Use the banked in-print frame instead.
  7324. #
  7325. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7326. # than the camera frames well, and the toolhead is parked out of the
  7327. # way. That is the *best* moment available on firmware that never emits
  7328. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7329. # back. Preferring the bank here unconditionally, as this code used to,
  7330. # is what shipped a mid-print photo with the toolhead over the part.
  7331. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7332. banked = _inprint_frame_bank.get(printer_id)
  7333. if banked:
  7334. frame_bytes = banked
  7335. frame_already_rotated = True
  7336. logger.info(
  7337. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7338. "frame (%d bytes) instead of a post-swap live grab",
  7339. len(banked),
  7340. )
  7341. else:
  7342. logger.warning(
  7343. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7344. "in-print bank is empty — falling back to a live grab, which may show a "
  7345. "swapped or empty plate",
  7346. printer_id,
  7347. )
  7348. # `restore_max_z` is set only once the plate is actually up, because the
  7349. # `finally` reads it to decide whether it owes a move back down.
  7350. #
  7351. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7352. # came up empty above: that machine may have just ejected its plate, and
  7353. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7354. # taking for a photo of a bed we already know may be bare.
  7355. if (
  7356. frame_bytes is None
  7357. and trigger == "finish_state"
  7358. and restore_plate_enabled
  7359. and not print_dispatch_context.end_gcode_injected(printer_id)
  7360. ):
  7361. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7362. if wants_restore is None:
  7363. logger.info(
  7364. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7365. printer_id,
  7366. )
  7367. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7368. logger.info(
  7369. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7370. printer_id,
  7371. )
  7372. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7373. restore_max_z = wants_restore
  7374. # Chamber light for the live capture below (#1655). The banked frame
  7375. # above was taken without it, like every in-print bank.
  7376. async with camera_light(printer if frame_bytes is None else None):
  7377. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7378. from backend.app.api.routes.camera import live_frame_for_capture
  7379. from backend.app.services.external_camera import capture_frame
  7380. # #2707: this used to collide with the live view and fail, which is
  7381. # how finish-photo notifications went out with no image attached.
  7382. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7383. defer, buffered = live_frame_for_capture(printer_id)
  7384. if defer:
  7385. frame_bytes = buffered
  7386. else:
  7387. frame_bytes = await capture_frame(
  7388. printer.external_camera_url,
  7389. printer.external_camera_type or "mjpeg",
  7390. snapshot_url=printer.external_camera_snapshot_url,
  7391. )
  7392. if frame_bytes:
  7393. logger.info(
  7394. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7395. len(frame_bytes),
  7396. )
  7397. elif frame_bytes is None:
  7398. from backend.app.api.routes.camera import get_buffered_frame
  7399. buffered = get_buffered_frame(printer_id)
  7400. if buffered:
  7401. frame_bytes = buffered
  7402. logger.info(
  7403. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7404. len(frame_bytes),
  7405. )
  7406. else:
  7407. from backend.app.services.camera import capture_camera_frame_bytes
  7408. frame_bytes = await capture_camera_frame_bytes(
  7409. ip_address=printer.ip_address,
  7410. access_code=printer.access_code,
  7411. model=printer.model,
  7412. timeout=15,
  7413. )
  7414. if frame_bytes:
  7415. logger.info(
  7416. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7417. len(frame_bytes),
  7418. )
  7419. if frame_bytes:
  7420. if not frame_already_rotated:
  7421. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7422. _stage22_finish_frames[printer_id] = frame_bytes
  7423. else:
  7424. logger.warning(
  7425. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7426. printer_id,
  7427. )
  7428. except Exception as e:
  7429. logger.warning(
  7430. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7431. printer_id,
  7432. e,
  7433. )
  7434. finally:
  7435. # #2547: we raised the plate, so we own lowering it — including when the
  7436. # capture above failed or threw partway through.
  7437. if restore_max_z is not None:
  7438. try:
  7439. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7440. except Exception as e:
  7441. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7442. # #1790: always unblock the consumer's bounded wait — whether we stored
  7443. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7444. # dict entry by the consumer doesn't affect signalling.
  7445. producer_done.set()
  7446. def _subtask_name_from_filename(filename: str) -> str:
  7447. """Recover the subtask name a print command would have carried for *filename*.
  7448. The dispatcher derives the printer-facing subtask name from the archive's
  7449. file name, so stripping the extensions back off gives the value MQTT echoes
  7450. on completion. Only the two extensions Bambuddy actually stores are removed,
  7451. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7452. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7453. """
  7454. name = PurePosixPath(filename).name
  7455. for suffix in (".3mf", ".gcode"):
  7456. if name.lower().endswith(suffix):
  7457. name = name[: -len(suffix)]
  7458. return name
  7459. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7460. """Whether the subtask name is the printed 3MF's own file name.
  7461. A print started from the printer's screen reports the same full name, with
  7462. its extension, as both subtask and file (#3009). A dispatched print reports
  7463. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7464. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7465. """
  7466. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7467. return False
  7468. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7469. # How the printer marks a subtask name it had to cut short. Observed on real
  7470. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7471. # (a name with multibyte characters came back at 98), so match the marker
  7472. # rather than a length.
  7473. _SUBTASK_TRUNCATION_MARKER = "..."
  7474. def _normalise_subtask_name(name: str) -> str:
  7475. """Canonical form for comparing a dispatched name against MQTT's echo.
  7476. The printer does not echo the name back verbatim: it substitutes
  7477. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7478. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7479. The 3MF lookup in this module has always known that -- it builds
  7480. space-to-underscore variants of every candidate filename, and its
  7481. directory search normalises both sides before comparing. This exists so
  7482. the completion check reads the same rule from the same place instead of
  7483. growing its own, which is exactly how it came to disagree (#2829).
  7484. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7485. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7486. are dropped after the substitution so both sides agree (#3241).
  7487. """
  7488. return name.strip().replace(" ", "_").strip("_").casefold()
  7489. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7490. """The 3MF files of the printer's folder listings that are this print's.
  7491. A file of the print's own name wins, in whichever folder. Only without one
  7492. is a file that merely contains the name taken, and then only when it is
  7493. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7494. candidates none can be told apart. Paths keep the listings' order.
  7495. """
  7496. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7497. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7498. if exact:
  7499. return exact
  7500. term = _normalise_subtask_name(search_term)
  7501. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7502. if len(partial) > 1:
  7503. logging.getLogger(__name__).info(
  7504. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7505. )
  7506. return []
  7507. return partial
  7508. def _subtask_names_match(expected: str, observed: str) -> bool:
  7509. """Whether two subtask names describe the same print.
  7510. Beyond the space/underscore substitution, the printer truncates long names
  7511. and marks the cut with ``...``. A truncated echo has to count as a match or
  7512. every print with a long name strands its queue item the same way.
  7513. """
  7514. expected_n = _normalise_subtask_name(expected)
  7515. observed_n = _normalise_subtask_name(observed)
  7516. if expected_n == observed_n:
  7517. return True
  7518. # Either side can be the truncated one: the printer truncates what it
  7519. # echoes, and an archive whose own filename was recorded from a previous
  7520. # truncated echo carries the marker too.
  7521. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7522. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7523. continue
  7524. # The full side has lost its edge underscores; a cut that lands right
  7525. # after one keeps it, so drop it here too (#3241). Nothing left before
  7526. # the marker is no evidence of anything, and must not match every name.
  7527. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7528. if kept and full.startswith(kept):
  7529. return True
  7530. return False
  7531. async def _queue_item_dispatched_name(db, item) -> str:
  7532. """The subtask name *item* was dispatched under, or "" when unknowable.
  7533. A row with no archive, or an archive with no file name, is unverifiable
  7534. rather than wrong; every caller answers that with its permissive branch.
  7535. """
  7536. if item.archive_id is None:
  7537. return ""
  7538. from backend.app.models.archive import PrintArchive
  7539. archive = await db.get(PrintArchive, item.archive_id)
  7540. if archive is None or not archive.filename:
  7541. return ""
  7542. return _subtask_name_from_filename(archive.filename)
  7543. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7544. """Whether this completion event is plausibly about *item*'s print.
  7545. The caller finds its queue row by printer and ``status='printing'`` alone,
  7546. which is all a completion event gives it -- there is no run identifier in
  7547. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7548. completion delivered for this printer closes whichever row happens to be
  7549. printing, however unrelated. Comparing the subtask name against the archive
  7550. the row was dispatched with costs one primary-key load and rules that out.
  7551. Deliberately permissive: it answers False only on a positive disagreement
  7552. between two names we actually have. A row with no archive, an archive with
  7553. no file name, or an event with no subtask name is unverifiable rather than
  7554. wrong, and refusing those would strand the item in ``printing`` and wedge
  7555. the printer's queue -- a worse failure than the one being prevented.
  7556. """
  7557. observed = (data.get("subtask_name") or "").strip()
  7558. if not observed or item.archive_id is None:
  7559. return True
  7560. from backend.app.models.archive import PrintArchive
  7561. archive = await db.get(PrintArchive, item.archive_id)
  7562. if archive is None or not archive.filename:
  7563. return True
  7564. expected = _subtask_name_from_filename(archive.filename)
  7565. if not expected or _subtask_names_match(expected, observed):
  7566. return True
  7567. logging.getLogger(__name__).warning(
  7568. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7569. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7570. "printing rather than closing a run this event is not about.",
  7571. item.id,
  7572. expected,
  7573. archive.id,
  7574. archive.filename,
  7575. observed,
  7576. )
  7577. return False
  7578. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7579. """Spend the 3MF download cache on a still-empty fallback archive.
  7580. ``on_print_complete`` drops the cache as its first act, which deletes the
  7581. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7582. print ran and the archive never got one, this is the last moment those bytes
  7583. exist (#2957).
  7584. """
  7585. logger = logging.getLogger(__name__)
  7586. names = [
  7587. n
  7588. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7589. if n
  7590. ]
  7591. for name in names:
  7592. try:
  7593. cached = get_cached_3mf(printer_id, name)
  7594. # The print has ended: its completion prices the archive, so no
  7595. # print-start estimate is scheduled to race it.
  7596. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7597. return
  7598. except Exception as e:
  7599. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7600. # Longest the print's end waits for its file to be deleted from the SD card
  7601. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7602. async def _cleanup_sd_card_after_print(
  7603. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7604. ) -> None:
  7605. """Delete a finished print's file from the printer's SD card."""
  7606. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7607. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7608. # auto-start files found in root on power cycle, causing ghost prints.
  7609. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7610. try:
  7611. if subtask_name:
  7612. archive_filename: str | None = None
  7613. async with async_session() as db:
  7614. from backend.app.models.archive import PrintArchive
  7615. from backend.app.models.printer import Printer
  7616. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7617. printer = result.scalar_one_or_none()
  7618. if archive_id:
  7619. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7620. archive_filename = archive_row.scalar_one_or_none()
  7621. if printer:
  7622. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7623. from backend.app.utils.filename import derive_remote_filename
  7624. # Primary candidate: the exact path the dispatcher uploaded to
  7625. # (derived from archive.filename via the same rule as upload).
  7626. # Without it, a library row that ended up with a doubled
  7627. # .gcode.3mf (#1542) leaves the real file behind because the
  7628. # subtask_name + ext fallbacks below don't match what's on the
  7629. # SD card. Fallbacks remain for archive-less prints (subtask
  7630. # never resolved to an archive) and for older naming variants.
  7631. candidate_paths: list[str] = []
  7632. if archive_filename:
  7633. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7634. for ext in (".3mf", ".gcode"):
  7635. fallback = f"/{subtask_name}{ext}"
  7636. if fallback not in candidate_paths:
  7637. candidate_paths.append(fallback)
  7638. # Three outcomes track across all candidates so the final log
  7639. # line reflects what actually happened. The A1 in #1721 always
  7640. # ends here with ``any_not_found=True`` and the others False
  7641. # — its firmware auto-cleans the SD card before our cleanup
  7642. # runs, every candidate FTP-DELE returns 550, and the old
  7643. # code burned 3 retries × 2 s × 3 candidates per print
  7644. # logging a misleading "may linger" WARNING on a successful
  7645. # print.
  7646. any_deleted = False
  7647. any_real_failure = False
  7648. any_not_found = False
  7649. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7650. for remote_path in candidate_paths:
  7651. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7652. logger.info(
  7653. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7654. remote_path,
  7655. printer.name,
  7656. )
  7657. continue
  7658. # Retry only the FAILED case — 550 NOT_FOUND will never
  7659. # recover by waiting, so a "file isn't here" answer
  7660. # advances immediately to the next candidate without
  7661. # consuming the retry budget.
  7662. for attempt in range(1, 4):
  7663. try:
  7664. delete_result = await delete_file_async(
  7665. printer.ip_address,
  7666. printer.access_code,
  7667. remote_path,
  7668. printer_model=printer.model,
  7669. )
  7670. except Exception as e:
  7671. delete_result = DeleteResult.FAILED
  7672. logger.warning(
  7673. "SD card cleanup attempt %d/3 raised for %s: %s",
  7674. attempt,
  7675. remote_path,
  7676. e,
  7677. )
  7678. if delete_result == DeleteResult.DELETED:
  7679. any_deleted = True
  7680. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7681. break
  7682. if delete_result == DeleteResult.NOT_FOUND:
  7683. any_not_found = True
  7684. break # 550 will not recover; try next candidate
  7685. # FAILED: real error — retry with backoff, then give up
  7686. if attempt < 3:
  7687. await asyncio.sleep(2)
  7688. else:
  7689. any_real_failure = True
  7690. logger.warning(
  7691. "SD card cleanup failed after 3 attempts for %s "
  7692. "(network/auth/transient error — file may linger on SD card)",
  7693. remote_path,
  7694. )
  7695. if not any_deleted and not any_real_failure and any_not_found:
  7696. # Every candidate said "not here." Either the printer
  7697. # firmware swept the SD card itself (common on A1) or the
  7698. # dispatcher's upload path doesn't match our candidate
  7699. # rule. Either way: nothing to clean up, no warning.
  7700. logger.debug(
  7701. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7702. "(printer likely self-cleaned)",
  7703. printer.name,
  7704. )
  7705. except Exception as e:
  7706. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7707. async def on_print_complete(printer_id: int, data: dict):
  7708. """Handle print completion - update the archive status.
  7709. The printer counts as printing until the print's usage is booked (or this
  7710. ends), so the AMS remain% weight sync can't charge it a second time while
  7711. the usage tracker works (WU-3). Marked before the first await.
  7712. """
  7713. from backend.app.services.usage_tracker import done_completing, mark_completing
  7714. mark_completing(printer_id)
  7715. try:
  7716. await _close_out_print(printer_id, data)
  7717. finally:
  7718. done_completing(printer_id)
  7719. async def _close_out_print(printer_id: int, data: dict):
  7720. import time
  7721. logger = logging.getLogger(__name__)
  7722. start_time = time.time()
  7723. def log_timing(section: str):
  7724. elapsed = time.time() - start_time
  7725. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7726. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7727. # A kill-switch stop sends its provider notification immediately. Keep the
  7728. # task so the later notification path can await it and avoid a duplicate;
  7729. # if that immediate attempt failed, the regular completion path retries.
  7730. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7731. # Last chance before the bytes go: if this print's archive is still an empty
  7732. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7733. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7734. # below deletes the file (#2957).
  7735. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7736. # A pending cool-off retry has nothing left to recover for — the cache is
  7737. # about to be dropped and the print is over.
  7738. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7739. if retry_task and not retry_task.done():
  7740. retry_task.cancel()
  7741. # Drop the 3MF download cache for this printer (#972). The print is over,
  7742. # nothing else legitimately needs the bytes; keeping them would only risk
  7743. # handing a stale file to the next print if it reuses the same name.
  7744. clear_3mf_cache(printer_id)
  7745. try:
  7746. ws_data = {
  7747. "status": data.get("status"),
  7748. "filename": data.get("filename"),
  7749. "subtask_name": data.get("subtask_name"),
  7750. "timelapse_was_active": data.get("timelapse_was_active"),
  7751. }
  7752. await ws_manager.send_print_complete(printer_id, ws_data)
  7753. log_timing("WebSocket send_print_complete")
  7754. except Exception as e:
  7755. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7756. # Capture user info before clearing (needed for print log entry)
  7757. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7758. # Clear current print user tracking (Issue #206)
  7759. printer_manager.clear_current_print_user(printer_id)
  7760. # If the user explicitly stopped this print from the queue UI the printer will
  7761. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7762. # correct "print stopped" notification/email is sent instead of a failure alert.
  7763. _raw_status = data.get("status", "completed")
  7764. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7765. logger.info(
  7766. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7767. _raw_status,
  7768. printer_id,
  7769. )
  7770. data = {**data, "status": "cancelled"}
  7771. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7772. logger.info(
  7773. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7774. _raw_status,
  7775. printer_id,
  7776. )
  7777. data = {**data, "status": "cancelled", "_kill_switch": True}
  7778. _user_stopped_printers.discard(printer_id)
  7779. _kill_switch_stopped.discard(printer_id)
  7780. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7781. # may have left material on the bed: a user can cancel ten hours into a
  7782. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7783. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7784. # `_user_stopped_printers` is only populated when the user stops via the
  7785. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7786. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7787. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7788. # Auto Off power cycles and Bambuddy restarts.
  7789. try:
  7790. notify_live_activities.print_finished(printer_id, data)
  7791. except Exception:
  7792. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7793. _final_status = data.get("status", "completed")
  7794. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7795. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7796. # MQTT relay - publish print complete
  7797. try:
  7798. printer_info = printer_manager.get_printer(printer_id)
  7799. if printer_info:
  7800. await mqtt_relay.on_print_complete(
  7801. printer_id,
  7802. printer_info.name,
  7803. printer_info.serial_number,
  7804. data.get("filename", ""),
  7805. data.get("subtask_name", ""),
  7806. data.get("status", "completed"),
  7807. )
  7808. except Exception:
  7809. pass # Don't fail print complete callback if MQTT fails
  7810. filename = data.get("filename", "")
  7811. subtask_name = data.get("subtask_name", "")
  7812. if not filename and not subtask_name:
  7813. # Which print ended can't be told: the printer reported no name since
  7814. # Bambuddy started (a print that failed while preparing, a calibration).
  7815. # Charge nothing, but close the print session, which otherwise kept the
  7816. # AMS weight sync off until the next print (AS-5). A print archived as
  7817. # running is closed and charged by the reconnect reconcile.
  7818. logger.warning("Print complete without filename or subtask_name")
  7819. try:
  7820. from backend.app.services.usage_tracker import discard_session
  7821. async with async_session() as db:
  7822. await discard_session(db, printer_id)
  7823. except Exception as e:
  7824. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7825. return
  7826. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7827. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7828. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7829. # Find the archive for this print
  7830. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7831. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7832. archive_id = None
  7833. for key in possible_keys:
  7834. archive_id = _active_prints.pop(key, None)
  7835. if archive_id:
  7836. _owned_print_archive_ids.discard(archive_id)
  7837. logger.info("Found archive %s with key %s", archive_id, key)
  7838. # Also clean up any other keys pointing to this archive
  7839. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7840. for k in keys_to_remove:
  7841. _active_prints.pop(k, None)
  7842. break
  7843. # The archive bound when the print started, before the name search below.
  7844. # Only this one may give the finish-photo plate restore a height (#3240):
  7845. # the search matches names by substring.
  7846. bound_archive_id = archive_id
  7847. if not archive_id:
  7848. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7849. async with async_session() as db:
  7850. from backend.app.models.archive import PrintArchive
  7851. # Try matching by subtask_name (stored as print_name) first. The
  7852. # same name rule as the queue's completion check: a name inside
  7853. # another ("Clip" in "Cable Clip") is a different print, and the
  7854. # printer's underscores for spaces and truncation still match.
  7855. if subtask_name:
  7856. printing = await db.scalars(
  7857. select(PrintArchive)
  7858. .where(PrintArchive.printer_id == printer_id)
  7859. .where(PrintArchive.status == "printing")
  7860. .order_by(PrintArchive.created_at.desc())
  7861. )
  7862. # A print started from the printer's screen reports its file
  7863. # name, extensions included, as the subtask (#3009).
  7864. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7865. archive = next(
  7866. (
  7867. candidate
  7868. for candidate in printing
  7869. if any(
  7870. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7871. or (
  7872. candidate.filename
  7873. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7874. )
  7875. for name in reported
  7876. )
  7877. ),
  7878. None,
  7879. )
  7880. if archive:
  7881. archive_id = archive.id
  7882. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7883. # Also try by filename
  7884. if not archive_id and filename:
  7885. result = await db.execute(
  7886. select(PrintArchive)
  7887. .where(PrintArchive.printer_id == printer_id)
  7888. .where(PrintArchive.filename == filename)
  7889. .where(PrintArchive.status == "printing")
  7890. .order_by(PrintArchive.created_at.desc())
  7891. .limit(1)
  7892. )
  7893. archive = result.scalar_one_or_none()
  7894. if archive:
  7895. archive_id = archive.id
  7896. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7897. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7898. # closed below. The stranded-job closer gives up after five and closed it
  7899. # first, so the job's auto-off and its billing never ran. Inline rather
  7900. # than in the background, so the next job of the same file isn't released
  7901. # (and uploaded under the name being deleted) while the cleanup still
  7902. # works on it. A delete already sent may still finish in its FTP thread
  7903. # after the cutoff, as one past delete_file_async's own timeout always did.
  7904. try:
  7905. await asyncio.wait_for(
  7906. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7907. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7908. )
  7909. except TimeoutError:
  7910. logger.warning(
  7911. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7912. printer_id,
  7913. _SD_CLEANUP_BUDGET_SECONDS,
  7914. )
  7915. log_timing("SD card cleanup")
  7916. # Update queue item status early — must run before the archive_id early-return
  7917. # so queue items don't get stuck in "printing" when archive lookup fails.
  7918. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7919. queue_item_id = None
  7920. billing_run_id: str | None = None
  7921. billing_user_id: int | None = None
  7922. billing_cost_center_id: int | None = None
  7923. billing_plate_id: int | None = None
  7924. queue_status = None
  7925. queue_auto_off = False
  7926. try:
  7927. from backend.app.core.database import run_with_retry
  7928. from backend.app.models.print_queue import PrintQueueItem
  7929. async def _update_queue_status(db):
  7930. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7931. nonlocal queue_item_id, queue_status, queue_auto_off
  7932. result = await db.execute(
  7933. select(PrintQueueItem)
  7934. .where(PrintQueueItem.printer_id == printer_id)
  7935. .where(PrintQueueItem.status == "printing")
  7936. )
  7937. printing_items = list(result.scalars().all())
  7938. if len(printing_items) > 1:
  7939. logger.warning(
  7940. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7941. printer_id,
  7942. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7943. )
  7944. item = printing_items[0] if printing_items else None
  7945. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7946. return
  7947. if item:
  7948. queue_status = data.get("status", "completed")
  7949. # MQTT sends "aborted" for cancelled prints; normalise to
  7950. # "cancelled" so it matches the queue schema Literal.
  7951. if queue_status == "aborted":
  7952. queue_status = "cancelled"
  7953. item.status = queue_status
  7954. item.completed_at = datetime.now(timezone.utc)
  7955. if queue_status == "failed" and not item.error_message:
  7956. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7957. # Bump usage counters on the source library file so admins can
  7958. # sort by "last printed" and (eventually) auto-purge stale
  7959. # files — #1008.
  7960. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7961. await db.commit()
  7962. queue_item_id = item.id
  7963. billing_run_id = item.billing_run_id
  7964. billing_user_id = item.created_by_id
  7965. billing_cost_center_id = item.cost_center_id
  7966. billing_plate_id = item.plate_id
  7967. queue_auto_off = item.auto_off_after
  7968. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7969. await run_with_retry(_update_queue_status, label="queue status update")
  7970. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7971. # their own sessions and have their own error handling — no retry needed.
  7972. if queue_item_id is not None:
  7973. # Batch orders (#342): this run may have been the last one an order
  7974. # owed. Re-evaluate here rather than lazily on read, so a finished
  7975. # order reports itself complete without someone opening the page.
  7976. try:
  7977. from backend.app.services.print_batch import refresh_batch_status_for_item
  7978. async with async_session() as db:
  7979. await refresh_batch_status_for_item(db, queue_item_id)
  7980. await db.commit()
  7981. except Exception as e:
  7982. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7983. # MQTT relay - publish queue job completed
  7984. try:
  7985. printer_info = printer_manager.get_printer(printer_id)
  7986. await mqtt_relay.on_queue_job_completed(
  7987. job_id=queue_item_id,
  7988. filename=filename or subtask_name,
  7989. printer_id=printer_id,
  7990. printer_name=printer_info.name if printer_info else "Unknown",
  7991. status=queue_status,
  7992. )
  7993. except Exception:
  7994. pass # Don't fail if MQTT fails
  7995. # Check if queue is now empty and send notification
  7996. try:
  7997. from sqlalchemy import func as sa_func
  7998. async with async_session() as db:
  7999. count_result = await db.execute(
  8000. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8001. )
  8002. pending_count = count_result.scalar() or 0
  8003. if pending_count == 0:
  8004. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8005. completed_result = await db.execute(
  8006. select(sa_func.count(PrintQueueItem.id)).where(
  8007. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8008. PrintQueueItem.completed_at >= today_start,
  8009. )
  8010. )
  8011. completed_count = completed_result.scalar() or 1
  8012. await notification_service.on_queue_completed(
  8013. completed_count=completed_count,
  8014. db=db,
  8015. )
  8016. except Exception:
  8017. pass # Don't fail if notification fails
  8018. # Handle auto_off_after - power off printer if the queue item opted
  8019. # in. Delegates to the smart-plug manager so the off honours each
  8020. # plug's configured strategy (time delay or temperature threshold),
  8021. # is cancelled if the printer starts printing again, and never cuts
  8022. # power on a loaded print (#1890). Previously an inline block here
  8023. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8024. # timeout regardless of print state — cutting a touchscreen reprint.
  8025. if queue_auto_off:
  8026. try:
  8027. async with async_session() as db:
  8028. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8029. except Exception as e:
  8030. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8031. except Exception as e:
  8032. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8033. log_timing("Queue item update")
  8034. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8035. # Must run before archive_id early-return so it fires for all prints (including
  8036. # prints started from BambuStudio/touchscreen that have no archive).
  8037. if data.get("status") == "completed":
  8038. try:
  8039. from backend.app.api.routes.settings import get_setting
  8040. async with async_session() as db:
  8041. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8042. threshold = float(threshold_str) if threshold_str else 35.0
  8043. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8044. async with async_session() as db:
  8045. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8046. if providers:
  8047. _bed_cool_waiters[printer_id] = {
  8048. "threshold": threshold,
  8049. "filename": filename or subtask_name or "",
  8050. "registered_at": time.time(),
  8051. }
  8052. logger.info(
  8053. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8054. printer_id,
  8055. threshold,
  8056. )
  8057. else:
  8058. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8059. except Exception as e:
  8060. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8061. # Capture the slicer estimate before usage tracking runs. The tracker may
  8062. # update archive.cost with this run's measured cost; billing partial runs
  8063. # against that already-partial value would discount the charge twice.
  8064. billing_planned_grams: float | None = None
  8065. billing_base_cost: float | None = None
  8066. if archive_id:
  8067. try:
  8068. async with async_session() as db:
  8069. from backend.app.models.archive import PrintArchive
  8070. billing_archive = await db.get(PrintArchive, archive_id)
  8071. if billing_archive:
  8072. billing_path = (
  8073. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8074. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8075. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8076. billing_archive,
  8077. billing_path,
  8078. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  8079. )
  8080. except Exception as e:
  8081. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8082. # --- Track filament consumption (must run before archive_id early-return so usage
  8083. # is recorded even when auto-archive is disabled) ---
  8084. usage_results: list[dict] = []
  8085. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8086. stored_ams_mapping = data.get("ams_mapping")
  8087. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8088. # Drained either way, like the plate below: left over, it would be read by
  8089. # the archive's next run, dispatched without a mapping.
  8090. registered_ams_mapping = _print_ams_mappings.pop(archive_id, None) if archive_id else None
  8091. if not stored_ams_mapping:
  8092. stored_ams_mapping = registered_ams_mapping
  8093. # Always drain the plate_id register on completion — the session already
  8094. # consumed it at print-start injection; leaving it would leak into the next
  8095. # print on the same archive_id (rare but possible with reprints) (#1697).
  8096. # Capture the popped value so the completion notification can scope the
  8097. # archive-level (summed-across-plates per #1593) filament + time totals
  8098. # down to the single plate that was actually printed (#1785).
  8099. notify_plate_id: int | None = None
  8100. if archive_id:
  8101. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  8102. # The start estimate must not outlive the real cost written below (COST-4).
  8103. if archive_id:
  8104. await _settle_archive_cost_estimate(archive_id)
  8105. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8106. try:
  8107. async with async_session() as db:
  8108. from backend.app.api.routes.settings import get_setting
  8109. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8110. if not _spoolman_on or _spoolman_on.lower() != "true":
  8111. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8112. async with async_session() as db:
  8113. usage_results = await usage_on_print_complete(
  8114. printer_id,
  8115. data,
  8116. printer_manager,
  8117. db,
  8118. archive_id=archive_id,
  8119. ams_mapping=stored_ams_mapping,
  8120. )
  8121. if usage_results:
  8122. await ws_manager.broadcast(
  8123. {
  8124. "type": "spool_usage_logged",
  8125. "printer_id": printer_id,
  8126. "usage": usage_results,
  8127. }
  8128. )
  8129. log_timing("Usage tracker")
  8130. except Exception as e:
  8131. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8132. # Drop the print-start context unconditionally — the Spoolman branch above
  8133. # skips the internal tracker entirely, so nothing else would clear what
  8134. # print start captured, and a row surviving its print would be restored
  8135. # onto the next one after a restart.
  8136. try:
  8137. from backend.app.services.usage_tracker import discard_session
  8138. async with async_session() as db:
  8139. await discard_session(db, printer_id)
  8140. except Exception as e:
  8141. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8142. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8143. # A partial run's cost from the Spoolman spools it was charged to; the
  8144. # built-in inventory's comes in usage_results.
  8145. spoolman_run_cost: float | None = None
  8146. if archive_id:
  8147. if data.get("status") == "completed":
  8148. try:
  8149. await _report_spoolman_usage(printer_id, archive_id)
  8150. log_timing("Spoolman usage report")
  8151. except Exception as e:
  8152. logger.warning("Spoolman usage reporting failed: %s", e)
  8153. else:
  8154. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8155. try:
  8156. async with async_session() as db:
  8157. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8158. printer_id,
  8159. archive_id,
  8160. db,
  8161. last_layer_num=data.get("last_layer_num"),
  8162. last_progress=data.get("last_progress"),
  8163. status=data.get("status") or "failed",
  8164. )
  8165. except Exception as e:
  8166. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8167. await _release_archived_spoolman_slots(printer_id)
  8168. log_timing("Filament usage tracking")
  8169. if not archive_id:
  8170. # The printer's own calibration run has no archive by design, so this
  8171. # arrives here every time one finishes. Returning before the no-archive
  8172. # notification keeps a calibration from being announced as a finished
  8173. # print. Everything above this point has already run — the plate-clear
  8174. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8175. # notification is skipped.
  8176. if is_internal_printer_job(filename, subtask_name):
  8177. logger.info(
  8178. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8179. filename,
  8180. subtask_name,
  8181. )
  8182. return
  8183. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8184. # Still send print-complete/failed/stopped notifications even without an archive.
  8185. # Try to enrich with queue/library-file data so user-specific emails work too.
  8186. async def _notify_no_archive():
  8187. try:
  8188. async with async_session() as db:
  8189. from backend.app.models.library import LibraryFile
  8190. from backend.app.models.print_queue import PrintQueueItem
  8191. from backend.app.models.printer import Printer
  8192. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8193. printer_obj = result.scalar_one_or_none()
  8194. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8195. # Only the queue item this completion itself closed (the
  8196. # reconciliation above, which checks the run belongs to it).
  8197. # A print started outside Bambuddy closed none, and must not
  8198. # borrow an earlier job's owner, email or times.
  8199. no_archive_data: dict | None = None
  8200. try:
  8201. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8202. if queue_item:
  8203. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8204. # How long it really ran, as the archive path reports it (#1198).
  8205. started = to_naive_utc(queue_item.started_at)
  8206. ended = to_naive_utc(queue_item.completed_at)
  8207. # Not for a completion reconciled at reconnect: it
  8208. # ended at an unknown time while the printer was
  8209. # offline, and "now" is the reconnect (DB-C9).
  8210. if (
  8211. not data.get("_reconciled")
  8212. and started
  8213. and ended
  8214. and (ended - started).total_seconds() > 0
  8215. ):
  8216. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8217. # Estimated time: the queue item caches it from its
  8218. # archive or library file; otherwise read the library
  8219. # file's metadata (LibraryFile has no column for it).
  8220. if queue_item.print_time_seconds:
  8221. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8222. elif queue_item.library_file_id:
  8223. lib_result = await db.execute(
  8224. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8225. )
  8226. lib_file = lib_result.scalar_one_or_none()
  8227. estimate = (
  8228. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8229. )
  8230. if estimate:
  8231. no_archive_data["print_time_seconds"] = estimate
  8232. except Exception as lookup_err:
  8233. logger.debug(
  8234. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8235. )
  8236. # Enrich with usage tracker results (captured in enclosing scope)
  8237. if usage_results:
  8238. if no_archive_data is None:
  8239. no_archive_data = {}
  8240. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8241. if total_from_usage > 0:
  8242. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8243. no_archive_data["usage_results"] = usage_results
  8244. # Try MQTT remaining_time for print duration when no queue/library data
  8245. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8246. mqtt_remaining = data.get("remaining_time")
  8247. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8248. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8249. ps = data.get("status", "completed")
  8250. logger.info(
  8251. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8252. )
  8253. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8254. await notification_service.on_print_complete(
  8255. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8256. )
  8257. else:
  8258. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8259. # Send user-specific email if we have a created_by_id
  8260. if no_archive_data and no_archive_data.get("created_by_id"):
  8261. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8262. await _dispatch_user_print_email(
  8263. ps,
  8264. no_archive_data["created_by_id"],
  8265. p_name,
  8266. raw_filename,
  8267. db,
  8268. )
  8269. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8270. except Exception as e:
  8271. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8272. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8273. await _discard_open_runs_of(printer_id)
  8274. return
  8275. log_timing("Archive lookup")
  8276. # Update archive status
  8277. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8278. try:
  8279. async with async_session() as db:
  8280. service = ArchiveService(db)
  8281. status = data.get("status", "completed")
  8282. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8283. if hms_errors:
  8284. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8285. failure_reason = derive_failure_reason(status, hms_errors)
  8286. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8287. # A reconciled completion closes out a stale archive at
  8288. # reconnect — it is not a user action, so don't mislabel it
  8289. # "userCancelled". It shares the stale-cleanup path's key
  8290. # (issue #2974) and records that the real end time is unknown,
  8291. # which is also why its logged duration is 0 (#2592). A failed
  8292. # one the printer's errors explain keeps their reason (#3310).
  8293. failure_reason = "noStatusUpdate"
  8294. elif data.get("_kill_switch"):
  8295. # Not the user's cancel: the kill switch stopped a print that did
  8296. # not come from Bambuddy.
  8297. failure_reason = "killSwitch"
  8298. if failure_reason:
  8299. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8300. elif status == "failed" and hms_errors:
  8301. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8302. await service.update_archive_status(
  8303. archive_id,
  8304. status=status,
  8305. completed_at=(
  8306. # A reconciled completed print ended at an estimated time,
  8307. # not at the reconnect (#3310).
  8308. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8309. if status in ("completed", "failed", "aborted", "cancelled")
  8310. else None
  8311. ),
  8312. failure_reason=failure_reason,
  8313. )
  8314. logger.info(
  8315. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8316. )
  8317. await ws_manager.send_archive_updated(
  8318. {
  8319. "id": archive_id,
  8320. "status": status,
  8321. }
  8322. )
  8323. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8324. # MQTT relay - publish archive updated
  8325. try:
  8326. await mqtt_relay.on_archive_updated(
  8327. archive_id=archive_id,
  8328. print_name=filename or subtask_name,
  8329. status=status,
  8330. )
  8331. except Exception:
  8332. pass # Don't fail if MQTT fails
  8333. except Exception as e:
  8334. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8335. # Continue with other operations even if archive update fails
  8336. log_timing("Archive status update")
  8337. # Apply finance wallet charge or release reservations once. For all partial
  8338. # terminal states (failed, aborted at the printer display, or cancelled via
  8339. # Bambuddy) use this run's measured spool delta, falling back to the last
  8340. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8341. # estimate and therefore cannot represent an interrupted run.
  8342. try:
  8343. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8344. async with async_session() as db:
  8345. from backend.app.models.archive import PrintArchive
  8346. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8347. archive = await db.get(PrintArchive, archive_id)
  8348. if archive and billing_run_id is None:
  8349. billing_run_id = getattr(archive, "billing_run_id", None)
  8350. if archive and archive.created_by_id is None and _print_user_info:
  8351. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8352. await db.flush()
  8353. run_status = data.get("status", "completed")
  8354. last_progress = data.get("last_progress")
  8355. if last_progress is None:
  8356. last_progress = data.get("progress")
  8357. actual_run_grams = _compute_run_filament_grams(
  8358. run_status,
  8359. billing_planned_grams,
  8360. last_progress,
  8361. usage_results,
  8362. )
  8363. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8364. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  8365. charged = await apply_print_charge_for_archive(
  8366. db,
  8367. archive_id,
  8368. charged_user_id=billing_user_id,
  8369. cost_center_id=(
  8370. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8371. ),
  8372. print_queue_id=queue_item_id,
  8373. print_run_id=billing_run_id,
  8374. base_cost_override=billing_base_cost,
  8375. filament_usage=filament_usage,
  8376. )
  8377. await db.commit()
  8378. if charged:
  8379. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8380. except Exception as e:
  8381. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8382. printer_info = printer_manager.get_printer(printer_id)
  8383. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8384. billing_filename = filename or subtask_name or "Unknown"
  8385. billing_error = str(e)
  8386. try:
  8387. await ws_manager.broadcast(
  8388. {
  8389. "type": "billing_charge_failed",
  8390. "printer_id": printer_id,
  8391. "printer_name": billing_printer_name,
  8392. "filename": billing_filename,
  8393. "archive_id": archive_id,
  8394. }
  8395. )
  8396. except Exception as notification_error:
  8397. logger.error(
  8398. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8399. archive_id,
  8400. notification_error,
  8401. )
  8402. async def _notify_billing_charge_failed() -> None:
  8403. try:
  8404. async with async_session() as notification_db:
  8405. await notification_service.on_billing_charge_failed(
  8406. printer_id,
  8407. billing_printer_name,
  8408. billing_filename,
  8409. archive_id,
  8410. billing_error,
  8411. notification_db,
  8412. )
  8413. except Exception as provider_error:
  8414. logger.error(
  8415. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8416. archive_id,
  8417. provider_error,
  8418. exc_info=True,
  8419. )
  8420. spawn_background_task(
  8421. _notify_billing_charge_failed(),
  8422. name=f"billing-charge-failed-{archive_id}",
  8423. )
  8424. log_timing("Finance charge update")
  8425. # Write independent print log entry (separate table, never touches archives)
  8426. # The run's id, for the energy work below: the archive's newest run is
  8427. # the one started last, which with plates of it on two printers need not
  8428. # be the one that just ended.
  8429. completed_run_id: int | None = None
  8430. try:
  8431. async with async_session() as db:
  8432. from backend.app.models.archive import PrintArchive
  8433. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8434. archive = await db.get(PrintArchive, archive_id)
  8435. if archive is None:
  8436. # Deleted while it printed: its run has nothing left to end on.
  8437. await discard_open_runs(db, printer_id)
  8438. await db.commit()
  8439. if archive:
  8440. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8441. # source archive row rather than creating a new one, so an
  8442. # archive that was auto-created from a printer-initiated
  8443. # print (created_by_id=NULL) would otherwise stay unattributed
  8444. # forever. When we have a print-session user AND the archive
  8445. # has no attribution yet, credit the current user. Never
  8446. # overwrite an existing attribution — the original uploader
  8447. # keeps ownership.
  8448. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8449. if archive.created_by_id is None and _print_user_id is not None:
  8450. archive.created_by_id = _print_user_id
  8451. p_info = printer_manager.get_printer(printer_id)
  8452. # Per-run actuals — written to PrintLogEntry so stats reflect
  8453. # what THIS print actually used, not the source archive's
  8454. # first-run values (#1378). Helper handles the partial-print
  8455. # math (failed / cancelled / stopped get scaled to progress
  8456. # or to tracked spool deltas).
  8457. _run_status = data.get("status", "completed")
  8458. # #2614: scope the per-run estimate to the printed plate. For a
  8459. # multi-plate 3MF dispatched one plate at a time, the archive's
  8460. # filament/cost are the whole-file totals; the PrintLogEntry must
  8461. # reflect only this plate. No effect on single-plate archives (the
  8462. # plate estimate equals the whole-file value) or on the tracker
  8463. # path (measured spool deltas win in _compute_run_filament_grams).
  8464. _est_full_path = (
  8465. app_settings.base_dir / archive.file_path if archive.file_path else None
  8466. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8467. # The plate that printed, as billing reads it: a reprint of
  8468. # another plate must not log the archive's first plate.
  8469. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8470. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8471. if _run_plate_id is None:
  8472. _run_plate_id = archive.plate_id
  8473. _run_grams = _compute_run_filament_grams(
  8474. _run_status,
  8475. _est_grams,
  8476. data.get("last_progress", data.get("progress")),
  8477. usage_results,
  8478. )
  8479. # Per-run cost — prefer usage_results sum. For partial prints
  8480. # we deliberately skip the topup-to-estimate logic in
  8481. # usage_tracker (which assumes the print completed); the raw
  8482. # tracked-spool sum is closer to what THIS run actually cost.
  8483. _run_cost: float | None = None
  8484. if usage_results:
  8485. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8486. if _run_cost is None and _run_status != "completed":
  8487. _run_cost = spoolman_run_cost
  8488. if _run_cost is None and _run_status == "completed":
  8489. _run_cost = _est_cost
  8490. from backend.app.models.printer import Printer as _Printer
  8491. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8492. run_entry = await write_log_entry(
  8493. db,
  8494. archive_id=archive.id,
  8495. # Captured by _update_queue_status above; None for
  8496. # printer-initiated prints with no queue row. Batch
  8497. # cost/energy roll-up joins on it (#342).
  8498. queue_item_id=queue_item_id,
  8499. status=_run_status,
  8500. print_name=archive.print_name,
  8501. # The plate this run printed, as the estimate above takes
  8502. # it; the archive's own is the latest run's.
  8503. plate_id=_run_plate_id,
  8504. printer_name=p_info.name if p_info else None,
  8505. printer_id=printer_id,
  8506. started_at=archive.started_at,
  8507. completed_at=archive.completed_at,
  8508. filament_type=archive.filament_type,
  8509. filament_color=archive.filament_color,
  8510. filament_used_grams=_run_grams,
  8511. cost=_run_cost,
  8512. wear_cost_per_hour=_wear_rate,
  8513. failure_reason=archive.failure_reason,
  8514. thumbnail_path=archive.thumbnail_path,
  8515. created_by_id=archive.created_by_id,
  8516. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8517. # Reconciled completions have an unknown real end time —
  8518. # log 0 duration instead of the whole disconnect gap (#2592),
  8519. # unless it was estimated (#3310).
  8520. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8521. # Its time is the estimate or nothing, never measured (#3310).
  8522. duration_unmeasured=bool(data.get("_reconciled")),
  8523. )
  8524. await record_archive_wear(db, archive, run_entry)
  8525. await db.commit()
  8526. completed_run_id = run_entry.id
  8527. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8528. except Exception as e:
  8529. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8530. log_timing("Print log entry")
  8531. # Run slow operations as background tasks to avoid blocking the event loop
  8532. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8533. async def _background_energy_calculation():
  8534. """Calculate and save energy usage in background.
  8535. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8536. backend restart no longer loses per-print energy data).
  8537. """
  8538. try:
  8539. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8540. async with async_session() as db:
  8541. from backend.app.models.archive import PrintArchive
  8542. archive = await db.get(PrintArchive, archive_id)
  8543. if archive is None:
  8544. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8545. return
  8546. starting_kwh = archive.energy_start_kwh
  8547. if starting_kwh is None:
  8548. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  8549. return
  8550. candidates = await energy_plug_candidates(db, printer_id)
  8551. if not candidates:
  8552. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8553. return
  8554. # Same ordering as the start reading, so the delta below is
  8555. # against the counter that produced `starting_kwh` (#2859).
  8556. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8557. if selected is None:
  8558. logger.warning(
  8559. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8560. printer_id,
  8561. ", ".join(plug.name for plug in candidates),
  8562. )
  8563. return
  8564. plug, energy = selected
  8565. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8566. energy_used = round(energy["total"] - starting_kwh, 4)
  8567. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8568. if energy_used < 0:
  8569. logger.warning(
  8570. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8571. archive_id,
  8572. starting_kwh,
  8573. energy["total"],
  8574. )
  8575. return
  8576. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8577. # Each hour of the print at the price of that hour (#1251). If
  8578. # that fails, the last price known, as before, rather than no
  8579. # energy at all. Read first: the session may be unusable after.
  8580. last_price = await stored_price(db)
  8581. try:
  8582. energy_cost_value = round(
  8583. await print_energy_cost(
  8584. db,
  8585. plug_id=archive.energy_start_plug_id,
  8586. start_at=archive.energy_start_at,
  8587. start_kwh=starting_kwh,
  8588. start_price=archive.energy_start_price,
  8589. end_kwh=energy["total"],
  8590. end_plug_id=plug.id,
  8591. price_now=await current_price(db),
  8592. ),
  8593. 3,
  8594. )
  8595. except Exception as e:
  8596. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8597. energy_cost_value = round(energy_used * last_price, 3)
  8598. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8599. # reprint doesn't visually clobber the source archive's energy data
  8600. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8601. from sqlalchemy import func
  8602. from backend.app.models.print_log import PrintLogEntry
  8603. existing_runs = await db.scalar(
  8604. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8605. )
  8606. if (existing_runs or 0) <= 1:
  8607. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8608. # we just wrote for THIS print. Either way it's the first run.
  8609. archive.energy_kwh = energy_used
  8610. archive.energy_cost = energy_cost_value
  8611. # Backfill the latest PrintLogEntry for this archive with energy
  8612. # (write_log_entry above ran before this background task completed,
  8613. # so energy fields are still NULL on that row).
  8614. if completed_run_id is not None:
  8615. run_row = await db.get(PrintLogEntry, completed_run_id)
  8616. else:
  8617. latest_run = await db.execute(
  8618. select(PrintLogEntry)
  8619. .where(PrintLogEntry.archive_id == archive_id)
  8620. .order_by(PrintLogEntry.id.desc())
  8621. .limit(1)
  8622. )
  8623. run_row = latest_run.scalar_one_or_none()
  8624. if run_row is not None:
  8625. run_row.energy_kwh = energy_used
  8626. run_row.energy_cost = energy_cost_value
  8627. await db.commit()
  8628. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8629. except Exception as e:
  8630. logger.warning("[ENERGY-BG] Failed: %s", e)
  8631. async def _background_finish_photo() -> str | None:
  8632. """Capture finish photo in background. Returns photo filename if captured."""
  8633. # #2547: set once this function has raised the plate itself (the
  8634. # timelapse path, where the moment producer returned without doing it).
  8635. # Declared out here so the `finally` can lower it again no matter where
  8636. # the capture below fails.
  8637. plate_restored_z: float | None = None
  8638. try:
  8639. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8640. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8641. # Read phase: settings + printer + archive in a short session, released
  8642. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8643. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8644. # tens of seconds; holding this session across it pinned one pooled
  8645. # connection idle-in-transaction per finishing print (issue #2572).
  8646. async with async_session() as db:
  8647. from backend.app.api.routes.settings import get_setting
  8648. from backend.app.models.archive import PrintArchive
  8649. from backend.app.models.printer import Printer
  8650. capture_enabled = await get_setting(db, "capture_finish_photo")
  8651. if capture_enabled is not None and capture_enabled.lower() != "true":
  8652. return None
  8653. if not archive_id:
  8654. return None
  8655. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8656. archive = (
  8657. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8658. ).scalar_one_or_none()
  8659. if not printer or not archive:
  8660. return None
  8661. import uuid
  8662. from datetime import datetime
  8663. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8664. if not archive.file_path:
  8665. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8666. archive_dir = resolve_archive_dir(archive)
  8667. photo_filename = None
  8668. # Prefer the timelapse last-frame source when a timelapse was
  8669. # recording — it captures the moment after the toolhead parks
  8670. # but before the bed drops, which the live-camera grab below
  8671. # would miss (#1397). Skipped for external cameras (those have
  8672. # their own framing and don't see a Bambu timelapse). Only
  8673. # runs when the USER explicitly enabled timelapse for this
  8674. # print — #1721 removed Bambuddy's force-on at dispatch
  8675. # because it caused per-layer nozzle parking on Smooth-mode
  8676. # slicer profiles.
  8677. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8678. printer.external_camera_enabled and printer.external_camera_url
  8679. )
  8680. timelapse_still_pending = False
  8681. if prefer_timelapse_source:
  8682. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8683. archive_id=archive_id,
  8684. archive_dir=archive_dir,
  8685. rotation=getattr(printer, "camera_rotation", 0),
  8686. )
  8687. # #1721: replacement framing path — on_finish_photo_moment
  8688. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8689. # parked, bed not yet dropped) and cached the JPEG bytes in
  8690. # _stage22_finish_frames. Consume them now so the saved photo
  8691. # has the better framing instead of the post-bed-drop angle
  8692. # the live-camera fallback below would give.
  8693. if not photo_filename:
  8694. # #1790: on the FINISH-state fallback path the producer
  8695. # task is dispatched back-to-back with this consumer, so
  8696. # a bare pop would race past with an empty result and
  8697. # the RTSP fallback below would collide with the
  8698. # producer's still-in-flight grab (single-client RTSP
  8699. # on Bambu printers). Wait for the producer to finish
  8700. # or give up before touching the cache.
  8701. #
  8702. # #2547: 20s was enough when the producer only ever grabbed a
  8703. # frame. It now also raises the plate first, which costs the
  8704. # settle window before the grab even starts — so the budget has
  8705. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8706. # under the notification's own photo wait below.
  8707. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8708. if in_flight is not None:
  8709. try:
  8710. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8711. except TimeoutError:
  8712. logger.warning(
  8713. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8714. printer_id,
  8715. )
  8716. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8717. if cached_frame:
  8718. # Already rotated by the producer (#2708) — rotating again
  8719. # here would undo the fix on the banked-frame path, whose
  8720. # bytes reach the cache having been rotated once already.
  8721. photos_dir = archive_dir / "photos"
  8722. photos_dir.mkdir(parents=True, exist_ok=True)
  8723. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8724. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8725. photo_path = photos_dir / photo_filename
  8726. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8727. logger.info(
  8728. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8729. photo_filename,
  8730. len(cached_frame),
  8731. )
  8732. # #2547: the timelapse path reaches the live grab below whenever the
  8733. # video hasn't landed in time — the documented usual outcome on
  8734. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8735. # returned early for those prints without raising the plate, so
  8736. # without this the photo that actually ships in the notification is
  8737. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8738. # asked us to fix. The archive still gets the better video frame
  8739. # later; this is about the image the user is sent.
  8740. #
  8741. # Gated on `timelapse_was_active` precisely because that is the
  8742. # condition under which the producer skipped. On every other path it
  8743. # has already raised and lowered the plate, and repeating that here
  8744. # would be a second pointless round trip.
  8745. if (
  8746. not photo_filename
  8747. and data.get("timelapse_was_active")
  8748. and not print_dispatch_context.end_gcode_injected(printer_id)
  8749. ):
  8750. try:
  8751. async with async_session() as db:
  8752. from backend.app.api.routes.settings import get_setting
  8753. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8754. if restore_setting is None or restore_setting.lower() == "true":
  8755. max_z = await _max_z_for_current_print(
  8756. printer_id, data, logger, bound_archive_id, notify_plate_id
  8757. )
  8758. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8759. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8760. plate_restored_z = max_z
  8761. except Exception as e:
  8762. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8763. # Fallback chain: external camera → buffered live frame →
  8764. # fresh RTSP capture. Only runs if the timelapse path above
  8765. # didn't already produce a photo.
  8766. # Chamber light for the live capture below (#1655).
  8767. async with camera_light(printer if not photo_filename else None):
  8768. if not photo_filename:
  8769. if printer.external_camera_enabled and printer.external_camera_url:
  8770. logger.info("[PHOTO-BG] Using external camera")
  8771. from backend.app.api.routes.camera import live_frame_for_capture
  8772. from backend.app.services.external_camera import capture_frame
  8773. # #2707: the second half of the finish-photo failure — the
  8774. # pre-capture and this fallback both collided with the live
  8775. # view. None here continues down the fallback chain.
  8776. defer, buffered = live_frame_for_capture(printer_id)
  8777. if defer:
  8778. frame_data = buffered
  8779. else:
  8780. frame_data = await capture_frame(
  8781. printer.external_camera_url,
  8782. printer.external_camera_type or "mjpeg",
  8783. snapshot_url=printer.external_camera_snapshot_url,
  8784. )
  8785. if frame_data:
  8786. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8787. photos_dir = archive_dir / "photos"
  8788. photos_dir.mkdir(parents=True, exist_ok=True)
  8789. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8790. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8791. photo_path = photos_dir / photo_filename
  8792. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8793. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8794. else:
  8795. # Check if camera stream is active - use buffered frame to avoid freeze
  8796. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8797. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8798. active_chamber_for_printer = [
  8799. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8800. ]
  8801. buffered_frame = get_buffered_frame(printer_id)
  8802. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8803. # Use frame from active stream
  8804. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8805. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8806. photos_dir = archive_dir / "photos"
  8807. photos_dir.mkdir(parents=True, exist_ok=True)
  8808. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8809. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8810. photo_path = photos_dir / photo_filename
  8811. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8812. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8813. else:
  8814. # No active stream - capture new frame
  8815. from backend.app.services.camera import capture_finish_photo
  8816. photo_filename = await capture_finish_photo(
  8817. printer_id=printer_id,
  8818. ip_address=printer.ip_address,
  8819. access_code=printer.access_code,
  8820. model=printer.model,
  8821. archive_dir=archive_dir,
  8822. rotation=getattr(printer, "camera_rotation", 0),
  8823. )
  8824. # Write phase: attach the photo in a fresh short-lived session.
  8825. if photo_filename:
  8826. async with async_session() as db:
  8827. from backend.app.models.archive import PrintArchive
  8828. arch = await db.get(PrintArchive, archive_id)
  8829. if arch is not None:
  8830. photos = arch.photos or []
  8831. photos.append(photo_filename)
  8832. arch.photos = photos
  8833. await db.commit()
  8834. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8835. # The short wait above is bounded so a slow printer can't hold up
  8836. # the print-complete notification, which is what the caller is
  8837. # blocking on. When it ran out with the video still on its way,
  8838. # keep waiting off to the side and add the better frame to the
  8839. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8840. # users, whose videos routinely take minutes to transfer, never get
  8841. # the pre-bed-drop framing this path exists to provide.
  8842. #
  8843. # Spawned here rather than at the point the wait gave up: both this
  8844. # function and the upgrade do a read-modify-write on `photos`, and
  8845. # the live-camera fallback above can take tens of seconds. Starting
  8846. # the upgrade before that write means the two can interleave and one
  8847. # silently drops the other's entry, leaving a JPEG on disk that the
  8848. # gallery never lists.
  8849. if timelapse_still_pending:
  8850. spawn_background_task(
  8851. _upgrade_finish_photo_from_timelapse(
  8852. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8853. ),
  8854. name=f"finish-photo-upgrade-{archive_id}",
  8855. )
  8856. return photo_filename
  8857. except Exception as e:
  8858. logger.warning("[PHOTO-BG] Failed: %s", e)
  8859. return None
  8860. finally:
  8861. # #2547: we raised the plate, so we owe the move back down — even if
  8862. # the capture in between threw. Otherwise the user finds the print
  8863. # pinned under the nozzle.
  8864. if plate_restored_z is not None:
  8865. try:
  8866. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8867. except Exception as e:
  8868. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8869. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8870. # Photo capture task - result will be used by notifications
  8871. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8872. log_timing("Background tasks scheduled (energy, photo)")
  8873. # Also run smart plug, notifications, and maintenance as background tasks
  8874. print_status = data.get("status", "completed")
  8875. async def _background_smart_plug():
  8876. """Handle smart plug automation in background."""
  8877. try:
  8878. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8879. async with async_session() as db:
  8880. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8881. logger.info("[AUTO-OFF-BG] Completed")
  8882. except Exception as e:
  8883. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8884. async def _background_notifications(finish_photo_filename: str | None = None):
  8885. """Send print complete notifications in background."""
  8886. try:
  8887. logger.info(
  8888. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8889. )
  8890. async with async_session() as db:
  8891. from backend.app.models.archive import PrintArchive
  8892. from backend.app.models.printer import Printer
  8893. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8894. printer = result.scalar_one_or_none()
  8895. printer_name = printer.name if printer else f"Printer {printer_id}"
  8896. archive_data = None
  8897. if archive_id:
  8898. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8899. archive = archive_result.scalar_one_or_none()
  8900. if archive:
  8901. # Actual elapsed time from started_at/completed_at when both are
  8902. # populated (every terminal status sets completed_at after #1198).
  8903. # Falls back to None so the notification path can decide whether to
  8904. # render the slicer estimate as a last resort.
  8905. actual_time_seconds = None
  8906. # Unknown for a completion reconciled at reconnect: the
  8907. # print ended while the printer was offline and
  8908. # completed_at is the reconnect, so the gap would read
  8909. # as the duration -- 14 h for a night offline (DB-C9).
  8910. # An estimated end (#3310) gives the estimate.
  8911. if (
  8912. archive.started_at
  8913. and archive.completed_at
  8914. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  8915. ):
  8916. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8917. if elapsed > 0:
  8918. actual_time_seconds = int(elapsed)
  8919. archive_data = {
  8920. "print_time_seconds": archive.print_time_seconds,
  8921. "actual_time_seconds": actual_time_seconds,
  8922. "actual_filament_grams": archive.filament_used_grams,
  8923. "failure_reason": archive.failure_reason,
  8924. "created_by_id": archive.created_by_id,
  8925. }
  8926. # Scale filament usage for partial prints
  8927. if print_status != "completed" and archive.filament_used_grams:
  8928. progress = data.get("progress") or 0
  8929. scale = _partial_progress_scale(progress)
  8930. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8931. archive_data["progress"] = progress
  8932. # Pass per-slot data from archive.extra_data
  8933. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8934. slots = archive.extra_data["filament_slots"]
  8935. if print_status != "completed":
  8936. scale = _partial_progress_scale(data.get("progress"))
  8937. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8938. archive_data["filament_slots"] = slots
  8939. # Scope project-summed totals down to the plate that was
  8940. # actually printed — see _scope_notification_archive_data_to_plate
  8941. # for the why (#1785).
  8942. archive_data = _scope_notification_archive_data_to_plate(
  8943. archive_data,
  8944. archive.file_path,
  8945. notify_plate_id,
  8946. print_status,
  8947. data.get("progress"),
  8948. app_settings.base_dir,
  8949. )
  8950. # Enrich filament_grams from usage_results when archive has no 3MF data
  8951. if not archive_data.get("actual_filament_grams") and usage_results:
  8952. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8953. if total_from_usage > 0:
  8954. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8955. # Pass usage tracker results for AMS slot info in notifications
  8956. if usage_results:
  8957. archive_data["usage_results"] = usage_results
  8958. # Add finish photo URL and image bytes if available
  8959. if finish_photo_filename:
  8960. photo_url, photo_bytes = await _finish_photo_for_notification(
  8961. db, archive, archive_id, finish_photo_filename
  8962. )
  8963. if photo_url:
  8964. archive_data["finish_photo_url"] = photo_url
  8965. if photo_bytes:
  8966. archive_data["image_data"] = photo_bytes
  8967. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8968. await notification_service.on_print_complete(
  8969. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8970. )
  8971. else:
  8972. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8973. # Post-print outcome confirmation (#1898). Runs in this
  8974. # background task so the finish photo fetched above rides
  8975. # along with the prompt.
  8976. if print_status == "completed" and archive_id:
  8977. await _dispatch_outcome_confirmation_safely(
  8978. db, printer_id, printer_name, data, archive_id, archive_data
  8979. )
  8980. # Send user-specific email notification
  8981. if archive_data:
  8982. created_by_id = archive_data.get("created_by_id")
  8983. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8984. await _dispatch_user_print_email(
  8985. print_status,
  8986. created_by_id,
  8987. printer_name,
  8988. raw_filename,
  8989. db,
  8990. image_data=archive_data.get("image_data"),
  8991. finish_photo_url=archive_data.get("finish_photo_url"),
  8992. )
  8993. logger.info("[NOTIFY-BG] Completed")
  8994. except Exception as e:
  8995. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8996. async def _background_maintenance_check():
  8997. """Check for maintenance due in background."""
  8998. if print_status != "completed":
  8999. return
  9000. try:
  9001. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9002. async with async_session() as db:
  9003. from backend.app.models.printer import Printer
  9004. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9005. printer = result.scalar_one_or_none()
  9006. printer_name = printer.name if printer else f"Printer {printer_id}"
  9007. await ensure_default_types(db)
  9008. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9009. attention = [
  9010. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9011. ]
  9012. items_needing_attention = [
  9013. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9014. for item in attention
  9015. ]
  9016. if items_needing_attention:
  9017. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9018. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9019. # MQTT relay - publish maintenance alerts
  9020. for item in attention:
  9021. current_value, threshold, unit = maintenance_alert_values(item)
  9022. try:
  9023. await mqtt_relay.on_maintenance_alert(
  9024. printer_id=printer_id,
  9025. printer_name=printer_name,
  9026. maintenance_type=item.maintenance_type_name,
  9027. current_value=current_value,
  9028. threshold=threshold,
  9029. unit=unit,
  9030. )
  9031. except Exception:
  9032. pass # Don't fail if MQTT fails
  9033. else:
  9034. logger.info("[MAINT-BG] Completed (no items need attention)")
  9035. except Exception as e:
  9036. logger.warning("[MAINT-BG] Failed: %s", e)
  9037. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9038. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9039. # Notification task waits for photo capture to complete first (with timeout).
  9040. # When a timelapse was recording, photo sourcing polls the per-print
  9041. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9042. # carries the correct bed-up photo instead of falling through to the
  9043. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9044. #
  9045. # #2547: both budgets now have to cover a plate restore as well.
  9046. #
  9047. # Without timelapse, the wait is on the moment producer, which raises the
  9048. # plate before its grab — so this has to outlast that producer's own budget.
  9049. #
  9050. # With timelapse, the capture polls up to
  9051. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9052. # falls back to a live grab, which is the case that raises the plate. At the
  9053. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9054. # restore would have moved the plate for a photo nobody waited for.
  9055. photo_wait_timeout = (
  9056. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9057. if data.get("timelapse_was_active")
  9058. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9059. )
  9060. async def _photo_then_notify():
  9061. """Wait for photo capture, then send notification with photo URL."""
  9062. finish_photo = None
  9063. try:
  9064. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9065. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9066. except TimeoutError:
  9067. logger.warning(
  9068. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9069. photo_wait_timeout,
  9070. )
  9071. except Exception as e:
  9072. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9073. try:
  9074. await _background_notifications(finish_photo)
  9075. except Exception as e:
  9076. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9077. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9078. # Stitch external camera layer timelapse if session was active
  9079. print_status = data.get("status", "completed")
  9080. async def _background_layer_timelapse():
  9081. """Stitch layer timelapse and attach to archive."""
  9082. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9083. try:
  9084. if print_status == "completed":
  9085. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9086. # The run the frames belong to, read before the stitch: it can
  9087. # take long enough for the archive to start printing again.
  9088. run_started_at = None
  9089. if archive_id:
  9090. async with async_session() as db:
  9091. run_archive = await ArchiveService(db).get_archive(archive_id)
  9092. run_started_at = run_archive.started_at if run_archive else None
  9093. timelapse_path = await tl_complete(printer_id)
  9094. if timelapse_path and archive_id:
  9095. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  9096. elif timelapse_path:
  9097. # Timelapse created but no archive - just clean up
  9098. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9099. else:
  9100. # Print failed or cancelled - cancel timelapse session
  9101. cancel_session(printer_id)
  9102. logger.info(
  9103. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9104. )
  9105. except Exception as e:
  9106. logger.warning("[LAYER-TL] Failed: %s", e)
  9107. # A completed print's session left _active_sessions when its stitch
  9108. # began: the one there now belongs to the next print, which may have
  9109. # started during the stitch, and must not lose its frames.
  9110. if print_status != "completed":
  9111. try:
  9112. cancel_session(printer_id)
  9113. except Exception:
  9114. pass # Best-effort timelapse session cancellation on error
  9115. layer_timelapse = _background_layer_timelapse()
  9116. if archive_id and print_status == "completed":
  9117. layer_timelapse = _mark_run_finishing(archive_id, layer_timelapse)
  9118. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9119. log_timing("All background tasks scheduled")
  9120. # Auto-scan for timelapse if recording was active during the print
  9121. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9122. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9123. # Schedule timelapse scan as background task with retries
  9124. # The printer needs time to encode the video after print completion
  9125. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id)
  9126. log_timing("Timelapse scan scheduled")
  9127. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9128. # AMS sensor history recording
  9129. _ams_history_task: asyncio.Task | None = None
  9130. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9131. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9132. def _retention_days(stored: str | None, default: int) -> int:
  9133. """A history retention setting as days to keep: at least 1, the default
  9134. when unset or unreadable. A stored 0 or less (the API took one before it
  9135. had a minimum) would put the cutoff at now and delete all history."""
  9136. try:
  9137. return max(1, int(stored)) if stored is not None else default
  9138. except (TypeError, ValueError):
  9139. return default
  9140. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9141. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9142. _ams_alarm_cooldown: dict[str, datetime] = {}
  9143. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9144. # (printer_id, ams_id) already reported as sending the drop index and no
  9145. # percentage. Logged once each so a supported printer that turns out to do this
  9146. # shows up in a support bundle rather than as a user wondering where the
  9147. # humidity reading went -- see the note at the read site below (#3140).
  9148. _ams_index_only_logged: set[tuple[int, int]] = set()
  9149. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9150. """Temperature at which the AMS alarm fires, falling back to the display band.
  9151. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9152. when a notification was sent as well, which is why a room above it made the
  9153. alarm fire once an hour for as long as the weather lasted -- and the only way
  9154. to stop that was to raise the display band and lose the colour that says the
  9155. unit is warm (#2905).
  9156. Unset resolves to the fair threshold, so an install that never sets one is
  9157. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9158. so that arrives here as a string and is handled by the same branch as any
  9159. other unparseable value -- there is no separate sentinel to keep in sync.
  9160. A non-positive value is refused rather than honoured: zero would alarm
  9161. permanently, and it is far more likely to be a cleared field than a
  9162. deliberate choice.
  9163. """
  9164. if raw_alarm_value is None:
  9165. return fair_threshold
  9166. try:
  9167. value = float(raw_alarm_value)
  9168. except (TypeError, ValueError):
  9169. return fair_threshold
  9170. if not math.isfinite(value) or value <= 0:
  9171. return fair_threshold
  9172. return value
  9173. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9174. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9175. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9176. # partway through a cool-down would otherwise resume alarming about heat the
  9177. # user asked for — the same internal-timestamp-row pattern as
  9178. # support.py's debug_logging_enabled_at.
  9179. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9180. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9181. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9182. # matters when it never does.
  9183. AMS_DRYING_GRACE_MINUTES = 120
  9184. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9185. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9186. Anything older than the grace cap would expire on its next visit anyway, so
  9187. discarding it here costs nothing and stops rows for deleted printers from
  9188. accumulating.
  9189. Stamps ahead of now get two defences, because a box whose clock jumps
  9190. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9191. ones are discarded outright, and the rest are clamped to now. Without the
  9192. clamp the cap would measure from a moment that has not happened yet and hold
  9193. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9194. after a clock jump is a far better failure than an alarm silently disabled
  9195. for hours.
  9196. """
  9197. from backend.app.models.settings import Settings
  9198. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9199. setting = result.scalar_one_or_none()
  9200. if not setting or not setting.value:
  9201. return {}
  9202. try:
  9203. raw = json.loads(setting.value)
  9204. except (ValueError, TypeError):
  9205. return {} # Corrupted row → no latch, alarms behave as they did before
  9206. if not isinstance(raw, dict):
  9207. return {}
  9208. now = datetime.now(timezone.utc)
  9209. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9210. latch: dict[str, datetime] = {}
  9211. for key, value in raw.items():
  9212. try:
  9213. stamp = datetime.fromisoformat(str(value))
  9214. except (ValueError, TypeError):
  9215. continue
  9216. if stamp.tzinfo is None:
  9217. stamp = stamp.replace(tzinfo=timezone.utc)
  9218. if not (now - window <= stamp <= now + window):
  9219. continue
  9220. # Nothing may sit in the future: suppression is measured as now minus
  9221. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9222. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9223. latch[str(key)] = min(stamp, now)
  9224. return latch
  9225. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9226. """Persist the latch, writing only when it actually changed.
  9227. Adds the session change but does not commit — the caller's own commit
  9228. carries it, so the latch lands in the same transaction as the sensor rows
  9229. that produced it.
  9230. """
  9231. from backend.app.models.settings import Settings
  9232. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9233. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9234. setting = result.scalar_one_or_none()
  9235. if setting is None:
  9236. # Don't create the row on installs that never dry anything.
  9237. if payload != "{}":
  9238. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9239. elif setting.value != payload:
  9240. setting.value = payload
  9241. def _ams_has_filament(ams_data: dict) -> bool:
  9242. """True if this AMS unit has at least one tray slot holding filament.
  9243. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9244. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9245. still report sensor readings, but those readings are ambient and not
  9246. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9247. humidity/temperature alarms on this check so empty units don't generate
  9248. hourly noise. Sensor history still records regardless so the UI charts
  9249. stay continuous.
  9250. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9251. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9252. """
  9253. bits = ams_data.get("tray_exist_bits")
  9254. if isinstance(bits, str) and bits.strip():
  9255. try:
  9256. return int(bits, 16) > 0
  9257. except ValueError:
  9258. pass
  9259. trays = ams_data.get("tray")
  9260. if isinstance(trays, list):
  9261. return any(
  9262. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9263. )
  9264. return False
  9265. async def record_ams_history():
  9266. """Background task to record AMS humidity and temperature data."""
  9267. logger = logging.getLogger(__name__)
  9268. # Wait a short time for MQTT connections to establish on startup
  9269. await asyncio.sleep(10)
  9270. while True:
  9271. try:
  9272. from backend.app.models.ams_history import AMSSensorHistory
  9273. from backend.app.models.printer import Printer
  9274. from backend.app.models.settings import Settings
  9275. async with async_session() as db:
  9276. # Get all active printers
  9277. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9278. printers = result.scalars().all()
  9279. # Get alarm thresholds from settings
  9280. humidity_threshold = 60.0 # Default: fair threshold
  9281. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9282. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9283. setting = result.scalar_one_or_none()
  9284. if setting:
  9285. try:
  9286. humidity_threshold = float(setting.value)
  9287. except (ValueError, TypeError):
  9288. pass # Keep default threshold if stored value is invalid
  9289. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9290. setting = result.scalar_one_or_none()
  9291. if setting:
  9292. try:
  9293. temp_fair_threshold = float(setting.value)
  9294. except (ValueError, TypeError):
  9295. pass # Keep default threshold if stored value is invalid
  9296. # The alarm gets its own threshold, seeded from the resolved fair
  9297. # value so an install that has never set one behaves exactly as
  9298. # it did before (#2905). ams_temp_fair decides when the card turns
  9299. # amber; 35 C is a reasonable place to change a colour and not a
  9300. # reasonable place to page someone. A room above it makes the
  9301. # alarm fire once an hour for as long as the weather lasts, and
  9302. # the only way to stop it was to raise the display band and lose
  9303. # the colour that says the unit is warm.
  9304. #
  9305. # An unset value is stored as the literal "None", which the except
  9306. # below swallows the same way it swallows garbage -- so the
  9307. # fallback costs nothing and needs no sentinel of its own.
  9308. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9309. setting = result.scalar_one_or_none()
  9310. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9311. temp_fair_threshold, setting.value if setting else None
  9312. )
  9313. # Per-filament humidity threshold overrides (#1605) — resolved
  9314. # per-AMS below from the loaded tray types. Reuses the same
  9315. # resolver as the auto-drying scheduler so behavior stays in
  9316. # lockstep across both consumers.
  9317. from backend.app.services.print_scheduler import PrintScheduler
  9318. per_type_humidity_thresholds: dict[str, int] = {}
  9319. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9320. setting = result.scalar_one_or_none()
  9321. if setting and setting.value:
  9322. try:
  9323. raw = json.loads(setting.value)
  9324. if isinstance(raw, dict):
  9325. for k, v in raw.items():
  9326. try:
  9327. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9328. v
  9329. )
  9330. except (TypeError, ValueError):
  9331. continue
  9332. except (ValueError, TypeError):
  9333. pass # Invalid JSON → no overrides, fall through to global threshold
  9334. # Per-AMS drying latch (#1802), loaded once per pass and written
  9335. # back below only if a unit changed it.
  9336. drying_latch = await _load_ams_drying_latch(db)
  9337. drying_latch_before = dict(drying_latch)
  9338. recorded_count = 0
  9339. for printer in printers:
  9340. # Get current state from printer manager
  9341. state = printer_manager.get_status(printer.id)
  9342. if not state or not state.connected or not state.raw_data:
  9343. continue # Skip disconnected printers - don't use stale data
  9344. raw_data = state.raw_data
  9345. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9346. continue
  9347. # Record data for each AMS unit
  9348. for ams_data in raw_data["ams"]:
  9349. ams_id = int(ams_data.get("id", 0))
  9350. # Percentage only. The 1-5 index is inverted, so
  9351. # charting it as a percentage drew the wettest units as
  9352. # the driest (#3140); a unit that reports no percentage
  9353. # leaves a gap in the chart instead. See
  9354. # utils/ams_humidity.
  9355. humidity = ams_humidity_percent(ams_data)
  9356. # No supported printer is known to send the index
  9357. # alone -- the report came from unsupported firmware,
  9358. # and no install has been seen using the old fallback.
  9359. # "Known" is doing work there, so say so once per unit:
  9360. # the alternative is a silent blank card.
  9361. if humidity is None and ams_data.get("humidity") is not None:
  9362. unit_key = (printer.id, ams_id)
  9363. if unit_key not in _ams_index_only_logged:
  9364. _ams_index_only_logged.add(unit_key)
  9365. logger.info(
  9366. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9367. "percentage. The index is inverted and is not shown as a percentage "
  9368. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9369. "Please report this with the printer and AMS firmware versions.",
  9370. printer.name,
  9371. ams_id,
  9372. )
  9373. # Get temperature
  9374. temperature = None
  9375. temp_str = ams_data.get("temp")
  9376. if temp_str is not None:
  9377. try:
  9378. temperature = float(temp_str)
  9379. except (ValueError, TypeError):
  9380. pass # Skip unparseable temperature value
  9381. # Skip if no data
  9382. if humidity is None and temperature is None:
  9383. continue
  9384. # Record the data point
  9385. history = AMSSensorHistory(
  9386. printer_id=printer.id,
  9387. ams_id=ams_id,
  9388. humidity=humidity,
  9389. # Both columns hold the same reading now that the
  9390. # index can no longer reach ``humidity``. Writing it
  9391. # through the same value also stops a genuine 0%
  9392. # from being stored as NULL, which the old truthiness
  9393. # test did.
  9394. humidity_raw=humidity,
  9395. temperature=temperature,
  9396. )
  9397. db.add(history)
  9398. recorded_count += 1
  9399. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9400. is_ams_ht = ams_id >= 128
  9401. if is_ams_ht:
  9402. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9403. else:
  9404. ams_label = f"AMS-{chr(65 + ams_id)}"
  9405. # Skip alarm dispatch for empty AMS units — humidity /
  9406. # temperature readings are ambient with no filament to
  9407. # protect, and the hourly notification just becomes
  9408. # noise. Sensor history was already recorded above so
  9409. # the UI charts stay continuous (#1619). Per-AMS check
  9410. # so a multi-AMS setup with one loaded + one empty
  9411. # still alarms on the loaded unit.
  9412. if not _ams_has_filament(ams_data):
  9413. continue
  9414. # Resolve per-filament humidity threshold for this AMS
  9415. # unit (#1605). Falls back to the global ams_humidity_fair
  9416. # when no per-type overrides are configured.
  9417. trays = ams_data.get("tray", []) or []
  9418. effective_humidity_threshold = float(
  9419. PrintScheduler.resolve_humidity_threshold(
  9420. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9421. )
  9422. )
  9423. # Check humidity alarm (only if above threshold)
  9424. if humidity is not None and humidity > effective_humidity_threshold:
  9425. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9426. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9427. now = datetime.now(timezone.utc)
  9428. if (
  9429. last_alarm is None
  9430. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9431. ):
  9432. _ams_alarm_cooldown[cooldown_key] = now
  9433. logger.info(
  9434. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9435. )
  9436. try:
  9437. # Call different notification method based on AMS type
  9438. if is_ams_ht:
  9439. await notification_service.on_ams_ht_humidity_high(
  9440. printer.id,
  9441. printer.name,
  9442. ams_label,
  9443. humidity,
  9444. effective_humidity_threshold,
  9445. db,
  9446. )
  9447. else:
  9448. await notification_service.on_ams_humidity_high(
  9449. printer.id,
  9450. printer.name,
  9451. ams_label,
  9452. humidity,
  9453. effective_humidity_threshold,
  9454. db,
  9455. )
  9456. except Exception as e:
  9457. logger.warning("Failed to send humidity alarm: %s", e)
  9458. # A drying cycle heats the unit far past ams_temp_fair on
  9459. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9460. # AMS-HT, against a 35 C default — so the alarm fired
  9461. # once an hour for the whole cycle and kept firing while
  9462. # the unit cooled back down (#1802). Latch on the
  9463. # firmware's own drying state and hold until the reading
  9464. # returns to normal. Humidity is deliberately left alone:
  9465. # it falls during drying, which is the whole point.
  9466. latch_key = f"{printer.id}:{ams_id}"
  9467. # The latch releases at `threshold`, so it takes the alarm
  9468. # number too. Handing it the display band would strand the
  9469. # latch on any unit that settles back above it -- a room
  9470. # where the AMS rests at 37.7 C never returns under a 35 C
  9471. # band, so the latch could only expire on the grace cap
  9472. # rather than releasing when the unit had actually cooled.
  9473. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9474. drying_active=is_drying_active(ams_data),
  9475. temperature=temperature,
  9476. threshold=temp_alarm_threshold,
  9477. latched_at=drying_latch.get(latch_key),
  9478. now=datetime.now(timezone.utc),
  9479. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9480. )
  9481. if new_latch is None:
  9482. drying_latch.pop(latch_key, None)
  9483. else:
  9484. drying_latch[latch_key] = new_latch
  9485. # Check temperature alarm (only if above threshold)
  9486. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9487. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9488. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9489. now = datetime.now(timezone.utc)
  9490. if (
  9491. last_alarm is None
  9492. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9493. ):
  9494. _ams_alarm_cooldown[cooldown_key] = now
  9495. logger.info(
  9496. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9497. f"{temperature}°C > {temp_alarm_threshold}°C"
  9498. )
  9499. try:
  9500. # Call different notification method based on AMS type
  9501. if is_ams_ht:
  9502. # The reported threshold has to be the one
  9503. # that fired, or the message says "> 35 °C"
  9504. # while firing at 45.
  9505. await notification_service.on_ams_ht_temperature_high(
  9506. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9507. )
  9508. else:
  9509. await notification_service.on_ams_temperature_high(
  9510. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9511. )
  9512. except Exception as e:
  9513. logger.warning("Failed to send temperature alarm: %s", e)
  9514. if drying_latch != drying_latch_before:
  9515. await _save_ams_drying_latch(db, drying_latch)
  9516. await db.commit()
  9517. if recorded_count > 0:
  9518. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9519. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9520. global _ams_cleanup_counter
  9521. _ams_cleanup_counter += 1
  9522. if _ams_cleanup_counter >= 288:
  9523. _ams_cleanup_counter = 0
  9524. # Get retention days from settings
  9525. from backend.app.models.settings import Settings
  9526. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9527. setting = result.scalar_one_or_none()
  9528. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9529. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9530. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9531. await db.commit()
  9532. if result.rowcount > 0:
  9533. logger.info(
  9534. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9535. )
  9536. # Wait until next recording interval
  9537. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9538. except asyncio.CancelledError:
  9539. break
  9540. except Exception as e:
  9541. logger.warning("AMS history recording failed: %s", e)
  9542. await asyncio.sleep(60) # Wait a bit before retrying
  9543. def start_ams_history_recording():
  9544. """Start the AMS history recording background task."""
  9545. global _ams_history_task
  9546. if _ams_history_task is None:
  9547. _ams_history_task = asyncio.create_task(record_ams_history())
  9548. logging.getLogger(__name__).info("AMS history recording started")
  9549. def stop_ams_history_recording():
  9550. """Stop the AMS history recording background task."""
  9551. global _ams_history_task
  9552. if _ams_history_task:
  9553. _ams_history_task.cancel()
  9554. _ams_history_task = None
  9555. logging.getLogger(__name__).info("AMS history recording stopped")
  9556. # Printer sensor history recording (nozzle / bed / chamber)
  9557. _printer_sensor_history_task: asyncio.Task | None = None
  9558. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9559. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9560. _printer_sensor_cleanup_counter = 0
  9561. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9562. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9563. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9564. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9565. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9566. _SENSOR_TARGET_KEYS = {
  9567. "nozzle": "nozzle_target",
  9568. "nozzle_2": "nozzle_2_target",
  9569. "bed": "bed_target",
  9570. "chamber": "chamber_target",
  9571. }
  9572. async def record_printer_sensor_history():
  9573. """Background task to record nozzle / bed / chamber readings.
  9574. Pulls from `state.temperatures` (already normalised across all printer
  9575. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9576. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9577. """
  9578. logger = logging.getLogger(__name__)
  9579. await asyncio.sleep(10)
  9580. while True:
  9581. try:
  9582. from backend.app.models.printer import Printer
  9583. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9584. from backend.app.models.settings import Settings
  9585. async with async_session() as db:
  9586. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9587. printers = result.scalars().all()
  9588. recorded_count = 0
  9589. for printer in printers:
  9590. state = printer_manager.get_status(printer.id)
  9591. if not state or not state.connected:
  9592. continue
  9593. temps = getattr(state, "temperatures", None) or {}
  9594. if not isinstance(temps, dict):
  9595. continue
  9596. for kind in _SENSOR_KINDS:
  9597. if kind not in temps:
  9598. continue
  9599. try:
  9600. value = float(temps[kind])
  9601. except (ValueError, TypeError):
  9602. continue
  9603. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9604. target_val: float | None = None
  9605. if target_raw is not None:
  9606. try:
  9607. target_val = float(target_raw)
  9608. except (ValueError, TypeError):
  9609. target_val = None
  9610. db.add(
  9611. PrinterSensorHistory(
  9612. printer_id=printer.id,
  9613. sensor_kind=kind,
  9614. value=value,
  9615. target=target_val,
  9616. )
  9617. )
  9618. recorded_count += 1
  9619. await db.commit()
  9620. if recorded_count > 0:
  9621. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9622. # Periodic cleanup — once every ~24h at this interval.
  9623. global _printer_sensor_cleanup_counter
  9624. _printer_sensor_cleanup_counter += 1
  9625. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9626. if _printer_sensor_cleanup_counter >= cleanup_every:
  9627. _printer_sensor_cleanup_counter = 0
  9628. result = await db.execute(
  9629. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9630. )
  9631. setting = result.scalar_one_or_none()
  9632. retention_days = _retention_days(
  9633. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9634. )
  9635. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9636. cleanup = await db.execute(
  9637. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9638. )
  9639. await db.commit()
  9640. if cleanup.rowcount > 0:
  9641. logger.info(
  9642. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9643. cleanup.rowcount,
  9644. retention_days,
  9645. )
  9646. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9647. except asyncio.CancelledError:
  9648. break
  9649. except Exception as e:
  9650. logger.warning("Printer sensor history recording failed: %s", e)
  9651. await asyncio.sleep(60)
  9652. def start_printer_sensor_history_recording():
  9653. global _printer_sensor_history_task
  9654. if _printer_sensor_history_task is None:
  9655. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9656. logging.getLogger(__name__).info("Printer sensor history recording started")
  9657. def stop_printer_sensor_history_recording():
  9658. global _printer_sensor_history_task
  9659. if _printer_sensor_history_task:
  9660. _printer_sensor_history_task.cancel()
  9661. _printer_sensor_history_task = None
  9662. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9663. # Printer runtime tracking
  9664. _runtime_tracking_task: asyncio.Task | None = None
  9665. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9666. # Printers the runtime tracker has seen connected since startup. One of them
  9667. # going offline clears its timestamp, so the time it was away is not counted
  9668. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9669. # connecting after a restart -- keeps it for a grace period: a print that ran
  9670. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9671. _runtime_seen_connected: set[int] = set()
  9672. # A printer never seen connected this long after the tracker started is
  9673. # offline, not still connecting: its stored timestamp predates a gap too.
  9674. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9675. async def track_printer_runtime():
  9676. """Background task to track printer active runtime (RUNNING state only).
  9677. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9678. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9679. which track mechanical wear. Pause time has no motion and no wear, so
  9680. counting it inflates maintenance warnings (#1521).
  9681. """
  9682. logger = logging.getLogger(__name__)
  9683. # Wait for MQTT connections to establish on startup
  9684. await asyncio.sleep(15)
  9685. started = time.monotonic()
  9686. while True:
  9687. try:
  9688. from backend.app.models.printer import Printer
  9689. # Fetch printer IDs in a short-lived read-only session
  9690. async with async_session() as db:
  9691. result = await db.execute(
  9692. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9693. Printer.is_active.is_(True)
  9694. )
  9695. )
  9696. printer_rows = result.all()
  9697. now = datetime.now(timezone.utc)
  9698. updated_count = 0
  9699. # Update each printer in its own short session to minimise write-lock
  9700. # hold time and avoid blocking critical commits like queue status
  9701. # updates (#897).
  9702. for pid, pname, runtime_secs, last_update in printer_rows:
  9703. state = printer_manager.get_status(pid)
  9704. if not state:
  9705. logger.debug("[%s] Runtime tracking: no state available", pname)
  9706. continue
  9707. if not state.connected:
  9708. logger.debug("[%s] Runtime tracking: not connected", pname)
  9709. offline = pid in _runtime_seen_connected or (
  9710. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9711. )
  9712. if offline and last_update is not None:
  9713. try:
  9714. async with async_session() as db:
  9715. printer = await db.get(Printer, pid)
  9716. if printer:
  9717. printer.last_runtime_update = None
  9718. await db.commit()
  9719. except Exception as e:
  9720. # Still marked: the next offline tick tries again.
  9721. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9722. continue
  9723. _runtime_seen_connected.discard(pid)
  9724. continue
  9725. _runtime_seen_connected.add(pid)
  9726. needs_commit = False
  9727. new_runtime = runtime_secs
  9728. new_last_update = last_update
  9729. if state.state == "RUNNING":
  9730. if last_update:
  9731. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9732. elapsed = (now - lu).total_seconds()
  9733. if elapsed > 0:
  9734. new_runtime = runtime_secs + int(elapsed)
  9735. updated_count += 1
  9736. needs_commit = True
  9737. logger.debug(
  9738. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9739. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9740. )
  9741. else:
  9742. needs_commit = True
  9743. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9744. new_last_update = now
  9745. else:
  9746. if last_update is not None:
  9747. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9748. new_last_update = None
  9749. needs_commit = True
  9750. if needs_commit:
  9751. try:
  9752. async with async_session() as db:
  9753. result = await db.execute(select(Printer).where(Printer.id == pid))
  9754. printer = result.scalar_one_or_none()
  9755. if printer:
  9756. printer.runtime_seconds = new_runtime
  9757. printer.last_runtime_update = new_last_update
  9758. await db.commit()
  9759. except Exception as e:
  9760. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9761. if updated_count > 0:
  9762. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9763. except asyncio.CancelledError:
  9764. logger.info("Runtime tracking cancelled")
  9765. break
  9766. except Exception as e:
  9767. logger.warning("Runtime tracking failed: %s", e)
  9768. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9769. def start_runtime_tracking():
  9770. """Start the printer runtime tracking background task."""
  9771. global _runtime_tracking_task
  9772. if _runtime_tracking_task is None:
  9773. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9774. logging.getLogger(__name__).info("Printer runtime tracking started")
  9775. def stop_runtime_tracking():
  9776. """Stop the printer runtime tracking background task."""
  9777. global _runtime_tracking_task
  9778. if _runtime_tracking_task:
  9779. _runtime_tracking_task.cancel()
  9780. _runtime_tracking_task = None
  9781. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9782. # SpoolBuddy device watchdog
  9783. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9784. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9785. async def _spoolbuddy_watchdog_loop():
  9786. """Periodic check for SpoolBuddy devices that have gone offline."""
  9787. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9788. while True:
  9789. try:
  9790. await spoolbuddy_watchdog()
  9791. except asyncio.CancelledError:
  9792. break
  9793. except Exception as e:
  9794. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9795. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9796. def start_spoolbuddy_watchdog():
  9797. global _spoolbuddy_watchdog_task
  9798. if _spoolbuddy_watchdog_task is None:
  9799. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9800. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9801. def stop_spoolbuddy_watchdog():
  9802. global _spoolbuddy_watchdog_task
  9803. if _spoolbuddy_watchdog_task:
  9804. _spoolbuddy_watchdog_task.cancel()
  9805. _spoolbuddy_watchdog_task = None
  9806. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9807. # Dead-MQTT-session recovery
  9808. #
  9809. # check_staleness() covers the "connected but silent" half-broken session. It
  9810. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9811. # is the only thing left watching at that point. When paho stops making
  9812. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9813. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9814. # offline with the UI open the whole time, recovered only when something
  9815. # happened to nudge it.
  9816. #
  9817. # This loop is that backstop. It only touches printers that had a working
  9818. # session and lost it, and only when the MQTT port still answers — a printer
  9819. # that is simply switched off is left to paho, since rebuilding a client
  9820. # against an unreachable host achieves nothing and would fill the log every
  9821. # night.
  9822. _connection_watchdog_task: asyncio.Task | None = None
  9823. CONNECTION_WATCHDOG_INTERVAL = 60
  9824. # How long a printer must have been silent before we stop trusting paho.
  9825. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9826. # so a session that is recovering on its own is never interrupted.
  9827. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9828. # Per-printer floor between rebuild attempts.
  9829. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9830. _connection_watchdog_last_attempt: dict[int, float] = {}
  9831. async def _recover_dead_printer_sessions() -> int:
  9832. """Rebuild MQTT clients that have been offline too long to still be trying.
  9833. Returns the number of printers a rebuild was attempted for (for tests and
  9834. for the caller's logging). Never raises: one unreachable printer must not
  9835. stop the sweep for the rest of the farm.
  9836. """
  9837. logger = logging.getLogger(__name__)
  9838. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9839. now = time.monotonic()
  9840. recovered = 0
  9841. for printer_id, client in list(printer_manager._clients.items()):
  9842. try:
  9843. if client.state.connected:
  9844. _connection_watchdog_last_attempt.pop(printer_id, None)
  9845. continue
  9846. # Time since the last inbound message is the age of the last known
  9847. # good session — no extra bookkeeping needed, and it is the same
  9848. # clock is_stale() reads. 0 means this client has never had one:
  9849. # that is the initial-connect path, where paho retrying is the
  9850. # correct and only behaviour, so leave it be.
  9851. last_msg = client._last_message_time
  9852. if not last_msg:
  9853. continue
  9854. offline_for = time.time() - last_msg
  9855. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9856. continue
  9857. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9858. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9859. continue
  9860. if not await check_port(client.ip_address, PORT_MQTT):
  9861. # Switched off, unplugged, or off the network. Paho's retry is
  9862. # the right handler; say so at debug level and move on.
  9863. logger.debug(
  9864. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9865. "— leaving the reconnect to paho",
  9866. printer_id,
  9867. offline_for,
  9868. )
  9869. _connection_watchdog_last_attempt[printer_id] = now
  9870. continue
  9871. _connection_watchdog_last_attempt[printer_id] = now
  9872. recovered += 1
  9873. logger.warning(
  9874. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9875. "rebuilding the client with a fresh session (last connect error: %s)",
  9876. printer_id,
  9877. offline_for,
  9878. PORT_MQTT,
  9879. client.last_connect_error or "none recorded",
  9880. )
  9881. # Async context, so this takes the hard-reset path: fresh client_id,
  9882. # paho's QoS 1 queue dropped. That matters — a project_file left
  9883. # unacked on the dead session would otherwise replay into the new
  9884. # one and trip 0500_4003 on the printer (#1136).
  9885. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9886. except Exception as e:
  9887. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9888. return recovered
  9889. async def _connection_watchdog_loop():
  9890. logger = logging.getLogger(__name__)
  9891. # Let the initial connects settle before judging anyone offline.
  9892. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9893. while True:
  9894. try:
  9895. await _recover_dead_printer_sessions()
  9896. except asyncio.CancelledError:
  9897. break
  9898. except Exception as e:
  9899. logger.warning("Connection watchdog sweep failed: %s", e)
  9900. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9901. def start_connection_watchdog():
  9902. global _connection_watchdog_task
  9903. if _connection_watchdog_task is None:
  9904. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9905. logging.getLogger(__name__).info("Printer connection watchdog started")
  9906. def stop_connection_watchdog():
  9907. global _connection_watchdog_task
  9908. if _connection_watchdog_task:
  9909. _connection_watchdog_task.cancel()
  9910. _connection_watchdog_task = None
  9911. _connection_watchdog_last_attempt.clear()
  9912. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9913. # Camera stream orphan cleanup
  9914. _camera_cleanup_task: asyncio.Task | None = None
  9915. CAMERA_CLEANUP_INTERVAL = 60
  9916. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9917. # kept frames of a failed stitch go after a day, not at the next restart.
  9918. TIMELAPSE_CLEANUP_EVERY = 60
  9919. async def _camera_cleanup_loop():
  9920. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9921. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9922. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9923. rounds = 0
  9924. while True:
  9925. try:
  9926. rounds += 1
  9927. await cleanup_orphaned_streams()
  9928. except asyncio.CancelledError:
  9929. break
  9930. except Exception as e:
  9931. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9932. try:
  9933. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9934. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9935. except asyncio.CancelledError:
  9936. break
  9937. except Exception as e:
  9938. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9939. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9940. def start_camera_cleanup():
  9941. global _camera_cleanup_task
  9942. if _camera_cleanup_task is None:
  9943. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9944. logging.getLogger(__name__).info("Camera stream cleanup started")
  9945. def stop_camera_cleanup():
  9946. global _camera_cleanup_task
  9947. if _camera_cleanup_task:
  9948. _camera_cleanup_task.cancel()
  9949. _camera_cleanup_task = None
  9950. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9951. # ---------------------------------------------------------------------------
  9952. # Expected-print TTL eviction
  9953. # ---------------------------------------------------------------------------
  9954. def _evict_stale_expected_prints() -> None:
  9955. """Remove entries from _expected_prints / _expected_print_creators that are
  9956. older than _EXPECTED_PRINT_TTL_SECONDS.
  9957. This prevents unbounded growth when a print is registered (via
  9958. register_expected_print) but on_print_start never fires — e.g. because the
  9959. printer disconnects, the app restarts, or the print is started directly from
  9960. the printer panel without going through the queue.
  9961. """
  9962. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9963. # (e.g. NTP sync, DST changes).
  9964. # A print that ended without its archive being found at completion leaves
  9965. # its id here; only running prints are owned.
  9966. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9967. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9968. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9969. if not stale_keys:
  9970. return
  9971. evicted_archive_ids: set[int] = set()
  9972. for key in stale_keys:
  9973. archive_id = _expected_prints.pop(key, None)
  9974. if archive_id is not None:
  9975. evicted_archive_ids.add(archive_id)
  9976. _expected_print_creators.pop(key, None)
  9977. _expected_print_registered_at.pop(key, None)
  9978. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9979. # that have no remaining live keys in _expected_prints (all variants
  9980. # were just evicted) and are not printing right now. Print start pops
  9981. # only the names the printer reported, so the "<base>.gcode" variant
  9982. # outlives it; without the printing check its eviction two hours after
  9983. # dispatch threw away a running print's plate, AMS mapping and cost
  9984. # centre, which completion still reads (#3275).
  9985. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9986. for archive_id in evicted_archive_ids:
  9987. if archive_id not in live_archive_ids:
  9988. _print_ams_mappings.pop(archive_id, None)
  9989. _print_cost_center_ids.pop(archive_id, None)
  9990. _print_plate_ids.pop(archive_id, None)
  9991. logging.getLogger(__name__).info(
  9992. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9993. )
  9994. async def _expected_prints_cleanup_loop() -> None:
  9995. """Background task: periodically evict stale expected-print entries."""
  9996. while True:
  9997. try:
  9998. _evict_stale_expected_prints()
  9999. except asyncio.CancelledError:
  10000. raise
  10001. except Exception as e:
  10002. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10003. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10004. def start_expected_prints_cleanup() -> None:
  10005. global _expected_prints_cleanup_task
  10006. if _expected_prints_cleanup_task is None:
  10007. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10008. logging.getLogger(__name__).info("Expected prints cleanup started")
  10009. def stop_expected_prints_cleanup() -> None:
  10010. global _expected_prints_cleanup_task
  10011. if _expected_prints_cleanup_task:
  10012. _expected_prints_cleanup_task.cancel()
  10013. _expected_prints_cleanup_task = None
  10014. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10015. # ---------------------------------------------------------------------------
  10016. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10017. # ---------------------------------------------------------------------------
  10018. _auth_cleanup_task: asyncio.Task | None = None
  10019. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10020. async def _run_auth_cleanup() -> None:
  10021. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10022. from backend.app.core.database import async_session
  10023. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10024. from backend.app.models.user_totp import UserTOTP
  10025. now = datetime.now(timezone.utc)
  10026. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10027. try:
  10028. async with async_session() as db:
  10029. stale_cutoff = now - timedelta(hours=1)
  10030. result = await db.execute(
  10031. select(UserTOTP).where(
  10032. UserTOTP.is_enabled.is_(False),
  10033. UserTOTP.created_at < stale_cutoff,
  10034. )
  10035. )
  10036. stale_records = result.scalars().all()
  10037. if stale_records:
  10038. for rec in stale_records:
  10039. await db.delete(rec)
  10040. await db.commit()
  10041. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10042. except Exception as e:
  10043. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10044. # Remove expired revoked-JTI entries (they are no longer needed once the
  10045. # original token's exp has passed — the token would be rejected by JWT
  10046. # signature verification regardless).
  10047. try:
  10048. async with async_session() as db:
  10049. await db.execute(
  10050. delete(AuthEphemeralToken).where(
  10051. AuthEphemeralToken.token_type == "revoked_jti",
  10052. AuthEphemeralToken.expires_at < now,
  10053. )
  10054. )
  10055. await db.commit()
  10056. except Exception as e:
  10057. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10058. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10059. # Events outside this window can never affect rate-limit decisions — they only
  10060. # consume DB space. Use the same window constant as the rate limiter so the
  10061. # two are always in sync.
  10062. try:
  10063. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10064. async with async_session() as db:
  10065. await db.execute(
  10066. delete(AuthRateLimitEvent).where(
  10067. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10068. )
  10069. )
  10070. await db.commit()
  10071. except Exception as e:
  10072. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10073. async def _auth_cleanup_loop() -> None:
  10074. """Periodic background task: run auth cleanup every hour."""
  10075. while True:
  10076. try:
  10077. await _run_auth_cleanup()
  10078. except asyncio.CancelledError:
  10079. break
  10080. except Exception as e:
  10081. logging.warning("Auth cleanup loop error: %s", e)
  10082. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10083. def start_auth_cleanup() -> None:
  10084. global _auth_cleanup_task
  10085. if _auth_cleanup_task is None:
  10086. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10087. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10088. def stop_auth_cleanup() -> None:
  10089. global _auth_cleanup_task
  10090. if _auth_cleanup_task:
  10091. _auth_cleanup_task.cancel()
  10092. _auth_cleanup_task = None
  10093. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10094. @asynccontextmanager
  10095. async def lifespan(app: FastAPI):
  10096. # Startup
  10097. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10098. # anything else can spawn tasks that might trip it.
  10099. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10100. install_proactor_reset_filter()
  10101. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10102. # what turned descriptor exhaustion into a corrupted database (#2883).
  10103. from backend.app.core.fd_limit import raise_open_file_limit
  10104. raise_open_file_limit()
  10105. # Before init_db, so the warning is near the top of the log rather than
  10106. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10107. warn_if_running_on_uvloop()
  10108. await init_db()
  10109. # Browser download tokens expire after five minutes. Remove abandoned
  10110. # prepared ZIPs at startup as well as before each new preparation so a
  10111. # quiet appliance cannot retain an unusable bundle indefinitely.
  10112. try:
  10113. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10114. await prune_stale_printer_file_bundles()
  10115. except Exception as exc:
  10116. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10117. # After migrations, so the is_env_managed column exists. Never raises --
  10118. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10119. # startup (see apply_env_oidc_provider).
  10120. from backend.app.core.oidc_env import apply_env_oidc_provider
  10121. async with async_session() as oidc_db:
  10122. await apply_env_oidc_provider(oidc_db)
  10123. # Close out batches that finished before `completed` was a reachable status
  10124. # (#342). Without this the Batches tab opens on every batch created since
  10125. # the feature shipped, all still marked active. Never blocks startup.
  10126. try:
  10127. from backend.app.services.print_batch import backfill_batch_statuses
  10128. async with async_session() as batch_db:
  10129. await backfill_batch_statuses(batch_db)
  10130. except Exception as exc:
  10131. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10132. # Register an app-scoped httpx client for Bambu Cloud services so
  10133. # per-request BambuCloudService instances reuse the same connection pool
  10134. # (important for routes like /cloud/filament-info that chain many
  10135. # get_setting_detail calls). The shared client stores no region/token
  10136. # state, so the per-request ownership pattern that fixed the region-bleed
  10137. # bug is preserved.
  10138. import httpx as _httpx
  10139. from backend.app.services.bambu_cloud import set_shared_http_client
  10140. from backend.app.services.model_providers.makerworld.service import (
  10141. set_shared_http_client as set_shared_makerworld_http_client,
  10142. )
  10143. from backend.app.services.orca_cloud import (
  10144. set_shared_http_client as set_shared_orca_http_client,
  10145. )
  10146. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10147. set_shared_http_client(_shared_cloud_http_client)
  10148. # Reuse the same connection pool for MakerWorld — different host, same
  10149. # keep-alive pool saves a TLS handshake per request.
  10150. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10151. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10152. # each spun up (and never closed) its own client, leaking sockets.
  10153. set_shared_orca_http_client(_shared_cloud_http_client)
  10154. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10155. # This can happen when a print was cancelled mid-print on versions before this fix.
  10156. try:
  10157. async with async_session() as db:
  10158. from backend.app.models.print_queue import PrintQueueItem
  10159. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10160. aborted_items = result.scalars().all()
  10161. if aborted_items:
  10162. for item in aborted_items:
  10163. item.status = "cancelled"
  10164. await db.commit()
  10165. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10166. except Exception as e:
  10167. logging.warning("Failed to fix aborted queue items: %s", e)
  10168. # Restore debug logging state from previous session
  10169. await init_debug_logging()
  10170. # Set up printer manager callbacks
  10171. loop = asyncio.get_event_loop()
  10172. printer_manager.set_event_loop(loop)
  10173. printer_manager.set_status_change_callback(on_printer_status_change)
  10174. printer_manager.set_print_start_callback(on_print_start)
  10175. printer_manager.set_print_complete_callback(on_print_complete)
  10176. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10177. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10178. printer_manager.set_ams_change_callback(on_ams_change)
  10179. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10180. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10181. await printer_manager.load_awaiting_plate_clear_from_db()
  10182. # Layer change callback for external camera timelapse
  10183. async def on_layer_change(printer_id: int, layer_num: int):
  10184. """Capture timelapse frame on layer change + first layer notification."""
  10185. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10186. await tl_layer_change(printer_id, layer_num)
  10187. # #1867: bank a recent in-print frame so the finish-photo path has a
  10188. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10189. # #2547 added `on_print_progress` as a second driver — this one alone
  10190. # stops firing once the final layer begins.
  10191. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10192. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10193. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10194. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10195. # nozzle clean), so a bare layer_num check can fire minutes before the
  10196. # first real extrusion. We require gcode_state == RUNNING and
  10197. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10198. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10199. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10200. # edge fires later; _first_layer_notified stays clear until we actually send
  10201. # so a deferred re-evaluation can win. See issue #1837.
  10202. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10203. client = printer_manager.get_client(printer_id)
  10204. state = client.state if client else None
  10205. if not state or state.state != "RUNNING":
  10206. return
  10207. if state.mc_print_sub_stage not in (None, 0):
  10208. return
  10209. _first_layer_notified[printer_id] = True
  10210. try:
  10211. async with async_session() as db:
  10212. from backend.app.models.printer import Printer
  10213. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10214. printer = result.scalar_one_or_none()
  10215. if not printer:
  10216. return
  10217. printer_name = printer.name
  10218. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10219. total_layers = state.total_layers if state else 0
  10220. image_data = await _capture_snapshot_for_notification(
  10221. printer_id, printer, logging.getLogger(__name__)
  10222. )
  10223. await notification_service.on_first_layer_complete(
  10224. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10225. )
  10226. except Exception as e:
  10227. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10228. printer_manager.set_layer_change_callback(on_layer_change)
  10229. async def on_print_progress(printer_id: int, percent: int):
  10230. """#2547: keep the in-print frame bank fresh through the final layer.
  10231. `on_layer_change` stops the moment the last layer starts, which on the
  10232. H2C capture that closed #2547 left the bank stale for the three minutes
  10233. that layer took. Progress is the only field that keeps advancing there,
  10234. and it freezes before the End G-code runs — so banking on it stays
  10235. inside the print and never sees a swapped plate.
  10236. """
  10237. client = printer_manager.get_client(printer_id)
  10238. state = client.state if client else None
  10239. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10240. printer_manager.set_print_progress_callback(on_print_progress)
  10241. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10242. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10243. waiter = _bed_cool_waiters.get(printer_id)
  10244. if not waiter:
  10245. return
  10246. threshold = waiter["threshold"]
  10247. if bed_temp > threshold:
  10248. return
  10249. # Bed is at or below threshold — fire notification and remove waiter
  10250. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10251. if not waiter_info:
  10252. return # Another callback already handled it
  10253. bed_cool_logger = logging.getLogger(__name__)
  10254. bed_cool_logger.info(
  10255. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10256. bed_temp,
  10257. printer_id,
  10258. threshold,
  10259. )
  10260. try:
  10261. printer_info = printer_manager.get_printer(printer_id)
  10262. p_name = printer_info.name if printer_info else "Unknown"
  10263. async with async_session() as db:
  10264. await notification_service.on_bed_cooled(
  10265. printer_id=printer_id,
  10266. printer_name=p_name,
  10267. bed_temp=bed_temp,
  10268. threshold=threshold,
  10269. filename=waiter_info["filename"],
  10270. db=db,
  10271. )
  10272. except Exception as e:
  10273. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10274. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10275. async def on_drying_complete(printer_id: int, ams_id: int):
  10276. """Smart-plug auto-off-after-drying trigger (#1349).
  10277. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10278. manager walks all plugs linked to this printer and turns off only
  10279. the ones with ``auto_off_after_drying`` enabled, after their
  10280. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10281. dual-AMS dry that ends within the same MQTT push) call this once
  10282. per unit — the manager's ``_cancel_pending_off`` collapses
  10283. repeated scheduling on the same plug to one timer, so duplicate
  10284. fires are safe.
  10285. """
  10286. try:
  10287. async with async_session() as db:
  10288. await smart_plug_manager.on_drying_complete(printer_id, db)
  10289. except Exception as e:
  10290. logging.getLogger(__name__).warning(
  10291. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10292. printer_id,
  10293. ams_id,
  10294. e,
  10295. )
  10296. printer_manager.set_drying_complete_callback(on_drying_complete)
  10297. async def on_drying_cycle_end(printer_id: int, cycle):
  10298. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10299. from backend.app.services.spool_drying import record_drying_cycle
  10300. try:
  10301. async with async_session() as db:
  10302. await record_drying_cycle(db, printer_id, cycle)
  10303. except Exception as e:
  10304. logging.getLogger(__name__).warning(
  10305. "Failed to record drying for printer %d (AMS %d): %s",
  10306. printer_id,
  10307. cycle.ams_id,
  10308. e,
  10309. )
  10310. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10311. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10312. """Surface the read-back result of a spool assignment to the UI (#2582).
  10313. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10314. echoed back the filament id we pushed. We relay that as a websocket
  10315. event so the frontend can toast "loaded" / "assignment didn't take"
  10316. instead of the historic silent fire-and-forget, which made the
  10317. AMS→Studio hand-off feel random to users.
  10318. """
  10319. try:
  10320. from backend.app.services.spool_assignment_notifications import (
  10321. _slot_label_from_global_tray,
  10322. )
  10323. if ams_id == 255:
  10324. global_id = 254 + tray_id
  10325. elif ams_id >= 128:
  10326. global_id = ams_id
  10327. else:
  10328. global_id = ams_id * 4 + tray_id
  10329. slot_label = _slot_label_from_global_tray(global_id)
  10330. printer_info = printer_manager.get_printer(printer_id)
  10331. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10332. await ws_manager.broadcast(
  10333. {
  10334. "type": "spool_assignment_verified",
  10335. "printer_id": printer_id,
  10336. "printer_name": printer_name,
  10337. "ams_id": ams_id,
  10338. "tray_id": tray_id,
  10339. "slot": slot_label,
  10340. "verified": verified,
  10341. # Present on success: False means the filament setting landed
  10342. # but the K-profile (cali_idx) did not — the reporter's exact
  10343. # "loaded but no flow profile" symptom.
  10344. "kprofile_applied": detail.get("kprofile_applied", True),
  10345. }
  10346. )
  10347. except Exception as e:
  10348. logging.getLogger(__name__).warning(
  10349. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10350. printer_id,
  10351. ams_id,
  10352. tray_id,
  10353. e,
  10354. )
  10355. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10356. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10357. """Persist a mid-print tray change for completion-time attribution.
  10358. AMS filament backup switches trays without telling the slicer, so the
  10359. tray-change log is the only record of which spool fed which layers.
  10360. Keeping it only in memory meant a restart mid-print charged everything
  10361. to the tray that finished the job.
  10362. """
  10363. try:
  10364. from backend.app.services.usage_tracker import record_tray_change
  10365. async with async_session() as db:
  10366. await record_tray_change(db, printer_id, tray_global, layer_num)
  10367. except Exception as e:
  10368. logging.getLogger(__name__).warning(
  10369. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10370. printer_id,
  10371. tray_global,
  10372. layer_num,
  10373. e,
  10374. )
  10375. printer_manager.set_tray_change_callback(on_tray_change)
  10376. # Initialize MQTT relay from settings
  10377. async with async_session() as db:
  10378. from backend.app.api.routes.settings import get_setting
  10379. mqtt_settings = {
  10380. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10381. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10382. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10383. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10384. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10385. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10386. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10387. }
  10388. await mqtt_relay.configure(mqtt_settings)
  10389. # Restore MQTT smart plug subscriptions
  10390. if mqtt_settings.get("mqtt_enabled"):
  10391. from backend.app.models.smart_plug import SmartPlug
  10392. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10393. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10394. mqtt_plugs = result.scalars().all()
  10395. restored = 0
  10396. for plug in mqtt_plugs:
  10397. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10398. restored += 1
  10399. if restored:
  10400. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10401. # Connect to all active printers
  10402. async with async_session() as db:
  10403. await init_printer_connections(db)
  10404. # Auto-connect to Spoolman if enabled
  10405. async with async_session() as db:
  10406. from backend.app.api.routes.settings import get_setting
  10407. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10408. spoolman_url = await get_setting(db, "spoolman_url")
  10409. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10410. try:
  10411. client = await init_spoolman_client(spoolman_url)
  10412. if await client.health_check():
  10413. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10414. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10415. field_ok = await client.ensure_tag_extra_field()
  10416. if not field_ok:
  10417. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10418. # Register the BambuStudio slicer-preset fields used by the
  10419. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10420. # unknown extra keys, so these must exist before any update
  10421. # that touches them.
  10422. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10423. if not await client.ensure_extra_field(field_name):
  10424. logging.warning(
  10425. "Spoolman extra field %r registration failed — "
  10426. "spool slicer-preset edits will return 502",
  10427. field_name,
  10428. )
  10429. else:
  10430. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10431. except Exception as e:
  10432. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10433. # Start the print scheduler
  10434. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10435. # Start the smart plug scheduler for time-based on/off
  10436. smart_plug_manager.start_scheduler()
  10437. # Start the Home Assistant sensor poller (#1148)
  10438. ha_sensor_manager.start()
  10439. location_ha_sensor_manager.start()
  10440. # Resume any pending auto-offs that were interrupted by restart
  10441. await smart_plug_manager.resume_pending_auto_offs()
  10442. # Start the notification digest scheduler
  10443. notification_service.start_digest_scheduler()
  10444. notify_live_activities.start()
  10445. notify_widgets.start()
  10446. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10447. # provider in reactions/both mode; the notification routes resync them.
  10448. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10449. # until the next provider save, not the whole startup.
  10450. try:
  10451. await telegram_reaction_poller.start()
  10452. except Exception as e:
  10453. logging.warning("Telegram reaction poller did not start: %s", e)
  10454. # Start the GitHub backup scheduler
  10455. await github_backup_service.start_scheduler()
  10456. # Start the local backup scheduler
  10457. await local_backup_service.start_scheduler()
  10458. await obico_detection_service.start()
  10459. # Start the library trash sweeper (#1008)
  10460. await library_trash_service.start_scheduler()
  10461. # Start the archive auto-purge sweeper (#1008 follow-up)
  10462. await archive_purge_service.start_scheduler()
  10463. # Start AMS history recording
  10464. start_ams_history_recording()
  10465. # Start printer sensor (nozzle / bed / chamber) history recording
  10466. start_printer_sensor_history_recording()
  10467. # Start printer runtime tracking
  10468. start_runtime_tracking()
  10469. # Start SpoolBuddy device watchdog
  10470. start_spoolbuddy_watchdog()
  10471. # Start camera stream orphan cleanup
  10472. start_camera_cleanup()
  10473. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10474. start_connection_watchdog()
  10475. # One-shot sweep for timelapse session directories orphaned by a crash
  10476. # or restart that happened mid-print (in-memory session tracking can't
  10477. # survive that, and nothing else reaps the leftover frames/output file)
  10478. try:
  10479. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10480. removed = cleanup_orphaned_timelapse_sessions()
  10481. if removed:
  10482. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10483. except Exception as e:
  10484. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10485. # Start expected-print TTL eviction (prevents memory leak when prints are
  10486. # registered but on_print_start never fires)
  10487. start_expected_prints_cleanup()
  10488. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10489. start_auth_cleanup()
  10490. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10491. from backend.app.services import announcements as announcements_service
  10492. announcements_service.start()
  10493. from backend.app.services.printer_media import start_printer_download_cleanup
  10494. start_printer_download_cleanup()
  10495. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10496. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10497. from backend.app.services.loop_watchdog import start_loop_watchdog
  10498. start_loop_watchdog()
  10499. # Initialize virtual printer manager and sync from DB
  10500. from backend.app.services.virtual_printer import virtual_printer_manager
  10501. virtual_printer_manager.set_session_factory(async_session)
  10502. virtual_printer_manager.set_printer_manager(printer_manager)
  10503. try:
  10504. await virtual_printer_manager.sync_from_db()
  10505. logging.info("Virtual printer manager synced from database")
  10506. except Exception as e:
  10507. logging.warning("Failed to sync virtual printers: %s", e)
  10508. yield
  10509. # Shutdown
  10510. print_scheduler.stop()
  10511. smart_plug_manager.stop_scheduler()
  10512. ha_sensor_manager.stop()
  10513. location_ha_sensor_manager.stop()
  10514. notification_service.stop_digest_scheduler()
  10515. await notify_live_activities.close()
  10516. await notify_widgets.close()
  10517. await telegram_reaction_poller.aclose()
  10518. github_backup_service.stop_scheduler()
  10519. local_backup_service.stop_scheduler()
  10520. library_trash_service.stop_scheduler()
  10521. archive_purge_service.stop_scheduler()
  10522. obico_detection_service.stop()
  10523. stop_ams_history_recording()
  10524. stop_printer_sensor_history_recording()
  10525. stop_runtime_tracking()
  10526. stop_spoolbuddy_watchdog()
  10527. stop_camera_cleanup()
  10528. stop_connection_watchdog()
  10529. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10530. stop_loop_watchdog()
  10531. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10532. # cleanly rather than waiting on a queue that nothing will ever fill.
  10533. try:
  10534. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10535. await shutdown_all_broadcasters()
  10536. except Exception as e:
  10537. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10538. stop_expected_prints_cleanup()
  10539. stop_auth_cleanup()
  10540. from backend.app.services import announcements as announcements_service
  10541. announcements_service.stop()
  10542. from backend.app.services.printer_media import stop_printer_download_cleanup
  10543. await stop_printer_download_cleanup()
  10544. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10545. from backend.app.services import timelapse_jobs
  10546. await timelapse_jobs.cancel_all()
  10547. printer_manager.disconnect_all()
  10548. slot_unlink_grace.reset()
  10549. await close_spoolman_client()
  10550. # Stop all virtual printer services
  10551. await virtual_printer_manager.stop_all()
  10552. await mqtt_smart_plug_service.disconnect(timeout=2)
  10553. await mqtt_relay.disconnect(timeout=2)
  10554. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10555. set_shared_http_client(None)
  10556. set_shared_makerworld_http_client(None)
  10557. set_shared_orca_http_client(None)
  10558. await _shared_cloud_http_client.aclose()
  10559. # Checkpoint WAL (SQLite only) and close all database connections
  10560. from backend.app.core.db_dialect import is_sqlite
  10561. if is_sqlite():
  10562. try:
  10563. async with engine.begin() as conn:
  10564. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10565. logging.info("WAL checkpoint completed")
  10566. except Exception as e:
  10567. logging.warning("WAL checkpoint failed: %s", e)
  10568. await engine.dispose()
  10569. app = FastAPI(
  10570. title=app_settings.app_name,
  10571. description="Archive and manage Bambu Lab 3MF files",
  10572. version=APP_VERSION,
  10573. lifespan=lifespan,
  10574. )
  10575. # Added first so it sits innermost, next to the routes: a refused header's value
  10576. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10577. app.add_middleware(RefusedHeaderResponseMask)
  10578. def _json_safe(value):
  10579. """The validation errors with every non-finite number written as text."""
  10580. if isinstance(value, float) and not math.isfinite(value):
  10581. return str(value)
  10582. if isinstance(value, dict):
  10583. return {key: _json_safe(item) for key, item in value.items()}
  10584. if isinstance(value, list | tuple):
  10585. return [_json_safe(item) for item in value]
  10586. return value
  10587. @app.exception_handler(RequestValidationError)
  10588. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10589. """FastAPI's own 422, except that it survives a non-finite number.
  10590. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10591. them), and the default handler echoes the input back in its errors,
  10592. which JSON cannot hold: the request ended in an error instead of a 422.
  10593. """
  10594. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10595. # =============================================================================
  10596. # Authentication Middleware - Secures ALL API routes by default
  10597. # =============================================================================
  10598. # Public routes that don't require authentication even when auth is enabled
  10599. PUBLIC_API_ROUTES = {
  10600. # Auth routes needed before/during login
  10601. "/api/v1/auth/status",
  10602. "/api/v1/auth/login",
  10603. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10604. # Advanced auth status needed for login page
  10605. "/api/v1/auth/advanced-auth/status",
  10606. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10607. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10608. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10609. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10610. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10611. # OIDC routes that must be reachable without a JWT
  10612. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10613. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10614. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10615. # Connected apps: the app's server swaps a code for the user's identity,
  10616. # authenticated by its client secret rather than a login token.
  10617. "/api/v1/connect/token",
  10618. # Version check for updates (no sensitive data)
  10619. "/api/v1/updates/version",
  10620. # Metrics endpoint handles its own prometheus_token authentication
  10621. "/api/v1/metrics",
  10622. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10623. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10624. # hostname / timezone / locale and the chrony NTP-gate state. The
  10625. # response contains user-set defaults and a public sync flag — no
  10626. # secrets. Without this entry the global auth middleware returns 401
  10627. # before the route handler runs, regardless of the route's own
  10628. # "no auth required" intent.
  10629. "/api/v1/system/appliance",
  10630. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10631. # authenticates with a long-lived ``camwall``-scoped token in the query
  10632. # string — exactly like the camera streams two lists below, and for the same
  10633. # reason (no header to put a JWT in). "Public" here only means the middleware
  10634. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10635. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10636. # plain ``camera_stream`` token does NOT open this door.
  10637. "/api/v1/camwall/printers",
  10638. # Overlay branding: the route enforces overlay-scoped token authentication.
  10639. "/api/v1/overlay-branding/logo",
  10640. }
  10641. # Route prefixes that are public (for routes with dynamic segments)
  10642. PUBLIC_API_PREFIXES = [
  10643. # WebSocket connections handle their own auth
  10644. "/api/v1/ws",
  10645. # OIDC authorize redirects — include provider_id in path
  10646. "/api/v1/auth/oidc/authorize/",
  10647. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10648. # a phone with no session, so no header can carry a JWT — the single-use
  10649. # capability token in the path IS the credential (same reasoning as the
  10650. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10651. # good/reject on the one archive the token was minted for.
  10652. "/api/v1/archives/confirm/",
  10653. ]
  10654. # Route patterns that are public (read-only display data)
  10655. # These are checked with "in path" - needed because browsers load images/videos
  10656. # via <img src> and <video src> which don't include Authorization headers
  10657. PUBLIC_API_PATTERNS = [
  10658. # Thumbnails
  10659. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10660. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10661. # Images and media
  10662. "/photos/", # /archives/{id}/photos/{filename}
  10663. "/project-image/", # /archives/{id}/project-image/{path}
  10664. "/qrcode", # /archives/{id}/qrcode
  10665. "/timelapse", # /archives/{id}/timelapse (video)
  10666. "/cover", # /printers/{id}/cover
  10667. "/icon", # /external-links/{id}/icon
  10668. # Camera (streams loaded via <img> tag)
  10669. "/camera/stream", # /printers/{id}/camera/stream
  10670. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10671. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10672. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10673. # string (same reasoning as the camera streams above — no header to carry a
  10674. # JWT). "Public" only means the middleware steps aside; the route still runs
  10675. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10676. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10677. "/overlay-status", # /printers/{id}/overlay-status
  10678. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10679. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10680. # download token in the URL path instead.
  10681. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10682. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10683. # and these patterns match by substring. Without its own entry the middleware
  10684. # 401s the slicer's header-less request before the route's token check runs,
  10685. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10686. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10687. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10688. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10689. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10690. ]
  10691. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10692. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10693. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10694. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10695. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10696. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10697. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10698. Invalid entries are dropped with a warning rather than failing startup, so
  10699. a typo in one origin doesn't take the whole deployment down.
  10700. """
  10701. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10702. if not raw:
  10703. return ()
  10704. valid: list[str] = []
  10705. for item in raw.split(","):
  10706. candidate = item.strip()
  10707. if not candidate:
  10708. continue
  10709. try:
  10710. parsed = urlparse(candidate)
  10711. except ValueError as e:
  10712. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10713. continue
  10714. if parsed.scheme not in ("http", "https"):
  10715. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10716. continue
  10717. if not parsed.netloc:
  10718. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10719. continue
  10720. if parsed.path and parsed.path != "/":
  10721. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10722. continue
  10723. if parsed.query or parsed.fragment:
  10724. _security_headers_logger.warning(
  10725. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10726. )
  10727. continue
  10728. if "*" in parsed.netloc:
  10729. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10730. continue
  10731. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10732. if valid:
  10733. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10734. return tuple(valid)
  10735. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10736. def _frame_ancestors(default_value: str) -> str:
  10737. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10738. ``default_value`` is the strict directive used when the operator has not
  10739. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10740. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10741. Settings URL builder's preview). When trusted origins
  10742. are configured, ``'self'`` is always included so same-origin embedding never
  10743. breaks even if an operator forgets to add their own origin to the list.
  10744. """
  10745. if _TRUSTED_FRAME_ORIGINS:
  10746. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10747. return f"frame-ancestors {default_value};"
  10748. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10749. # patterns are anchored on the exact emitted name so the relaxed policies
  10750. # below can never apply to any other asset.
  10751. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10752. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10753. # -> /assets/pdf.worker.min-<hash>.js
  10754. # Vite also emits a one-line chunk under the second name that only exports the
  10755. # worker's URL. The page imports it as a module, and a module script is run
  10756. # under the importing document's policy, never its own response's, so it
  10757. # matching as well changes nothing.
  10758. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10759. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10760. @app.middleware("http")
  10761. async def security_headers_middleware(request, call_next):
  10762. """Add standard HTTP security headers to every response."""
  10763. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10764. # changes nothing for Bambuddy's own pages — index.html has no inline
  10765. # scripts since the SW registration moved to /sw-register.js. The reason
  10766. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10767. # script injected into the HTML on the edge, with a fresh hash on every
  10768. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10769. # it clones the same nonce onto its injected <script>, and the inline
  10770. # script passes the policy without us needing 'unsafe-inline'. See
  10771. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10772. csp_nonce = secrets.token_urlsafe(16)
  10773. # Routes that render their own HTML need it too, or their inline script is
  10774. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10775. # one that does: it submits its own form so a verdict still costs one tap.
  10776. request.state.csp_nonce = csp_nonce
  10777. response = await call_next(request)
  10778. response.headers["X-Content-Type-Options"] = "nosniff"
  10779. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10780. # browsers honour CSP frame-ancestors instead, and the legacy
  10781. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10782. # When operators have explicitly allowlisted trusted frame origins (#1191
  10783. # — typically Home Assistant on a different port), drop X-Frame-Options
  10784. # and let the CSP-side frame-ancestors directive govern embedding.
  10785. if not _TRUSTED_FRAME_ORIGINS:
  10786. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10787. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10788. # Content-Security-Policy for the React SPA.
  10789. # Notes:
  10790. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10791. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10792. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10793. # - media-src blob:: timelapse video player uses Blob URLs.
  10794. # - font-src data:: some icon fonts are embedded as data URIs.
  10795. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10796. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10797. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10798. # default CSP would render a blank page.
  10799. response.headers["Content-Security-Policy"] = (
  10800. "default-src 'self'; "
  10801. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10802. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10803. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10804. "connect-src 'self'; "
  10805. "font-src 'self' data: https://fonts.gstatic.com; "
  10806. "worker-src 'self' blob:; "
  10807. "object-src 'none'; "
  10808. "base-uri 'self'; " + _frame_ancestors("'none'")
  10809. )
  10810. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10811. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10812. # its emscripten/embind glue generates invoker functions with `new
  10813. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10814. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10815. # own response — not the document's — so relaxing it here confines
  10816. # eval to that DOM-less worker context. The document policy below
  10817. # stays nonce-strict, and this response header has no effect when the
  10818. # file is merely fetched (a fetch's CSP is enforced against the
  10819. # requesting document, not the resource's own headers).
  10820. response.headers["Content-Security-Policy"] = (
  10821. "default-src 'self'; "
  10822. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10823. "connect-src 'self'; "
  10824. "object-src 'none'; "
  10825. "base-uri 'self'; " + _frame_ancestors("'none'")
  10826. )
  10827. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10828. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10829. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10830. # rule as the STEP worker above: the policy that governs a dedicated
  10831. # worker is the one delivered with its own script, so the wasm compile
  10832. # has to be permitted here rather than on the document. Unlike the STEP
  10833. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10834. response.headers["Content-Security-Policy"] = (
  10835. "default-src 'self'; "
  10836. "script-src 'self' 'wasm-unsafe-eval'; "
  10837. "connect-src 'self'; "
  10838. "object-src 'none'; "
  10839. "base-uri 'self'; " + _frame_ancestors("'none'")
  10840. )
  10841. else:
  10842. # The streaming overlay is embedded same-origin by the URL builder's
  10843. # preview in Settings (#1422), so this branch allows 'self'.
  10844. # Embedding from anywhere else is still refused: 'self'
  10845. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10846. # a clickjacking page on another host is blocked exactly as before.
  10847. # (The overlay draws status over a camera feed and its only interactive
  10848. # element is the logo link, so there is nothing to bait a click into
  10849. # even from a same-origin framer.) Cross-origin embedding of the
  10850. # overlay — Home Assistant on another port — remains what
  10851. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10852. # allowlist in.
  10853. #
  10854. # The connected-app consent page (/connect/authorize) gets the same
  10855. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10856. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10857. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10858. # requires every ancestor to be this origin, so a foreign page -- a
  10859. # sidebar link's site included -- still cannot frame the consent
  10860. # screen to bait a click.
  10861. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10862. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10863. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10864. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10865. # the policy served with their own script, so each gets it in its own
  10866. # branch above and the document policy stays as strict as it was.
  10867. response.headers["Content-Security-Policy"] = (
  10868. "default-src 'self'; "
  10869. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10870. "style-src 'self' 'unsafe-inline'; "
  10871. "img-src 'self' data: blob:; "
  10872. "media-src 'self' blob:; "
  10873. "connect-src 'self' ws: wss:; "
  10874. "font-src 'self' data:; "
  10875. "object-src 'none'; "
  10876. "base-uri 'self'; "
  10877. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10878. )
  10879. if request.url.scheme == "https":
  10880. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10881. return response
  10882. @app.middleware("http")
  10883. async def auth_middleware(request, call_next):
  10884. """Enforce authentication on all API routes when auth is enabled.
  10885. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10886. regardless of whether individual routes have auth dependencies.
  10887. """
  10888. from starlette.responses import JSONResponse
  10889. path = request.url.path
  10890. # Only apply to API routes
  10891. if not path.startswith("/api/"):
  10892. return await call_next(request)
  10893. # Allow public routes
  10894. if path in PUBLIC_API_ROUTES:
  10895. return await call_next(request)
  10896. # Allow public prefixes
  10897. for prefix in PUBLIC_API_PREFIXES:
  10898. if path.startswith(prefix):
  10899. return await call_next(request)
  10900. # Allow public patterns (read-only display data like thumbnails)
  10901. for pattern in PUBLIC_API_PATTERNS:
  10902. if pattern in path:
  10903. return await call_next(request)
  10904. # Check if auth is enabled. Fail CLOSED on any exception during the
  10905. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10906. # an attacker who could force a DB exception (e.g. file-descriptor
  10907. # exhaustion via login flood) bypass auth on every protected endpoint.
  10908. # Only the probe is guarded: the request itself runs outside the try, so an
  10909. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10910. try:
  10911. async with async_session() as db:
  10912. from backend.app.core.auth import is_auth_enabled
  10913. auth_enabled = await is_auth_enabled(db)
  10914. except Exception:
  10915. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10916. return JSONResponse(
  10917. status_code=503,
  10918. content={"detail": "Authentication service temporarily unavailable"},
  10919. )
  10920. if not auth_enabled:
  10921. # Auth disabled, allow all requests
  10922. return await call_next(request)
  10923. # Auth is enabled - require valid token
  10924. auth_header = request.headers.get("Authorization")
  10925. x_api_key = request.headers.get("X-API-Key")
  10926. # Check for API key auth first
  10927. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10928. # API key authentication - let the request through to be validated by route handler
  10929. # API keys are validated per-route since they have different permission levels
  10930. return await call_next(request)
  10931. # Check for JWT auth
  10932. if not auth_header or not auth_header.startswith("Bearer "):
  10933. return JSONResponse(
  10934. status_code=401,
  10935. content={"detail": "Authentication required"},
  10936. headers={"WWW-Authenticate": "Bearer"},
  10937. )
  10938. # Validate JWT token
  10939. import jwt
  10940. try:
  10941. from backend.app.core.auth import (
  10942. ALGORITHM,
  10943. SECRET_KEY,
  10944. _is_token_fresh,
  10945. get_user_by_username,
  10946. is_jti_revoked,
  10947. )
  10948. token = auth_header.replace("Bearer ", "")
  10949. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10950. username = payload.get("sub")
  10951. if not username:
  10952. raise ValueError("No username in token")
  10953. jti = payload.get("jti")
  10954. if not jti:
  10955. raise ValueError("No jti in token")
  10956. iat = payload.get("iat")
  10957. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10958. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10959. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10960. async with async_session() as db:
  10961. if await is_jti_revoked(jti, db):
  10962. return JSONResponse(
  10963. status_code=401,
  10964. content={"detail": "Token has been revoked"},
  10965. headers={"WWW-Authenticate": "Bearer"},
  10966. )
  10967. user = await get_user_by_username(db, username)
  10968. if not user or not user.is_active:
  10969. return JSONResponse(
  10970. status_code=401,
  10971. content={"detail": "User not found or inactive"},
  10972. headers={"WWW-Authenticate": "Bearer"},
  10973. )
  10974. if not _is_token_fresh(iat, user):
  10975. return JSONResponse(
  10976. status_code=401,
  10977. content={"detail": "Token no longer valid"},
  10978. headers={"WWW-Authenticate": "Bearer"},
  10979. )
  10980. except jwt.ExpiredSignatureError:
  10981. return JSONResponse(
  10982. status_code=401,
  10983. content={"detail": "Token has expired"},
  10984. headers={"WWW-Authenticate": "Bearer"},
  10985. )
  10986. except (jwt.InvalidTokenError, ValueError):
  10987. return JSONResponse(
  10988. status_code=401,
  10989. content={"detail": "Invalid token"},
  10990. headers={"WWW-Authenticate": "Bearer"},
  10991. )
  10992. except Exception:
  10993. # Not a bad token but a failure checking it (database, pool): refuse,
  10994. # as for the probe above, rather than answer 401 -- the frontend reads
  10995. # a 401 from /auth/me as final and signs the user out.
  10996. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10997. return JSONResponse(
  10998. status_code=503,
  10999. content={"detail": "Authentication service temporarily unavailable"},
  11000. )
  11001. return await call_next(request)
  11002. @app.middleware("http")
  11003. async def trace_id_middleware(request, call_next):
  11004. """Stamp every HTTP request with a trace ID and echo it back.
  11005. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11006. @app.middleware decorators LIFO, so the last-decorated runs first
  11007. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11008. which means auth-middleware log lines (and every line emitted on the
  11009. way down to and back from the route handler) all carry the same
  11010. trace ID. If we put it before auth, auth's logs would be stamped
  11011. with the *previous* request's ID — useless for correlation.
  11012. Honours an inbound ``X-Trace-Id`` header so callers running their
  11013. own tracing can correlate their span IDs with our log lines, but
  11014. only if the value passes the whitelist gate in
  11015. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11016. rejected (too long, contains control chars, etc.) silently triggers
  11017. a freshly minted server-side ID rather than failing the request.
  11018. The minted (or echoed) ID is set on a ContextVar so that every log
  11019. record emitted during the request — application logs *and* uvicorn's
  11020. access log — carries it via TraceIDFilter, and is also written to
  11021. the ``X-Trace-Id`` response header so clients can pin a server-side
  11022. log search to the exact request they made.
  11023. """
  11024. from backend.app.core.trace import (
  11025. generate_trace_id,
  11026. normalise_inbound_trace_id,
  11027. trace_id_var,
  11028. )
  11029. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11030. trace_id = inbound if inbound is not None else generate_trace_id()
  11031. token = trace_id_var.set(trace_id)
  11032. try:
  11033. response = await call_next(request)
  11034. finally:
  11035. # Reset the ContextVar so a record emitted in a totally
  11036. # unrelated background task that just happens to inherit this
  11037. # context doesn't keep referencing this request's ID forever.
  11038. # In practice ContextVar.reset is best-effort under asyncio
  11039. # task-spawn semantics, but the cost is one attribute write so
  11040. # we may as well do it.
  11041. trace_id_var.reset(token)
  11042. response.headers["X-Trace-Id"] = trace_id
  11043. return response
  11044. # API routes
  11045. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11046. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11047. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11048. app.include_router(users.router, prefix=app_settings.api_prefix)
  11049. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11050. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11051. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11052. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11053. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11054. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11055. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11056. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11057. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11058. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11059. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11060. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11061. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11062. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11063. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11064. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11065. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11066. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11067. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11068. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11069. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11070. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11071. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11072. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11073. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11074. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11075. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11076. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11077. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11078. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11079. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11080. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11081. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11082. app.include_router(library.router, prefix=app_settings.api_prefix)
  11083. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11084. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11085. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11086. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11087. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11088. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11089. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11090. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11091. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11092. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11093. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11094. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11095. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11096. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11097. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11098. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11099. app.include_router(system.router, prefix=app_settings.api_prefix)
  11100. app.include_router(support.router, prefix=app_settings.api_prefix)
  11101. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11102. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11103. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11104. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11105. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11106. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11107. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11108. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11109. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11110. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11111. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11112. # Serve static files (React build)
  11113. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11114. # Compressed, and cached for good where Vite hashed the name (#3175).
  11115. app.mount(
  11116. "/assets",
  11117. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11118. name="assets",
  11119. )
  11120. if (app_settings.static_dir / "img").exists():
  11121. app.mount(
  11122. "/img",
  11123. StaticFiles(directory=app_settings.static_dir / "img"),
  11124. name="img",
  11125. )
  11126. if (app_settings.static_dir / "icons").exists():
  11127. app.mount(
  11128. "/icons",
  11129. StaticFiles(directory=app_settings.static_dir / "icons"),
  11130. name="icons",
  11131. )
  11132. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11133. # falls through to the SPA catch-all and returns index.html, which the
  11134. # browser's font sanitizer rejects ("downloadable font: rejected by
  11135. # sanitizer").
  11136. if (app_settings.static_dir / "fonts").exists():
  11137. app.mount(
  11138. "/fonts",
  11139. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11140. name="fonts",
  11141. )
  11142. @app.get("/")
  11143. async def serve_frontend():
  11144. """Serve the React frontend."""
  11145. index_file = app_settings.static_dir / "index.html"
  11146. if index_file.exists():
  11147. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11148. return {
  11149. "message": "Bambuddy API",
  11150. "docs": "/docs",
  11151. "frontend": "Build and place React app in /static directory",
  11152. }
  11153. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11154. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11155. # forever, but the HTML wrapping it is the only file that knows which hash
  11156. # is current. Without explicit cache-control headers Chromium decides
  11157. # heuristically (typically 10% of the time since Last-Modified) and on
  11158. # long-running kiosks happily serves stale HTML across browser restarts.
  11159. # That stale HTML references an old bundle hash, the old bundle is also
  11160. # in the disk cache, and the user ends up running pre-update JS forever
  11161. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11162. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11163. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11164. @app.get("/health")
  11165. async def health_check():
  11166. """Health check endpoint."""
  11167. return {"status": "healthy"}
  11168. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11169. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11170. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11171. # in deployment debugging.
  11172. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  11173. async def serve_manifest():
  11174. """Serve PWA manifest."""
  11175. manifest_file = app_settings.static_dir / "manifest.json"
  11176. if manifest_file.exists():
  11177. return FileResponse(manifest_file, media_type="application/manifest+json")
  11178. return {"error": "Manifest not found"}
  11179. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  11180. async def serve_service_worker():
  11181. """Serve service worker."""
  11182. sw_file = app_settings.static_dir / "sw.js"
  11183. if sw_file.exists():
  11184. return FileResponse(
  11185. sw_file,
  11186. media_type="application/javascript",
  11187. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11188. )
  11189. return {"error": "Service worker not found"}
  11190. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  11191. async def serve_sw_register():
  11192. """Serve the service-worker registration bootstrap script.
  11193. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11194. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11195. """
  11196. reg_file = app_settings.static_dir / "sw-register.js"
  11197. if reg_file.exists():
  11198. return FileResponse(reg_file, media_type="application/javascript")
  11199. return {"error": "sw-register.js not found"}
  11200. # ── GCode viewer static files ────────────────────────────────────────────────
  11201. # Catch-all route for React Router (must be last)
  11202. @app.get("/{full_path:path}")
  11203. async def serve_spa(full_path: str):
  11204. """Serve React app for client-side routing."""
  11205. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11206. if full_path.startswith("api/"):
  11207. from fastapi import HTTPException
  11208. raise HTTPException(status_code=404, detail="Not found")
  11209. index_file = app_settings.static_dir / "index.html"
  11210. if index_file.exists():
  11211. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11212. return {"error": "Frontend not built"}