main.py 635 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Track printers waiting for bed to cool after print completion.
  512. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  513. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  514. _bed_cool_waiters: dict[int, dict] = {}
  515. # Track printers where the user explicitly stopped the print from the queue UI.
  516. # When on_print_complete fires with status "failed" for these printers we treat it
  517. # as "cancelled" (stopped by user) so the correct notification email is sent.
  518. _user_stopped_printers: set[int] = set()
  519. # Printers whose running print the kill switch stopped. Their completion is a
  520. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  521. _kill_switch_stopped: set[int] = set()
  522. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  523. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  524. # holds the previous observation so we only fire on the True → False edge (a
  525. # False → False repeat doesn't notify; an initial False at startup doesn't
  526. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  527. # holds the per-printer pending asyncio task that fires the notification
  528. # after a debounce window — cancelled if the printer reconnects before the
  529. # window elapses, so transient MQTT blips don't flood the user.
  530. _printer_last_connected: dict[int, bool] = {}
  531. # Printers whose relay offline event went out, so the reconnect publishes the
  532. # matching online event and a blip shorter than the debounce publishes neither.
  533. _printer_offline_published: set[int] = set()
  534. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  535. # Debounce: a printer must stay offline this long before we notify. Sized
  536. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  537. # so a single stale-trigger cooldown isn't enough to fire — only a real
  538. # offline that survives one reconnect attempt notifies.
  539. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  540. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  541. # when status="failed" to label the print's failure_reason in archives.
  542. #
  543. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  544. # which is wrong on two counts:
  545. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  546. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  547. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  548. # the public wiki) as part of its user-cancel sequence. Matching on the module
  549. # alone caused user-cancellations to be archived as "Layer shift" failures.
  550. # We now match by full short code only — anything not in this map leaves
  551. # failure_reason=None rather than guessing.
  552. # Values are the canonical camelCase failure-reason keys, NOT display labels
  553. # (issue #2974). The vocabulary is enforced on writes by
  554. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  555. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  556. # Statistics breakdown. Storing a label here instead put a second spelling of
  557. # the same cause into one column: the Failure Analysis widget groups on the raw
  558. # value, so a print the backend classified and an identical one a user
  559. # classified counted as two different reasons, and the label form could never
  560. # be translated because there was no key for ``t()`` to resolve.
  561. _HMS_FAILURE_REASONS: dict[str, str] = {
  562. # Layer shift / step loss
  563. "0300_4057": "layerShift",
  564. "0300_4068": "layerShift",
  565. "0300_800C": "layerShift",
  566. # Filament runout (printer-side & per-AMS-slot)
  567. "0300_8004": "filamentRunout",
  568. "0700_8011": "filamentRunout",
  569. "0701_8011": "filamentRunout",
  570. "0702_8011": "filamentRunout",
  571. "0703_8011": "filamentRunout",
  572. "0704_8011": "filamentRunout",
  573. "0705_8011": "filamentRunout",
  574. "0706_8011": "filamentRunout",
  575. "0707_8011": "filamentRunout",
  576. "07FF_8011": "filamentRunout",
  577. # Clogged nozzle / extruder
  578. "0300_4006": "cloggedNozzle",
  579. "0300_8016": "cloggedNozzle",
  580. "0300_801C": "cloggedNozzle",
  581. "0700_8003": "cloggedNozzle",
  582. "0700_8007": "cloggedNozzle",
  583. "0700_8013": "cloggedNozzle",
  584. "0701_8003": "cloggedNozzle",
  585. "0701_8007": "cloggedNozzle",
  586. "0701_8013": "cloggedNozzle",
  587. "0702_8003": "cloggedNozzle",
  588. # AI print monitoring — spaghetti / the model coming off the plate.
  589. # `spaghettiDetached` is a key the archive editor already offers for this
  590. # failure mode, not a new one, so a derived reason opens the dropdown on
  591. # that option rather than blank — and survives the next save, which clears
  592. # any value the editor does not recognise.
  593. #
  594. # A module-0x0C row is safe here despite the warning above: that warning is
  595. # about matching on the module alone, and 0C00_8042 is a full short code
  596. # with a documented meaning ("The AI print monitor has detected a spaghetti
  597. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  598. # cannot collide.
  599. #
  600. # 0300_8003's own text ends "before continuing your print", but on an X2D
  601. # it arrives with the print already paused, offering only
  602. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  603. #
  604. # Two neighbours are left out on purpose, so this does not get re-derived:
  605. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  606. # reads as a warning about a print that is still running, not a halt.
  607. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  608. # the waste chute. That is not the print failing.
  609. #
  610. # That line is drawn from the text, not from `severity`, because severity
  611. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  612. # module/error word with no level in it, and bambu_mqtt.py gives every
  613. # print_error entry a flat severity=3. Matching on the short code alone is
  614. # the right shape for derive_failure_reason, not an omission.
  615. "0300_8003": "spaghettiDetached",
  616. "0C00_8042": "spaghettiDetached",
  617. }
  618. def _hms_short_code(attr: int, code: int | str) -> str:
  619. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  620. if isinstance(code, str):
  621. code_int = int(code.replace("0x", ""), 16) if code else 0
  622. else:
  623. code_int = int(code or 0)
  624. attr_int = int(attr or 0)
  625. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  626. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  627. """Derive the failure_reason key for an archived print.
  628. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  629. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  630. no HMS code matches (don't guess — null is honest). The keys are the
  631. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  632. translated at render time.
  633. """
  634. if status in ("aborted", "cancelled"):
  635. return "userCancelled"
  636. if status != "failed":
  637. return None
  638. for err in hms_errors or []:
  639. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  640. if short_code in _HMS_FAILURE_REASONS:
  641. return _HMS_FAILURE_REASONS[short_code]
  642. return None
  643. # Track created_by_id for expected prints so the user email can be sent even when
  644. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  645. # {(printer_id, filename): created_by_id}
  646. _expected_print_creators: dict[tuple[int, str], int] = {}
  647. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  648. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  649. # tag tuple changes for the slot. Cleared when the slot is reported empty
  650. # so remove + reinsert reliably re-prompts the UI.
  651. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  652. async def _broadcast_unknown_tag(
  653. *,
  654. printer_id: int,
  655. ams_id: int,
  656. tray_id: int,
  657. tag_uid: str,
  658. tray_uuid: str,
  659. tray_type: str | None = None,
  660. tray_color: str | None = None,
  661. tray_sub_brands: str | None = None,
  662. tray_count: int | None = None,
  663. ) -> None:
  664. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  665. _logger = logging.getLogger(__name__)
  666. slot_key = (ams_id, tray_id)
  667. tag_key = (tag_uid or "", tray_uuid or "")
  668. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  669. if per_printer.get(slot_key) == tag_key:
  670. _logger.debug(
  671. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  672. printer_id,
  673. ams_id,
  674. tray_id,
  675. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  676. )
  677. return
  678. _logger.info(
  679. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  680. printer_id,
  681. ams_id,
  682. tray_id,
  683. tray_type,
  684. tray_color,
  685. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  686. )
  687. # Broadcast first; only commit the dedup if the WS write succeeds.
  688. # If broadcast raises, the next MQTT push retries instead of being
  689. # permanently silenced by a poisoned dedup entry.
  690. await ws_manager.broadcast(
  691. {
  692. "type": "unknown_tag",
  693. "printer_id": printer_id,
  694. "ams_id": ams_id,
  695. "tray_id": tray_id,
  696. "tag_uid": tag_uid,
  697. "tray_uuid": tray_uuid,
  698. "tray_type": tray_type,
  699. "tray_color": tray_color,
  700. "tray_sub_brands": tray_sub_brands,
  701. "tray_count": tray_count,
  702. }
  703. )
  704. per_printer[slot_key] = tag_key
  705. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  706. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  707. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  708. if per_printer is None:
  709. return
  710. per_printer.pop((ams_id, tray_id), None)
  711. # TTL for expected-print entries: evict registrations older than this to prevent
  712. # unbounded growth when a print is registered but never starts (e.g. printer
  713. # disconnect, app restart, print started from the printer panel).
  714. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  715. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  716. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  717. # Cleanup loop interval
  718. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  719. _expected_prints_cleanup_task: asyncio.Task | None = None
  720. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  721. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  722. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  723. possible_keys: list[tuple[int, str]] = []
  724. filename = (state.gcode_file or state.current_print or "").strip()
  725. subtask_name = (state.subtask_name or "").strip()
  726. if subtask_name:
  727. possible_keys.append((printer_id, subtask_name))
  728. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  729. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  730. if filename:
  731. base_name = filename.rsplit("/", 1)[-1]
  732. if base_name.endswith(".gcode.3mf"):
  733. root_name = base_name[: -len(".gcode.3mf")]
  734. possible_keys.append((printer_id, root_name))
  735. possible_keys.append((printer_id, base_name))
  736. possible_keys.append((printer_id, f"{root_name}.gcode"))
  737. possible_keys.append((printer_id, f"{root_name}.3mf"))
  738. elif base_name.endswith(".3mf"):
  739. root_name = base_name[: -len(".3mf")]
  740. possible_keys.append((printer_id, root_name))
  741. possible_keys.append((printer_id, base_name))
  742. elif base_name.endswith(".gcode"):
  743. root_name = base_name[: -len(".gcode")]
  744. possible_keys.append((printer_id, root_name))
  745. possible_keys.append((printer_id, f"{root_name}.3mf"))
  746. possible_keys.append((printer_id, base_name))
  747. else:
  748. possible_keys.append((printer_id, base_name))
  749. possible_keys.append((printer_id, f"{base_name}.3mf"))
  750. return possible_keys
  751. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  752. """The id of who started the print, unless that user has been deleted since.
  753. Deleting a user forgets them in printer_manager, but a print that ended a
  754. moment before still holds them.
  755. """
  756. if not print_user or print_user.get("user_id") is None:
  757. return None
  758. from backend.app.models.user import User
  759. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  760. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  761. """Check the cheap, process-local print ownership signals."""
  762. if printer_manager.get_current_print_user(printer_id):
  763. return True
  764. return any(
  765. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  766. for key in _build_status_print_keys(printer_id, state)
  767. )
  768. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  769. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  770. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  771. async def _printing_archive_without_job_id(
  772. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  773. ):
  774. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  775. An archive with a real id of its own is a print that reported one: a "0"
  776. print is not it, even under the same name (one whose completion was missed
  777. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  778. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  779. """
  780. from backend.app.models.archive import PrintArchive
  781. query = select(PrintArchive).where(
  782. PrintArchive.printer_id == printer_id,
  783. PrintArchive.status == "printing",
  784. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  785. )
  786. if dispatched_only:
  787. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  788. if live_only:
  789. query = query.where(PrintArchive.deleted_at.is_(None))
  790. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  791. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  792. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  793. """The archive of the print running on ``printer_id``, or None (#3327).
  794. By the print's subtask_id first, which the firmware mints per print; with
  795. ``printing_only`` only an archive that is still printing (a leftover row of
  796. a completion never seen must not stand in for another job). A print
  797. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  798. screen) reports subtask_id "0", which links it to nothing: the archive
  799. Bambuddy bound to the running print comes next, the one completion charges
  800. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  801. own prints, so with ``by_name`` a "0" print last falls back to its printing
  802. archive under the name the printer reports. That can be an earlier run of
  803. the same name whose completion was missed while Bambuddy was down: good
  804. enough for a plate label or a cover, not for which objects skip-objects
  805. offers, so those callers leave it off. None until the archive exists, and
  806. never a deleted one.
  807. """
  808. from backend.app.models.archive import PrintArchive
  809. from backend.app.services.print_log import open_run_on_printer
  810. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  811. if subtask_id not in ("", "0"):
  812. # The run open on the printer for this job: the archive row is shared
  813. # by every plate of it, its printer and job id the latest start's.
  814. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  815. if run is not None and run.archive_id is not None:
  816. archive = await db.scalar(
  817. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  818. )
  819. if archive is not None:
  820. return archive
  821. query = select(PrintArchive).where(
  822. PrintArchive.printer_id == printer_id,
  823. PrintArchive.subtask_id == subtask_id,
  824. PrintArchive.deleted_at.is_(None),
  825. )
  826. if printing_only:
  827. query = query.where(PrintArchive.status == "printing")
  828. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  829. if archive is not None:
  830. return archive
  831. bound = next(
  832. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  833. None,
  834. )
  835. if bound is not None:
  836. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  837. if not by_name or subtask_id != "0":
  838. return None
  839. reported = _reported_print_names(printer_id, state)
  840. if not reported:
  841. return None
  842. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  843. def _bind_active_print(
  844. printer_id: int,
  845. archive_id: int,
  846. archive_filename: str | None,
  847. filename: str | None = None,
  848. subtask_name: str | None = None,
  849. ) -> None:
  850. """Track a running print under every name its completion may report.
  851. One set for every path that binds a print (new archive, expected print,
  852. restart resume, fallback): the archive's file name, the name the printer
  853. reported, and the subtask with and without ``.3mf``. Paths that registered
  854. fewer names lost the bound archive at completion, and with it the plate
  855. restore's height (#3240), whenever MQTT reported a name they had left out.
  856. """
  857. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  858. if name:
  859. _active_prints[(printer_id, name)] = archive_id
  860. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  861. """The archive of the run open on the printer, if it is still there.
  862. With ``subtask_id``, only a run of that job."""
  863. try:
  864. from backend.app.models.archive import PrintArchive
  865. from backend.app.services.print_log import open_run_on_printer
  866. async with async_session() as db:
  867. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  868. if run is None or run.archive_id is None:
  869. return None
  870. return await db.scalar(
  871. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  872. )
  873. except Exception as e:
  874. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  875. return None
  876. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  877. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  878. each announced by run/started, now gone without an end."""
  879. if not discarded:
  880. return
  881. try:
  882. from backend.app.models.printer import Printer
  883. async with async_session() as db:
  884. printer = (
  885. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  886. ).first()
  887. if printer is not None:
  888. for run in discarded:
  889. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  890. except Exception as e:
  891. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  892. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  893. """Publish the run a print's end just wrote on the MQTT relay (archive
  894. redesign); nothing without one. Never in the way of the completion."""
  895. if run_id is None:
  896. return
  897. try:
  898. from backend.app.models.archive import PrintArchive
  899. from backend.app.models.print_log import PrintLogEntry
  900. from backend.app.models.printer import Printer
  901. async with async_session() as db:
  902. run = await db.get(PrintLogEntry, run_id)
  903. printer = (
  904. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  905. ).first()
  906. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  907. if run is not None and printer is not None:
  908. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  909. except Exception as e:
  910. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  911. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  912. """Write the run of the print that just started on the archive (archive
  913. redesign). In a session of its own and never in the way of the print
  914. start: until its readers move over, the archive still carries the print.
  915. The archive's start must be committed before. ``subtask_id`` is the
  916. printer's job, which finds the run again at a resume."""
  917. try:
  918. from backend.app.models.archive import PrintArchive
  919. from backend.app.models.printer import Printer
  920. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  921. async with async_session() as db:
  922. archive = await db.get(PrintArchive, archive_id)
  923. if archive is None:
  924. return
  925. printer = (
  926. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  927. ).first()
  928. printer_name = printer.name if printer is not None else None
  929. already = await open_run_on_printer(db, printer_id)
  930. before = run_snapshot(already) if already is not None else None
  931. run = await open_run(
  932. db,
  933. archive,
  934. printer_id=printer_id,
  935. printer_name=printer_name,
  936. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  937. subtask_id=subtask_id,
  938. )
  939. await db.commit()
  940. # Once per print: a resume or a repeated start finds the run it opened.
  941. # A new one replaced the run still open there (open_run): that one's
  942. # print ended unseen.
  943. # Compared by start too: SQLite can give the new run the id of the one
  944. # it replaced.
  945. replaced = (
  946. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  947. )
  948. if run is not None and printer is not None and (before is None or replaced):
  949. if replaced:
  950. await _announce_discarded_runs([before], printer_id)
  951. try:
  952. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  953. except Exception:
  954. pass # Don't fail the print start if MQTT fails
  955. except Exception as e:
  956. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  957. async def _drop_replaced_plate_videos(
  958. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  959. ) -> None:
  960. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  961. one the archive showed (when print start judged it this plate's), and
  962. those of the archive's earlier runs of the same plate. A plate keeps one
  963. video, as when the archive held the only one; another plate's stays. The
  964. runs that held them lose them. Commits."""
  965. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  966. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  967. runs = select(PrintLogEntry).where(
  968. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  969. )
  970. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  971. paths = {stale_relpath} if stale_relpath else set()
  972. if plate_id is not None:
  973. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  974. # A video another plate's run holds is that plate's.
  975. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  976. if not paths:
  977. return
  978. for run in with_video:
  979. if run.timelapse_path in paths:
  980. run.timelapse_path = None
  981. await db.commit()
  982. for relpath in sorted(p for p in paths if p):
  983. try:
  984. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  985. if stale_path.is_file():
  986. stale_path.unlink()
  987. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  988. except (OSError, PathTraversalError) as e:
  989. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  990. def _mark_owned_if_dispatched(archive) -> None:
  991. """Remember a running print's archive as Bambuddy's when it carries a
  992. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  993. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  994. if archive.billing_run_id is not None or archive.created_by_id is not None:
  995. _owned_print_archive_ids.add(archive.id)
  996. async def _is_printer_kill_switch_enabled_cached() -> bool:
  997. """Return the kill-switch setting without querying on every MQTT frame."""
  998. global _kill_switch_setting_cache
  999. now = time.monotonic()
  1000. if _kill_switch_setting_cache is not None:
  1001. enabled, expires_at = _kill_switch_setting_cache
  1002. if now < expires_at:
  1003. return enabled
  1004. async with async_session() as db:
  1005. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1006. enabled = await is_printer_kill_switch_enabled(db)
  1007. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1008. return enabled
  1009. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1010. """Resolve whether the current print was started by Bambuddy.
  1011. ``None`` means identity is not yet safe to decide. The kill switch must
  1012. defer in that case: stopping a print is irreversible, and the first status
  1013. frames after a restart may arrive before all subtask fields are populated.
  1014. """
  1015. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1016. return True
  1017. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1018. # printer's screen) play gcode from its read-only system partition, where no
  1019. # user file can be. Only that path counts: a calibration *name* proves
  1020. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1021. # path, and any print can be given that name.
  1022. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1023. return True
  1024. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1025. # which nothing distinguishes from a user's file given that name, so it is
  1026. # not exempt: with the kill switch on, calibrate on those printers with the
  1027. # switch off.
  1028. possible_keys = _build_status_print_keys(printer_id, state)
  1029. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1030. # is on disk. subtask_id is minted per print and pins the answer to the job
  1031. # actually running, rather than to an unrelated one that reuses a filename.
  1032. raw_subtask_id = getattr(state, "subtask_id", None)
  1033. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1034. if subtask_id == "":
  1035. # Not reported yet: the first frames after a restart can lack it.
  1036. return None
  1037. from backend.app.models.archive import PrintArchive
  1038. if subtask_id == "0":
  1039. # A print started outside the cloud from Bambu Studio, Handy or the
  1040. # printer's screen reports "0", so there is no id to match: one of
  1041. # Bambuddy's printing archives on this printer under the name the
  1042. # printer reports, compared as the printer echoes names (spaces become
  1043. # underscores). Nothing reported to compare yet: wait.
  1044. reported = _reported_print_names(printer_id, state)
  1045. if not reported:
  1046. return None
  1047. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1048. else:
  1049. from backend.app.services.print_log import open_run_on_printer
  1050. # This job's run open on the printer: the archive is shared by every
  1051. # plate of it, and its status, printer and job id are the latest
  1052. # start's, which may be another printer's.
  1053. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1054. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1055. if archive is None:
  1056. result = await db.execute(
  1057. select(PrintArchive)
  1058. .where(
  1059. PrintArchive.printer_id == printer_id,
  1060. PrintArchive.status == "printing",
  1061. PrintArchive.subtask_id == subtask_id,
  1062. )
  1063. .order_by(PrintArchive.created_at.desc())
  1064. .limit(1)
  1065. )
  1066. archive = result.scalar_one_or_none()
  1067. # An archive row on its own proves nothing: `on_print_start` archives every
  1068. # print it observes, including ones started from Bambu Studio or Handy, and
  1069. # stamps them with the same status and subtask_id. Authorizing on its mere
  1070. # existence would disable the kill switch the moment the 3MF finishes
  1071. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1072. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1073. # (carried over from the queue item that started it).
  1074. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1075. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1076. # both the archive filename and every normalized key reported by MQTT.
  1077. _owned_print_archive_ids.add(archive.id)
  1078. _active_prints[(printer_id, archive.filename)] = archive.id
  1079. for key in possible_keys:
  1080. _active_prints[key] = archive.id
  1081. return True
  1082. # No dispatch marker. Before calling this someone else's print, check whether
  1083. # Bambuddy has a job of its own running on this printer: a library-file
  1084. # dispatch has no archive at send time, and an archive created seconds later
  1085. # by `on_print_start` carries neither marker. The queue row, which the
  1086. # scheduler commits to status="printing" before the MQTT send, is the one
  1087. # durable record every Bambuddy print has. It cannot be tied to this
  1088. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1089. # print is irreversible, and refusing to act costs nothing but a log line.
  1090. from backend.app.models.print_queue import PrintQueueItem
  1091. dispatched_here = await db.scalar(
  1092. select(PrintQueueItem.id)
  1093. .where(
  1094. PrintQueueItem.printer_id == printer_id,
  1095. PrintQueueItem.status == "printing",
  1096. )
  1097. .limit(1)
  1098. )
  1099. if dispatched_here is not None:
  1100. return None
  1101. return False
  1102. async def _send_kill_switch_provider_notification(
  1103. printer_id: int,
  1104. printer_name: str,
  1105. data: dict,
  1106. ) -> bool:
  1107. """Send the immediate print-stopped provider notification.
  1108. Returning a success flag lets the normal MQTT completion path retry when
  1109. this early notification could not be delivered.
  1110. """
  1111. logger = logging.getLogger(__name__)
  1112. try:
  1113. async with async_session() as db:
  1114. from backend.app.services.print_log import open_run_on_printer
  1115. # The print it stopped, for {archive_id} / {run_id}: the completion
  1116. # that would name them skips its notification after this one.
  1117. run = await open_run_on_printer(db, printer_id)
  1118. await notification_service.on_print_complete(
  1119. printer_id,
  1120. printer_name,
  1121. "stopped",
  1122. data,
  1123. db,
  1124. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1125. )
  1126. return True
  1127. except Exception as e:
  1128. logger.warning(
  1129. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1130. printer_id,
  1131. e,
  1132. )
  1133. return False
  1134. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1135. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1136. if task is None:
  1137. return False
  1138. try:
  1139. return await task
  1140. except Exception as e:
  1141. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1142. return False
  1143. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1144. """At a resume: whether the print's run still lacks its energy start
  1145. reading. The archive's may be an earlier print's. Commits a reading
  1146. found on the archive for this run onto it."""
  1147. try:
  1148. from backend.app.services.print_log import run_needs_energy_start
  1149. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1150. await db.commit()
  1151. return needs
  1152. except Exception as e:
  1153. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1154. return archive.energy_start_kwh is None
  1155. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1156. """Capture the smart plug lifetime counter on the archive at print start.
  1157. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1158. tracking survives a backend restart mid-print. The print-end handler reads
  1159. this value back from the DB and computes the delta against the current
  1160. plug counter.
  1161. """
  1162. _logger = logging.getLogger(__name__)
  1163. try:
  1164. candidates = await energy_plug_candidates(db, printer_id)
  1165. if not candidates:
  1166. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1167. return False
  1168. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1169. if selected is None:
  1170. # Naming the plugs matters here: with several linked to one printer
  1171. # this is the difference between "the meter is offline" and "you
  1172. # linked only accessories" (#2859).
  1173. _logger.warning(
  1174. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1175. printer_id,
  1176. archive.id,
  1177. ", ".join(plug.name for plug in candidates),
  1178. )
  1179. return False
  1180. plug, energy = selected
  1181. archive.energy_start_kwh = float(energy["total"])
  1182. # With the plug's snapshots, what lets the cost follow the price over
  1183. # the print rather than take the price at its end (#1251). A price that
  1184. # can't be had must not cost the print its energy reading.
  1185. archive.energy_start_at = utcnow_naive()
  1186. archive.energy_start_plug_id = plug.id
  1187. try:
  1188. from backend.app.services.energy_price import current_price
  1189. archive.energy_start_price = await current_price(db)
  1190. except Exception as e:
  1191. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1192. archive.energy_start_price = None
  1193. try:
  1194. from backend.app.services.print_log import mirror_energy_start
  1195. await mirror_energy_start(db, archive, printer_id=printer_id)
  1196. except Exception as e:
  1197. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1198. await db.commit()
  1199. _logger.info(
  1200. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1201. f" ({context})" if context else "",
  1202. archive.id,
  1203. plug.name,
  1204. energy["total"],
  1205. )
  1206. return True
  1207. except Exception as e:
  1208. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1209. return False
  1210. def forget_print_creator(user_id: int) -> None:
  1211. """The print-start emails of a deleted user's jobs go to nobody, not to
  1212. whoever is given the id next (SQLite reuses it)."""
  1213. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1214. del _expected_print_creators[key]
  1215. async def forget_printer(printer_id: int) -> None:
  1216. """Drop what is kept for a deleted printer's id, here and in the services.
  1217. SQLite used to give the id to the next printer created, which inherited it
  1218. all: the running print's owner (its prints passed the kill switch and were
  1219. billed to that user), the plate-clear gate, pending and suppressed
  1220. notifications, the camera feed, the plate references. Ids are no longer
  1221. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1222. stay. Called after the delete is committed, and again by work that was in
  1223. flight and wrote state back.
  1224. Every printer-keyed map of this module is listed here or, with the reason,
  1225. in tests/unit/test_forget_printer.py.
  1226. """
  1227. from backend.app.api.routes import camera
  1228. from backend.app.services import (
  1229. bambu_ftp,
  1230. kprofile_drift,
  1231. layer_timelapse,
  1232. plate_detection,
  1233. print_dispatch_context,
  1234. usage_tracker,
  1235. )
  1236. from backend.app.services.notify_live_activities import notify_live_activities
  1237. from backend.app.services.obico_detection import obico_detection_service
  1238. from backend.app.services.printer_file_cache import printer_file_cache
  1239. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1240. archive_ids = set()
  1241. for tracked in (_active_prints, _expected_prints):
  1242. for key in [key for key in tracked if key[0] == printer_id]:
  1243. archive_ids.add(tracked.pop(key))
  1244. for archive_id in archive_ids:
  1245. _owned_print_archive_ids.discard(archive_id)
  1246. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1247. for key in [key for key in registered if key[0] == printer_id]:
  1248. del registered[key]
  1249. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1250. for key in [key for key in tracked if key[0] == printer_id]:
  1251. del tracked[key]
  1252. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1253. _ams_index_only_logged.discard(key)
  1254. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1255. del _ams_alarm_cooldown[key]
  1256. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1257. # A kill-switch notice is about a stop that happened and is left to finish.
  1258. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1259. task = tasks.pop(printer_id, None)
  1260. if task is not None:
  1261. task.cancel()
  1262. for keyed in (
  1263. _stage22_finish_frames,
  1264. _stage22_finish_in_flight,
  1265. _inprint_frame_bank,
  1266. _inprint_frame_bank_ts,
  1267. _printer_reconciled_since_connect,
  1268. _printer_kprofiles_primed_since_connect,
  1269. _last_progress_milestone,
  1270. _first_layer_notified,
  1271. _kill_switch_notification_tasks,
  1272. _notified_hms_errors,
  1273. _hms_print_state,
  1274. _hms_forget_when_gone,
  1275. _timelapse_baselines,
  1276. _bed_cool_waiters,
  1277. _printer_last_connected,
  1278. _unknown_tag_last_broadcast,
  1279. _last_status_broadcast,
  1280. _connection_watchdog_last_attempt,
  1281. ):
  1282. keyed.pop(printer_id, None)
  1283. for marked in (
  1284. _unauthorized_print_kill_sent,
  1285. _user_stopped_printers,
  1286. _kill_switch_stopped,
  1287. _printer_offline_published,
  1288. _nozzle_count_updated,
  1289. _runtime_seen_connected,
  1290. _timelapse_baselines_unread,
  1291. ):
  1292. marked.discard(printer_id)
  1293. printer_manager.forget_printer(printer_id)
  1294. printer_file_cache.forget_printer(printer_id)
  1295. print_dispatch_context.clear(printer_id)
  1296. kprofile_drift.forget_printer(printer_id, deleted=True)
  1297. layer_timelapse.cancel_session(printer_id)
  1298. usage_tracker.forget_printer(printer_id)
  1299. obico_detection_service.forget_printer(printer_id)
  1300. bambu_ftp.clear_3mf_cache(printer_id)
  1301. await camera.forget_printer(printer_id)
  1302. printers.clear_cover_cache(printer_id)
  1303. print_scheduler.forget_printer(printer_id)
  1304. notify_live_activities.forget_printer(printer_id)
  1305. plate_detection.remove_printer_references(printer_id)
  1306. def register_expected_print(
  1307. printer_id: int,
  1308. filename: str,
  1309. archive_id: int,
  1310. ams_mapping: list[int] | None = None,
  1311. created_by_id: int | None = None,
  1312. cost_center_id: int | None = None,
  1313. plate_id: int | None = None,
  1314. ):
  1315. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1316. # Store with multiple filename variations to catch different naming patterns
  1317. _expected_prints[(printer_id, filename)] = archive_id
  1318. # Also store without .3mf extension if present
  1319. if filename.endswith(".3mf"):
  1320. base = filename[:-4]
  1321. _expected_prints[(printer_id, base)] = archive_id
  1322. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1323. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1324. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1325. # path attributes the whole file's filament total to the spool instead of just
  1326. # the printed plate (#1697). They describe this dispatch: one that has none
  1327. # drops what an earlier dispatch of the archive left (sent, never started),
  1328. # unless a plate of the archive is printing now and still needs them.
  1329. dispatch = (printer_id, archive_id)
  1330. archive_printing = _printing_here(printer_id, archive_id)
  1331. if ams_mapping is not None:
  1332. _print_ams_mappings[dispatch] = ams_mapping
  1333. elif not archive_printing:
  1334. _print_ams_mappings.pop(dispatch, None)
  1335. if cost_center_id is not None:
  1336. _print_cost_center_ids[dispatch] = cost_center_id
  1337. elif not archive_printing:
  1338. _print_cost_center_ids.pop(dispatch, None)
  1339. if plate_id is not None:
  1340. _print_plate_ids[dispatch] = plate_id
  1341. elif not archive_printing:
  1342. _print_plate_ids.pop(dispatch, None)
  1343. # Store created_by_id so the user start email can be sent even when the archive
  1344. # itself has no created_by_id (e.g. library-file-based queue prints)
  1345. if created_by_id is not None:
  1346. _expected_print_creators[(printer_id, filename)] = created_by_id
  1347. if filename.endswith(".3mf"):
  1348. base = filename[:-4]
  1349. _expected_print_creators[(printer_id, base)] = created_by_id
  1350. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1351. # Record registration time for TTL-based eviction
  1352. _registered_at = time.monotonic()
  1353. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1354. if filename.endswith(".3mf"):
  1355. base = filename[:-4]
  1356. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1357. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1358. logging.getLogger(__name__).info(
  1359. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1360. )
  1361. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1362. """Undo :func:`register_expected_print` when the print never went out.
  1363. Registration has to happen *before* the MQTT print command, because the
  1364. printer can report the print before the line after the send executes. So
  1365. every path that registers and then fails to send — a cancel winning the
  1366. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1367. between — leaves an expectation for a print that will never arrive.
  1368. The TTL sweep evicts those after two hours, which is far longer than it
  1369. takes a user to react to a failed dispatch by pressing print again: that
  1370. reprint would be folded into the *old* archive and take the stale
  1371. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1372. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1373. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1374. are keyed by printer and archive, not by file, so they may only be dropped
  1375. once no live key of the printer still points at that archive.
  1376. """
  1377. keys = [(printer_id, filename)]
  1378. if filename.endswith(".3mf"):
  1379. base = filename[:-4]
  1380. keys.append((printer_id, base))
  1381. keys.append((printer_id, f"{base}.gcode"))
  1382. removed = False
  1383. for key in keys:
  1384. if _expected_prints.pop(key, None) is not None:
  1385. removed = True
  1386. _expected_print_creators.pop(key, None)
  1387. _expected_print_registered_at.pop(key, None)
  1388. # Still needed by another expected print of the archive on the printer,
  1389. # or a plate of it printing there, as in the sweep.
  1390. if not _expected_or_printing_here(printer_id, archive_id):
  1391. _drop_dispatch(printer_id, archive_id)
  1392. if removed:
  1393. logging.getLogger(__name__).info(
  1394. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1395. printer_id,
  1396. filename,
  1397. archive_id,
  1398. )
  1399. def _compute_run_filament_grams(
  1400. status: str,
  1401. archive_filament_used_grams: float | None,
  1402. progress: float | int | None,
  1403. usage_results: list[dict] | None,
  1404. ) -> float | None:
  1405. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1406. Priority for every status:
  1407. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1408. weight delta — same source that drives "Total Consumed" on the
  1409. Inventory page, so Stats and Inventory totals stay aligned).
  1410. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1411. back to the canonical "this print used X" value).
  1412. 3. For partial statuses: ``estimate * progress%``.
  1413. 4. ``None`` if nothing is known.
  1414. """
  1415. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1416. if tracked_grams > 0:
  1417. return round(tracked_grams, 1)
  1418. if status == "completed":
  1419. return archive_filament_used_grams
  1420. if archive_filament_used_grams:
  1421. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1422. if scale > 0:
  1423. return round(archive_filament_used_grams * scale, 1)
  1424. return None
  1425. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1426. """Whether a plate of the archive is printing on the printer."""
  1427. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1428. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1429. """Whether a print of the archive is expected or printing on the printer."""
  1430. return _printing_here(printer_id, archive_id) or any(
  1431. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1432. )
  1433. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1434. """Forget what the dispatch of the archive to the printer registered."""
  1435. dispatch = (printer_id, archive_id)
  1436. _print_ams_mappings.pop(dispatch, None)
  1437. _print_cost_center_ids.pop(dispatch, None)
  1438. _print_plate_ids.pop(dispatch, None)
  1439. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1440. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1441. stored_ams_mapping = data.get("ams_mapping")
  1442. if not stored_ams_mapping and archive_id:
  1443. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1444. return stored_ams_mapping
  1445. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1446. """Resolve plate_id for print start without consuming stored direct-Print state.
  1447. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1448. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1449. read it back at print-start without popping (the entry is popped on print
  1450. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1451. """
  1452. if archive_id is None:
  1453. return None
  1454. return _print_plate_ids.get((printer_id, archive_id))
  1455. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1456. """The slicer's time for the plate this print prints, for its start
  1457. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1458. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1459. whole file's time when its plates are not known; None for a plate not
  1460. known of several, and the notification takes the printer's remaining
  1461. time."""
  1462. from backend.app.services.print_cost_estimate import run_estimate
  1463. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1464. estimate = run_estimate(archive, plate_id)
  1465. return estimate.seconds if estimate is not None else None
  1466. _plate_estimates_task: asyncio.Task | None = None
  1467. async def _fill_plate_estimates() -> None:
  1468. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1469. try:
  1470. filled = await fill_plate_estimates(async_session)
  1471. except asyncio.CancelledError:
  1472. raise
  1473. except Exception as exc:
  1474. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1475. return
  1476. if filled:
  1477. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1478. def _partial_progress_scale(progress: int | float | None) -> float:
  1479. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1480. Used by every site that multiplies a "would-have-used" slicer estimate
  1481. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1482. so the three sites in ``_background_notifications`` (and the per-plate
  1483. override helper) can't drift apart on the coercion shape.
  1484. """
  1485. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1486. def _scope_notification_archive_data_to_plate(
  1487. archive_data: dict,
  1488. archive_file_path: str | None,
  1489. plate_id: int | None,
  1490. print_status: str,
  1491. progress: int | float | None,
  1492. base_dir: Path,
  1493. ) -> dict:
  1494. """Override summed-across-plates totals in ``archive_data`` with the values
  1495. for ``plate_id`` so the completion notification reports what was actually
  1496. printed, not the whole project (#1785).
  1497. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1498. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1499. the archive card's "whole project" headline, wrong for the completion
  1500. notification of a single-plate print. The queue UI already re-reads the
  1501. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1502. notification payload (filament grams, time estimate, per-slot breakdown).
  1503. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1504. no per-plate values — in every fail case the original ``archive_data`` is
  1505. returned unchanged so the notification still sends.
  1506. """
  1507. if plate_id is None or not archive_file_path:
  1508. return archive_data
  1509. from backend.app.utils.threemf_tools import (
  1510. extract_filament_usage_from_3mf,
  1511. extract_print_time_from_3mf,
  1512. )
  1513. archive_path = base_dir / archive_file_path
  1514. if not archive_path.exists():
  1515. return archive_data
  1516. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1517. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1518. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1519. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1520. if plate_time:
  1521. archive_data["print_time_seconds"] = plate_time
  1522. # Gate both the grams headline AND the per-slot breakdown on the same
  1523. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1524. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1525. # to the project-level grams the archive columns already provide rather
  1526. # than ship a project-level headline next to an all-zero per-plate
  1527. # breakdown.
  1528. if plate_grams > 0:
  1529. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1530. archive_data["filament_slots"] = [
  1531. {
  1532. "slot_id": s.get("slot_id"),
  1533. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1534. "type": s.get("type", ""),
  1535. "color": s.get("color", ""),
  1536. }
  1537. for s in plate_slots
  1538. ]
  1539. return archive_data
  1540. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1541. """Best-effort filament metadata from the MQTT print-start snapshot.
  1542. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1543. file during print, see #1533) so the fallback PrintArchive still has
  1544. enough filament info to support the inventory views and AMS-expansion
  1545. planning the operator opens it for. Returns a dict with optional
  1546. ``filament_type`` and ``filament_color`` keys in the same
  1547. comma-separated format the 3MF extractor produces, so the rest of the
  1548. codebase treats the fallback archive identically to a normal one.
  1549. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1550. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1551. entries). When supplied, only the slots actually consumed by this
  1552. print contribute. Without it the function falls back to every loaded
  1553. AMS slot — less accurate but still useful.
  1554. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1555. that the unit tests pass directly, AND the on_print_start callback
  1556. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1557. bambu_mqtt service hands to main.py at runtime. The original
  1558. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1559. handled the inner shape and silently returned ``{}`` for every real
  1560. print start, leaving fallback archives' filament fields NULL — the
  1561. exact regression the fix was meant to close. Reported with a log
  1562. proving the AMS state was right there at
  1563. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1564. """
  1565. result: dict[str, str] = {}
  1566. # Look at the on_print_start wrapper first, then the inner shape.
  1567. raw_data = (data or {}).get("raw_data")
  1568. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1569. if not isinstance(ams_root, dict):
  1570. ams_root = (data or {}).get("ams") or {}
  1571. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1572. if not isinstance(ams_units, list) or not ams_units:
  1573. return result
  1574. from backend.app.services.print_scheduler import _global_tray_id
  1575. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1576. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1577. loaded: dict[int, tuple[str, str]] = {}
  1578. for unit in ams_units:
  1579. if not isinstance(unit, dict):
  1580. continue
  1581. try:
  1582. unit_id = int(unit.get("id", 0))
  1583. except (TypeError, ValueError):
  1584. continue
  1585. for tray in unit.get("tray") or []:
  1586. if not isinstance(tray, dict):
  1587. continue
  1588. try:
  1589. tray_id = int(tray.get("id", 0))
  1590. except (TypeError, ValueError):
  1591. continue
  1592. ttype = (tray.get("tray_type") or "").strip()
  1593. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1594. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1595. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1596. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1597. if not ttype:
  1598. continue # Empty / unloaded slot.
  1599. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1600. if not loaded:
  1601. return result
  1602. if ams_mapping:
  1603. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1604. filaments = [loaded[g] for g in used_ids if g in loaded]
  1605. if not filaments:
  1606. return result # Mapping points entirely at slots we have no data for.
  1607. else:
  1608. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1609. types_joined = ",".join(f[0] for f in filaments)
  1610. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1611. # Column limits per backend/app/models/archive.py: filament_type=50,
  1612. # filament_color=200.
  1613. if types_joined:
  1614. result["filament_type"] = types_joined[:50]
  1615. if colors_joined:
  1616. result["filament_color"] = colors_joined[:200]
  1617. return result
  1618. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1619. """Start a layer-timelapse session for *archive_id* when the printer has
  1620. an external camera configured. Returns True if a session was started.
  1621. Three call sites in on_print_start (expected-archive promotion, fallback
  1622. archive creation, fresh-archive creation) used to inline this same
  1623. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1624. on the first pass). Centralising the conditional + call here makes the
  1625. contract testable in isolation and keeps the three sites locked in step.
  1626. """
  1627. if not (printer.external_camera_enabled and printer.external_camera_url):
  1628. return False
  1629. from backend.app.services.layer_timelapse import start_session
  1630. start_session(
  1631. printer_id,
  1632. archive_id,
  1633. printer.external_camera_url,
  1634. printer.external_camera_type or "mjpeg",
  1635. snapshot_url=printer.external_camera_snapshot_url,
  1636. rotation=getattr(printer, "camera_rotation", 0),
  1637. )
  1638. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1639. return True
  1640. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1641. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1642. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1643. — since #2926 — the description the parser already resolved, which is preferred
  1644. when present so the queue's failure reason reads the same as the status
  1645. response. The short code still produces the bracketed label, and still
  1646. resolves the sentence for a caller whose entries predate the field. An entry
  1647. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1648. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1649. label when no description is on file. Returns None for an empty list so
  1650. callers can leave error_message unset.
  1651. """
  1652. if not hms_errors:
  1653. return None
  1654. from backend.app.services.hms_errors import get_error_description
  1655. parts: list[str] = []
  1656. for err in hms_errors:
  1657. try:
  1658. # `_hms_short_code` rather than a local derivation: this one used to
  1659. # format the error without masking it to 16 bits, so an `hms[]` entry
  1660. # whose code carries an alert-level group produced a five-digit label
  1661. # like "0500_3000A" — not a code the user can look up, and never a
  1662. # catalogue key, so the sentence was lost with it.
  1663. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1664. except (TypeError, ValueError):
  1665. continue
  1666. description = err.get("description") or get_error_description(short_code)
  1667. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1668. # groups and is not a code anyone can look up; its full code in the
  1669. # printer screen's four groups is (#2728).
  1670. full_code = str(err.get("full_code") or "")
  1671. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1672. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1673. return "; ".join(parts) if parts else None
  1674. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1675. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1676. print completes successfully. Gated to status=='completed': failed, cancelled
  1677. and aborted prints do not count as usage. Caller is responsible for committing
  1678. the session. No-op when the queue item has no linked library file (e.g. reprints
  1679. from an archive). See #1008."""
  1680. if queue_status != "completed" or item.library_file_id is None:
  1681. return
  1682. from backend.app.models.library import LibraryFile
  1683. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1684. if lib_file is None:
  1685. return
  1686. lib_file.print_count = (lib_file.print_count or 0) + 1
  1687. lib_file.last_printed_at = datetime.now(timezone.utc)
  1688. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1689. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1690. When on_print_complete fires with status 'failed' for a printer in this set we
  1691. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1692. rather than a 'print failed' notification.
  1693. """
  1694. _user_stopped_printers.add(printer_id)
  1695. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1696. _last_status_broadcast: dict[int, str] = {}
  1697. # Track printers where we've updated nozzle_count
  1698. _nozzle_count_updated: set[int] = set()
  1699. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1700. """Wait the debounce window then fire `on_printer_offline` if the printer
  1701. is still offline.
  1702. Scheduled by `on_printer_status_change` on the connected → disconnected
  1703. edge (#1752). Cancelled by the same handler if the printer reconnects
  1704. before the window elapses, so a single MQTT blip + recovery doesn't
  1705. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1706. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1707. route through the same status-change callback, so this covers both.
  1708. """
  1709. logger = logging.getLogger(__name__)
  1710. try:
  1711. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1712. still_offline = not printer_manager.is_connected(printer_id)
  1713. logger.info(
  1714. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1715. printer_id,
  1716. still_offline,
  1717. )
  1718. if not still_offline:
  1719. return
  1720. async with async_session() as db:
  1721. from backend.app.models.printer import Printer
  1722. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1723. printer = result.scalar_one_or_none()
  1724. if not printer:
  1725. logger.warning(
  1726. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1727. printer_id,
  1728. )
  1729. return
  1730. # Recorded only when the relay can publish it, so the reconnect's
  1731. # online event always has an offline before it.
  1732. if mqtt_relay.enabled and mqtt_relay.connected:
  1733. _printer_offline_published.add(printer_id)
  1734. try:
  1735. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1736. except Exception as e:
  1737. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1738. logger.info(
  1739. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1740. printer_id,
  1741. printer.name,
  1742. )
  1743. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1744. except asyncio.CancelledError:
  1745. raise
  1746. except Exception as e:
  1747. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1748. finally:
  1749. _printer_offline_notify_tasks.pop(printer_id, None)
  1750. def _hms_notify_key(error) -> str:
  1751. """What identifies a fault for notification de-duplication.
  1752. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1753. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1754. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1755. and -0006 together) shared a key and only the first was ever notified. An
  1756. entry without a full code falls back to attr and code together.
  1757. """
  1758. full_code = getattr(error, "full_code", "") or ""
  1759. if full_code:
  1760. return full_code.upper()
  1761. return f"{error.attr:08X}:{error.code}"
  1762. def _hms_fault_counts(error) -> bool:
  1763. """Whether a fault counts as a problem: the same rule the frontend's
  1764. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1765. It counts when Bambu publishes text for it or it offers action buttons, and
  1766. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1767. no actions does not count: those are things like "the top cover is open" or
  1768. "the chamber is hot, fan speed increased", which a printer can hold through
  1769. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1770. it always has; those are prompts such as "unable to start drying" (#2728).
  1771. """
  1772. if error.severity < 1:
  1773. return False
  1774. has_actions = bool(getattr(error, "actions", None))
  1775. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1776. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1777. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1778. """The new faults that count (see ``_hms_fault_counts``).
  1779. These go to the MQTT relay; the caller also needs a description before it
  1780. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1781. used to read ``severity >= 2`` when severity held the part byte; on the real
  1782. level that would drop the task-stopping errors (#2728).
  1783. """
  1784. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1785. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1786. """The faults on this printer not notified yet, and record them as notified.
  1787. Tracking is updated before anything is sent, so concurrent status callbacks
  1788. cannot notify the same fault twice. A notified fault is forgotten once it
  1789. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1790. and on is notified once (#3226), while one that clears and comes back much
  1791. later is notified again.
  1792. When ``print_state`` changes (a print resumed, started or finished), every
  1793. fault recorded so far is forgotten the first time it is gone, without the
  1794. wait: a runout fixed before resuming must be notified if it happens again a
  1795. few minutes later, while the printer sits paused. Not only the faults gone
  1796. at the change itself, because the update that flips the state can still
  1797. carry the old fault (a ``print_error`` entry stays until a payload brings
  1798. ``hms``).
  1799. """
  1800. now = time.time()
  1801. current = {_hms_notify_key(e) for e in errors}
  1802. seen = _notified_hms_errors.setdefault(printer_id, {})
  1803. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1804. if print_state is not None:
  1805. print_state = print_state.upper()
  1806. if _hms_print_state.get(printer_id, print_state) != print_state:
  1807. forget_when_gone.update(seen)
  1808. _hms_print_state[printer_id] = print_state
  1809. for key, last_seen in list(seen.items()):
  1810. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1811. del seen[key]
  1812. forget_when_gone.discard(key)
  1813. new = current - seen.keys()
  1814. for key in current:
  1815. seen[key] = now
  1816. if not seen:
  1817. _notified_hms_errors.pop(printer_id, None)
  1818. if not forget_when_gone:
  1819. _hms_forget_when_gone.pop(printer_id, None)
  1820. return _hms_errors_to_notify(errors, new)
  1821. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1822. # "Printing", -1 and 255 are "no stage" (#3211).
  1823. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1824. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1825. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1826. Records it as notified. Called only for a printing state with progress above 0.
  1827. Progress before the first layer is not progress through the print (#3211).
  1828. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1829. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1830. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1831. 75% notification together with Print Started, and since 75 was then on
  1832. record, 25 and 50 could never fire. So nothing counts while the printer
  1833. reports a layer count but has not started layer 1.
  1834. Without a layer count -- a print whose first frame carried no
  1835. ``total_layer_num``, until the pushall that asks for it is answered
  1836. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1837. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1838. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1839. reports neither keeps the old behaviour rather than never notifying.
  1840. """
  1841. if (state.layer_num or 0) < 1:
  1842. if (state.total_layers or 0) > 0:
  1843. return None
  1844. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1845. return None
  1846. progress = state.progress or 0
  1847. current_milestone = 0
  1848. if progress >= 75:
  1849. current_milestone = 75
  1850. elif progress >= 50:
  1851. current_milestone = 50
  1852. elif progress >= 25:
  1853. current_milestone = 25
  1854. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1855. _last_progress_milestone[printer_id] = current_milestone
  1856. return current_milestone
  1857. return None
  1858. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1859. """Handle printer status changes - broadcast via WebSocket."""
  1860. try:
  1861. notify_live_activities.observe(printer_id, state)
  1862. except Exception:
  1863. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1864. try:
  1865. pause_eta.observe(printer_id, state)
  1866. except Exception:
  1867. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1868. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1869. # transitions disconnected → connected — which covers both Bambuddy
  1870. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1871. # `reconcile_stale_active_prints` exactly once for this connection so
  1872. # any archive still in `status="printing"` that can't actually be
  1873. # running anymore (printer IDLE / different subtask / empty subtask)
  1874. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1875. # finished during a disconnect window + a smart-plug power cycle
  1876. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1877. # next boot. Reconciliation runs concurrently — it must not block the
  1878. # WebSocket dedup / broadcast logic below, and the connected edge is
  1879. # marked True BEFORE the await so concurrent status updates inside
  1880. # the same connection don't re-trigger reconciliation.
  1881. #
  1882. # Wait for a real push_status before reconciling (#1679): MQTT
  1883. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1884. # the connection, BEFORE `_request_push_all` round-trips. At that
  1885. # instant the `PrinterState` is still on construction defaults — most
  1886. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1887. # If reconcile spawns here, every in-flight archive falls through to
  1888. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1889. # creates a duplicate archive on the real PRINT COMPLETE and
  1890. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1891. # keeps the #1542 mechanism intact: once the first real push_status
  1892. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1893. # fires again with the flag still False — reconcile then runs against
  1894. # actual evidence.
  1895. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1896. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1897. _printer_reconciled_since_connect[printer_id] = True
  1898. spawn_background_task(
  1899. reconcile_stale_active_prints(printer_id),
  1900. name=f"reconcile-stale-prints-{printer_id}",
  1901. )
  1902. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1903. # Re-arm so the next reconnect triggers reconciliation again.
  1904. _printer_reconciled_since_connect[printer_id] = False
  1905. # Same edge, for the calibration table the AMS card reads its K values from.
  1906. #
  1907. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1908. # tables to ask for. A `state_known` gate alone is not enough: the first
  1909. # real push_status is what makes the state known, and the nozzle fields do
  1910. # not always arrive in it. Latching there would spend this connection's one
  1911. # attempt on a printer that could not yet say what was fitted.
  1912. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1913. if (
  1914. state.connected
  1915. and state_known
  1916. and nozzle_known
  1917. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1918. ):
  1919. _printer_kprofiles_primed_since_connect[printer_id] = True
  1920. spawn_background_task(
  1921. prime_kprofile_table(printer_id),
  1922. name=f"prime-kprofiles-{printer_id}",
  1923. )
  1924. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1925. _printer_kprofiles_primed_since_connect[printer_id] = False
  1926. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1927. # else in the AMS report changing -- a power cycle does it to every slot --
  1928. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1929. # while the printer is idle; needs_check is cheap and throttled per slot.
  1930. # Guarded: nothing here may stop the status broadcast below.
  1931. try:
  1932. if not state.connected:
  1933. kprofile_drift.forget_printer(printer_id)
  1934. elif kprofile_drift.needs_check(printer_id, state):
  1935. spawn_background_task(
  1936. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1937. name=f"reapply-kprofiles-{printer_id}",
  1938. )
  1939. except Exception:
  1940. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1941. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1942. # connected → disconnected. The "back online" channel is already covered
  1943. # by the print-failure notification (firmware reports gcode_state=FAILED
  1944. # on reconnect of an interrupted print), so there is no online
  1945. # notification. The MQTT relay gets both: offline after the debounce, and
  1946. # online on the reconnect that follows a published offline.
  1947. prev_connected = _printer_last_connected.get(printer_id)
  1948. _printer_last_connected[printer_id] = state.connected
  1949. if prev_connected is True and not state.connected:
  1950. existing = _printer_offline_notify_tasks.get(printer_id)
  1951. if existing is None or existing.done():
  1952. logging.getLogger(__name__).info(
  1953. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1954. printer_id,
  1955. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1956. )
  1957. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1958. _maybe_notify_printer_offline(printer_id),
  1959. name=f"printer-offline-notify-{printer_id}",
  1960. )
  1961. elif state.connected:
  1962. # Kept until the relay can actually send online: with its broker down
  1963. # now, the next status update after the reconnect sends it.
  1964. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1965. _printer_offline_published.discard(printer_id)
  1966. printer_info = printer_manager.get_printer(printer_id)
  1967. if printer_info:
  1968. try:
  1969. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1970. except Exception as e:
  1971. logging.getLogger(__name__).warning(
  1972. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1973. )
  1974. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1975. if pending is not None and not pending.done():
  1976. logging.getLogger(__name__).info(
  1977. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1978. printer_id,
  1979. )
  1980. pending.cancel()
  1981. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1982. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1983. temps = state.temperatures or {}
  1984. nozzle_temp = round(temps.get("nozzle", 0))
  1985. bed_temp = round(temps.get("bed", 0))
  1986. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1987. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1988. # Auto-detect dual-nozzle printers from MQTT temperature data
  1989. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1990. _nozzle_count_updated.add(printer_id)
  1991. # Update nozzle_count in database
  1992. async with async_session() as db:
  1993. from backend.app.models.printer import Printer
  1994. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1995. printer = result.scalar_one_or_none()
  1996. if printer and printer.nozzle_count != 2:
  1997. printer.nozzle_count = 2
  1998. await db.commit()
  1999. logging.getLogger(__name__).info(
  2000. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2001. )
  2002. # Include target temps for heating phase detection
  2003. bed_target = round(temps.get("bed_target", 0))
  2004. nozzle_target = round(temps.get("nozzle_target", 0))
  2005. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2006. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2007. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2008. #
  2009. # dry_countdown_stalled rides along because it is the one drying signal the
  2010. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2011. # dry_time stopped moving, so on the frame that flips it every other member
  2012. # of this key is identical and the push would be deduplicated away. Mid-print
  2013. # a temperature would eventually break the tie, but a parked command on an
  2014. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2015. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2016. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2017. ams_dry_key = (
  2018. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2019. if state.raw_data
  2020. else ()
  2021. )
  2022. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2023. #
  2024. # The filament identity fields are here because Configure Slot writes
  2025. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2026. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2027. # matched, this function returned before broadcasting, and the card kept
  2028. # showing the old filament until the 30s fallback poll or a page reload —
  2029. # even though the configure route asks the printer for a fresh pushall and
  2030. # that push does carry the new values. Reset always worked, because it
  2031. # clears tray_type.
  2032. #
  2033. # These fields only change when someone configures a slot or swaps a spool,
  2034. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2035. ams_tray_key = (
  2036. tuple(
  2037. (
  2038. t.get("id"),
  2039. t.get("tray_type", ""),
  2040. t.get("state"),
  2041. t.get("tray_color", ""),
  2042. t.get("tray_info_idx", ""),
  2043. t.get("tray_sub_brands", ""),
  2044. t.get("cali_idx"),
  2045. )
  2046. for a in (state.raw_data.get("ams") or [])
  2047. for t in a.get("tray", [])
  2048. )
  2049. if state.raw_data
  2050. else ()
  2051. )
  2052. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2053. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2054. # in the AMS change-hash (tray fields only, and widening that would fire
  2055. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2056. # screen changed no key at all and the card's inlet badges sat stale until a
  2057. # reload. Like the filament-backup flag, these only move when someone
  2058. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2059. fts_key = (
  2060. state.fila_switch.installed if state.fila_switch else False,
  2061. tuple(sorted(state.ams_switch_inlet.items())),
  2062. # Which hotend holds which slot. Unlike the two above this does move
  2063. # mid-print, on every filament change — but only between discrete slots,
  2064. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2065. # it live: it decides which hotend the Load dialog may offer and whether
  2066. # Unload has anything to act on.
  2067. tuple(
  2068. sorted(
  2069. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2070. # Sort on the extruder id alone: the other members are nullable
  2071. # and comparing None with an int raises.
  2072. key=lambda entry: entry[0],
  2073. )
  2074. ),
  2075. )
  2076. status_key = (
  2077. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2078. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2079. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2080. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2081. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2082. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2083. )
  2084. # Fields that change only when the machine does (a nozzle swap, a firmware
  2085. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2086. # but on an idle printer nothing else moves the key when they change.
  2087. machine_key = (
  2088. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2089. state.firmware_version,
  2090. state.developer_mode,
  2091. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2092. # Cooling/heating, switched on the printer's screen too: on an idle
  2093. # printer nothing else moves the key (PSF-4).
  2094. state.airduct_mode,
  2095. )
  2096. status_key = f"{status_key}:{machine_key}"
  2097. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2098. if not is_active_print:
  2099. _unauthorized_print_kill_sent.discard(printer_id)
  2100. elif printer_id in _unauthorized_print_kill_sent:
  2101. # stop_print() was already sent for this print; avoid all further
  2102. # ownership and settings work until the printer leaves an active state.
  2103. pass
  2104. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2105. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2106. _unauthorized_print_kill_sent.discard(printer_id)
  2107. else:
  2108. kill_switch_enabled = False
  2109. authorization: bool | None = None
  2110. status_logger = logging.getLogger(__name__)
  2111. try:
  2112. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2113. if kill_switch_enabled:
  2114. async with async_session() as db:
  2115. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2116. except Exception as e:
  2117. # Fail safe: a database/reconciliation error must never turn into an
  2118. # irreversible stop of a print whose ownership is still unknown.
  2119. authorization = None
  2120. status_logger.warning(
  2121. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2122. )
  2123. if not kill_switch_enabled or authorization is True:
  2124. _unauthorized_print_kill_sent.discard(printer_id)
  2125. elif authorization is None:
  2126. _unauthorized_print_kill_sent.discard(printer_id)
  2127. status_logger.debug(
  2128. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2129. printer_id,
  2130. )
  2131. else:
  2132. try:
  2133. stopped = printer_manager.stop_print(printer_id)
  2134. if stopped:
  2135. _unauthorized_print_kill_sent.add(printer_id)
  2136. _kill_switch_stopped.add(printer_id)
  2137. printer_info = printer_manager.get_printer(printer_id)
  2138. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2139. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2140. notification_data = {
  2141. "status": "stopped",
  2142. "filename": state.gcode_file or state.current_print or "",
  2143. "subtask_name": state.subtask_name or "",
  2144. "progress": state.progress,
  2145. "reason": "unauthorized_print",
  2146. }
  2147. status_logger.warning(
  2148. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2149. printer_id,
  2150. state.state,
  2151. )
  2152. try:
  2153. await ws_manager.broadcast(
  2154. {
  2155. "type": "kill_switch_triggered",
  2156. "printer_id": printer_id,
  2157. "printer_name": printer_name,
  2158. "filename": filename,
  2159. "reason": "unauthorized_print",
  2160. }
  2161. )
  2162. except Exception as e:
  2163. status_logger.warning(
  2164. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2165. )
  2166. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2167. if previous_task is not None and not previous_task.done():
  2168. previous_task.cancel()
  2169. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2170. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2171. name=f"kill-switch-notification-{printer_id}",
  2172. )
  2173. else:
  2174. status_logger.warning(
  2175. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2176. printer_id,
  2177. state.state,
  2178. )
  2179. except Exception as e:
  2180. status_logger.warning(
  2181. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2182. )
  2183. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2184. try:
  2185. printer_info = printer_manager.get_printer(printer_id)
  2186. if printer_info:
  2187. await mqtt_relay.on_printer_status(
  2188. printer_id,
  2189. state,
  2190. printer_info.name,
  2191. printer_info.serial_number,
  2192. printer_manager.is_awaiting_plate_clear(printer_id),
  2193. )
  2194. except Exception:
  2195. pass # Don't fail status callback if MQTT fails
  2196. if _last_status_broadcast.get(printer_id) == status_key:
  2197. return # No change, skip WebSocket broadcast
  2198. _last_status_broadcast[printer_id] = status_key
  2199. # Check for progress milestone notifications (25%, 50%, 75%)
  2200. progress = state.progress or 0
  2201. is_printing = state.state in ("RUNNING", "PRINTING")
  2202. if is_printing and progress > 0:
  2203. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2204. if current_milestone is not None:
  2205. try:
  2206. from backend.app.models.printer import Printer
  2207. # Read the printer in a short session and release the connection
  2208. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2209. # pinned a pooled connection per milestone, per printer (issue #2572).
  2210. async with async_session() as db:
  2211. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2212. printer = result.scalar_one_or_none()
  2213. printer_name = printer.name if printer else f"Printer {printer_id}"
  2214. filename = state.subtask_name or state.gcode_file or "Unknown"
  2215. # remaining_time is in minutes, convert to seconds for notification
  2216. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2217. # Capture camera snapshot for notification image attachment (no DB held).
  2218. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2219. # Notification send needs a session (provider/template lookups).
  2220. async with async_session() as db:
  2221. await notification_service.on_print_progress(
  2222. printer_id,
  2223. printer_name,
  2224. filename,
  2225. current_milestone,
  2226. db,
  2227. remaining_time_seconds,
  2228. image_data=image_data,
  2229. )
  2230. except Exception as e:
  2231. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2232. elif progress < 5:
  2233. # Reset milestone tracking when print restarts or new print begins
  2234. _last_progress_milestone[printer_id] = 0
  2235. _first_layer_notified[printer_id] = False
  2236. # HMS error codes that should not trigger notifications even though they
  2237. # have known descriptions (e.g. user-initiated actions, not real errors).
  2238. _HMS_NOTIFICATION_SUPPRESS = {
  2239. "0500_400E", # Printing was cancelled (user action, not an error)
  2240. }
  2241. # Check for new HMS errors and send notifications
  2242. current_hms_errors = getattr(state, "hms_errors", []) or []
  2243. if current_hms_errors:
  2244. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2245. if new_errors:
  2246. try:
  2247. from backend.app.models.printer import Printer
  2248. # Read the printer in a short session and release the connection
  2249. # BEFORE the ~15s camera snapshot below (issue #2572).
  2250. async with async_session() as db:
  2251. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2252. printer = result.scalar_one_or_none()
  2253. printer_name = printer.name if printer else f"Printer {printer_id}"
  2254. # Format error details for notification
  2255. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2256. module_names = {
  2257. 0x03: "Print/Task",
  2258. 0x05: "Nozzle/Extruder",
  2259. 0x07: "AMS/Filament",
  2260. 0x0C: "Motion Controller",
  2261. 0x12: "Chamber",
  2262. }
  2263. # Capture camera snapshot once for all error notifications (no DB held).
  2264. error_image_data = await _capture_snapshot_for_notification(
  2265. printer_id, printer, logging.getLogger(__name__)
  2266. )
  2267. # Notification sends need a session (provider/template lookups).
  2268. async with async_session() as db:
  2269. sent_count = 0
  2270. for error in new_errors:
  2271. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2272. # Build short code like "0700_8010"
  2273. # Mask to 16 bits to handle printers that send larger values
  2274. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2275. error_code_masked = error_code_int & 0xFFFF
  2276. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2277. # Only notify for errors Bambu publishes text for — printers
  2278. # send undocumented codes that aren't real errors, and Bambu
  2279. # lists some with empty text. Resolved at parse time (#2926);
  2280. # short_code is still needed for the suppression set below.
  2281. description = error.description
  2282. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2283. continue
  2284. error_type = f"{module_name} Error"
  2285. error_detail = description
  2286. await notification_service.on_printer_error(
  2287. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2288. )
  2289. sent_count += 1
  2290. if sent_count:
  2291. logging.getLogger(__name__).info(
  2292. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2293. )
  2294. # Also publish to MQTT relay (no DB): every new fault that
  2295. # counts, with or without text, the same set the UI counts.
  2296. printer_info = printer_manager.get_printer(printer_id)
  2297. if printer_info:
  2298. errors_data = [
  2299. {
  2300. "code": e.code,
  2301. "attr": e.attr,
  2302. "module": e.module,
  2303. "severity": e.severity,
  2304. }
  2305. for e in new_errors
  2306. ]
  2307. await mqtt_relay.on_printer_error(
  2308. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2309. )
  2310. except Exception as e:
  2311. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2312. else:
  2313. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2314. # across a print state change) are forgotten. Some codes, e.g. chamber
  2315. # temperature regulation during PETG prints, toggle every few seconds.
  2316. _take_new_hms_faults(printer_id, [], state.state)
  2317. await ws_manager.send_printer_status(
  2318. printer_id,
  2319. printer_state_to_dict(
  2320. state,
  2321. printer_id,
  2322. printer_manager.get_model(printer_id),
  2323. printer_manager.get_drying_targets(printer_id),
  2324. ),
  2325. )
  2326. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2327. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2328. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2329. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2330. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2331. K-profiles are per-nozzle and the printer's calibration table is numbered
  2332. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2333. switch's other inlet therefore silently invalidates every configured slot in
  2334. it: the index stays put and now resolves against the other nozzle's table.
  2335. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2336. and 0.020 on the right kept the left profile after the move, and a manual
  2337. RFID re-read only re-asserted the same wrong one.
  2338. Configuring a slot is a deliberate preparation step, so this re-selects
  2339. rather than re-configures: only the calibration binding moves, and only for
  2340. slots whose spool already has a stored profile for the new nozzle. A slot
  2341. Bambuddy knows nothing about is left exactly as the operator left it.
  2342. """
  2343. logger = logging.getLogger(__name__)
  2344. target_extruder = extruder_for_inlet(inlet)
  2345. if target_extruder is None:
  2346. return
  2347. client = printer_manager.get_client(printer_id)
  2348. state = printer_manager.get_status(printer_id)
  2349. if not client or not state or not state.raw_data:
  2350. return
  2351. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2352. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2353. # the nozzle width, which changes both the K profile to select and the
  2354. # preset the slot should carry.
  2355. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2356. ams_raw = state.raw_data.get("ams")
  2357. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2358. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2359. if not unit:
  2360. return
  2361. try:
  2362. async with async_session() as db:
  2363. for tray in unit.get("tray", []):
  2364. tray_id = int(tray.get("id", -1))
  2365. if tray_id < 0 or not tray.get("tray_type"):
  2366. continue
  2367. current_idx = tray.get("cali_idx")
  2368. profile = await find_slot_kprofile_for_extruder(
  2369. db,
  2370. printer_id,
  2371. ams_id,
  2372. tray_id,
  2373. target_extruder,
  2374. nozzle_diameter,
  2375. printer_manager.get_model(printer_id),
  2376. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2377. )
  2378. if profile is None or profile.cali_idx is None:
  2379. continue
  2380. if current_idx == profile.cali_idx:
  2381. continue # Already on the right one.
  2382. logger.info(
  2383. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2384. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2385. printer_id,
  2386. ams_id,
  2387. tray_id,
  2388. inlet,
  2389. target_extruder,
  2390. profile.name,
  2391. current_idx,
  2392. profile.cali_idx,
  2393. profile.k_value,
  2394. )
  2395. client.extrusion_cali_sel(
  2396. ams_id=ams_id,
  2397. tray_id=tray_id,
  2398. cali_idx=profile.cali_idx,
  2399. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2400. nozzle_diameter=nozzle_diameter,
  2401. )
  2402. except Exception as e:
  2403. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2404. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2405. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2406. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2407. from the delayed re-check -- which is why it takes the AMS data and print
  2408. state as arguments instead of reading them from the push (#3186).
  2409. """
  2410. logger = logging.getLogger(__name__)
  2411. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2412. # Auto-unlink spool assignments with stale fingerprints. Under the
  2413. # per-printer assignment lock since #3186: the held-removal re-check runs
  2414. # this outside any MQTT push, so it can now overlap one.
  2415. try:
  2416. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2417. from sqlalchemy.orm import selectinload
  2418. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2419. from backend.app.models.spool import Spool as _Spool
  2420. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2421. from backend.app.services.ams_slot_presence import spool_present
  2422. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2423. # Built-in assignments only. Since #2812 they survive a switch to
  2424. # Spoolman mode rather than being deleted by it, and this pass ends
  2425. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2426. # time as the AMS contents changed under the other mode, undoing the
  2427. # preservation more slowly but just as completely.
  2428. assignments = []
  2429. if not await spoolman_owns_assignments(db):
  2430. result = await db.execute(
  2431. select(SA)
  2432. .where(SA.printer_id == printer_id)
  2433. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2434. )
  2435. assignments = result.scalars().all()
  2436. # ``printing_now`` (top of this function) keeps a runout from
  2437. # unlinking the spool that fed the print — the next idle-time pass
  2438. # unlinks it if the user really did take it out.
  2439. stale = []
  2440. # Removals this pass is holding rather than unlinking (#3186).
  2441. held: set[tuple] = set()
  2442. for assignment in assignments:
  2443. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2444. if assignment.ams_id == 255:
  2445. ps = printer_manager.get_status(printer_id)
  2446. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2447. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2448. current_tray = None
  2449. for vt in vt_tray_raw:
  2450. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2451. current_tray = vt
  2452. break
  2453. if not current_tray:
  2454. # vt_tray data may not have arrived yet — keep assignment
  2455. continue
  2456. else:
  2457. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2458. if not current_tray:
  2459. if printing_now:
  2460. logger.info(
  2461. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2462. assignment.spool_id,
  2463. assignment.ams_id,
  2464. assignment.tray_id,
  2465. )
  2466. continue
  2467. # A whole AMS unit can drop out of one push and come back in
  2468. # the next; only a slot that stays gone is a removal (#3186).
  2469. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2470. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2471. held.add(hold_key)
  2472. logger.info(
  2473. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2474. "unlinking if it is still gone in %ds",
  2475. assignment.spool_id,
  2476. assignment.ams_id,
  2477. assignment.tray_id,
  2478. int(slot_unlink_grace.GRACE_SECONDS),
  2479. )
  2480. continue
  2481. logger.info(
  2482. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2483. assignment.spool_id,
  2484. assignment.ams_id,
  2485. assignment.tray_id,
  2486. )
  2487. stale.append(assignment) # Slot empty
  2488. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2489. # A Bambu Lab spool is in this slot — check if it's the same spool
  2490. # that's currently assigned. If yes, keep the assignment (avoids
  2491. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2492. # the printer's filament preset on every startup).
  2493. tray_uuid = current_tray.get("tray_uuid", "")
  2494. tag_uid = current_tray.get("tag_uid", "")
  2495. spool = assignment.spool
  2496. spool_matches = False
  2497. if spool:
  2498. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2499. spool.tag_uid
  2500. and tag_uid
  2501. and tag_uid != "0000000000000000"
  2502. and spool.tag_uid.upper() == tag_uid.upper()
  2503. ):
  2504. spool_matches = True
  2505. if spool_matches:
  2506. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2507. cur_color = current_tray.get("tray_color", "")
  2508. cur_type = current_tray.get("tray_type", "")
  2509. fp_color = assignment.fingerprint_color or ""
  2510. fp_type = assignment.fingerprint_type or ""
  2511. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2512. assignment.fingerprint_color = cur_color
  2513. assignment.fingerprint_type = cur_type
  2514. logger.debug(
  2515. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2516. assignment.spool_id,
  2517. assignment.ams_id,
  2518. assignment.tray_id,
  2519. )
  2520. continue
  2521. # Different BL spool or unrecognized — unlink so auto-assign can match
  2522. logger.info(
  2523. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2524. assignment.spool_id,
  2525. assignment.ams_id,
  2526. assignment.tray_id,
  2527. tray_uuid,
  2528. )
  2529. stale.append(assignment)
  2530. else:
  2531. cur_color = current_tray.get("tray_color", "")
  2532. cur_type = current_tray.get("tray_type", "")
  2533. cur_state = current_tray.get("state")
  2534. fp_color = assignment.fingerprint_color or ""
  2535. fp_type = assignment.fingerprint_type or ""
  2536. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2537. # the slot was empty when the user pre-assigned via SpoolBuddy
  2538. # (the firmware drops ams_filament_setting on empty slots, so
  2539. # MQTT was deferred). The moment any filament gets inserted
  2540. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2541. # reconfigured spool — fire the deferred configuration.
  2542. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2543. # extruder" code) OR, on firmwares that don't use the state
  2544. # enum meaningfully, a non-empty tray_type when state is
  2545. # NOT one of the firmware's explicit empty signals (9, 10).
  2546. # state-only was wrong for firmwares that never set 11 — A1
  2547. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2548. # always report state=3 — so the replay never fired for them
  2549. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2550. # explicit "empty" signals authoritative over any stale
  2551. # tray_type that might survive the relay's auto-clearing.
  2552. #
  2553. # tray_exist_bits comes first because that guard cannot tell
  2554. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2555. # writes state=9 when the bit is 0 and leaves it there when the
  2556. # bit returns. A non-RFID spool inserted into a pre-assigned
  2557. # slot brings no tray_type with it, so the stale 9 made this
  2558. # expression false forever and the deferred config never fired
  2559. # — the deadlock #1322 removed from the assign path, still in
  2560. # place here (#3084, #3100).
  2561. loaded = spool_present(current_tray) is True or (
  2562. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2563. )
  2564. if not fp_type.strip() and loaded and assignment.spool:
  2565. # The fingerprint ends this replay. Not recorded when nothing
  2566. # could be sent (no MQTT client while the printer reconnects),
  2567. # so the next AMS change tries again. An attempt that raised is
  2568. # recorded as before: it may have sent part of the commands and
  2569. # would raise again on every change, remain% steps included.
  2570. configured: bool | None = False
  2571. try:
  2572. from backend.app.api.routes.inventory import (
  2573. apply_spool_to_slot_via_mqtt,
  2574. )
  2575. configured = await apply_spool_to_slot_via_mqtt(
  2576. db=db,
  2577. current_user=None,
  2578. spool=assignment.spool,
  2579. printer_id=printer_id,
  2580. ams_id=assignment.ams_id,
  2581. tray_id=assignment.tray_id,
  2582. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2583. current_tray_type=cur_type,
  2584. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2585. )
  2586. except Exception:
  2587. logger.exception(
  2588. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2589. assignment.spool_id,
  2590. printer_id,
  2591. assignment.ams_id,
  2592. assignment.tray_id,
  2593. )
  2594. configured = None
  2595. if configured is False:
  2596. logger.warning(
  2597. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2598. "retrying on the next AMS change",
  2599. assignment.spool_id,
  2600. printer_id,
  2601. assignment.ams_id,
  2602. assignment.tray_id,
  2603. )
  2604. else:
  2605. if configured:
  2606. logger.info(
  2607. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2608. assignment.spool_id,
  2609. printer_id,
  2610. assignment.ams_id,
  2611. assignment.tray_id,
  2612. )
  2613. assignment.fingerprint_color = cur_color
  2614. assignment.fingerprint_type = cur_type
  2615. continue
  2616. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2617. # Blank tray data mid-print is a runout, not a swap: the
  2618. # firmware clears colour and type when it unloads a spool
  2619. # it just emptied. Unlinking here would erase the record
  2620. # of which spool fed the print so far.
  2621. if printing_now and not cur_color.strip() and not cur_type.strip():
  2622. logger.info(
  2623. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2624. "(runout?)",
  2625. assignment.spool_id,
  2626. assignment.ams_id,
  2627. assignment.tray_id,
  2628. )
  2629. continue
  2630. # Same reasoning off the print, on firmware's own say-so:
  2631. # a blank tray report from a slot whose tray_exist_bits
  2632. # bit is set describes a spool the AMS cannot identify —
  2633. # a non-RFID one, or one whose slot was reset — not a
  2634. # spool that was taken out. Deleting the assignment there
  2635. # threw away the identity the user had supplied, which is
  2636. # the only place it existed (#3100). A slot the bit calls
  2637. # empty, or one that carries no bit at all, still unlinks.
  2638. #
  2639. # Unless the slot was reported empty first: a removal
  2640. # already held means a spool came out and another went
  2641. # in, so the blank report keeps the hold running below
  2642. # rather than cancelling it (#3186).
  2643. if (
  2644. spool_present(current_tray) is True
  2645. and not cur_color.strip()
  2646. and not cur_type.strip()
  2647. and not slot_unlink_grace.is_held(
  2648. printer_id,
  2649. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2650. )
  2651. ):
  2652. logger.info(
  2653. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2654. "tray reports no filament data yet",
  2655. assignment.spool_id,
  2656. assignment.ams_id,
  2657. assignment.tray_id,
  2658. )
  2659. continue
  2660. # A blank report the presence bit does not vouch for is
  2661. # still only one push. An idle X1C cleared a whole AMS
  2662. # unit's bits, colour and type for a moment and lost
  2663. # four saved assignments that way (#3186); unlink only
  2664. # if the slot is still blank after the grace period.
  2665. if not cur_color.strip() and not cur_type.strip():
  2666. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2667. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2668. held.add(hold_key)
  2669. logger.info(
  2670. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2671. "unlinking if it is still blank in %ds",
  2672. assignment.spool_id,
  2673. assignment.ams_id,
  2674. assignment.tray_id,
  2675. int(slot_unlink_grace.GRACE_SECONDS),
  2676. )
  2677. continue
  2678. # Fingerprint mismatch — but check if tray now matches the
  2679. # assigned spool (e.g. auto-configure changed the tray).
  2680. # Both sides are reduced to the type the slot can carry
  2681. # before comparing: the assign path writes that rather
  2682. # than the spool's raw material (#2902), so a spool whose
  2683. # material is a product line — "PLA+", "HTPLA" — reports
  2684. # back as "PLA" and would otherwise fail this check and
  2685. # be auto-unlinked from the slot it was just assigned to.
  2686. # Reducing the printer's side too keeps slots configured
  2687. # by an older Bambuddy, still reporting "PLA+", matching.
  2688. spool = assignment.spool
  2689. if spool:
  2690. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2691. # Two ways the assign path can have arrived at the
  2692. # slot's type, so both count as "we wrote this".
  2693. # The material column is one; the spool's preset is
  2694. # the other, and it outranks the material when the
  2695. # spool has one -- a spool whose material says PLA
  2696. # and whose preset is "Bambu PLA Aero" puts
  2697. # PLA-AERO in the slot (#2902). Read from the stored
  2698. # preset name rather than resolving the preset,
  2699. # because this runs on every AMS push and a cloud
  2700. # lookup here would be both slow and unavailable on
  2701. # the unauthenticated replay path.
  2702. spool_types = {printer_filament_type(spool.material).upper()}
  2703. if spool.slicer_filament_name:
  2704. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2705. # An imported local preset stores its type outright,
  2706. # which is what the assign path used -- and the name
  2707. # above may be unset. One keyed read, and only on a
  2708. # mismatch, which is rare.
  2709. #
  2710. # slicer_filament is free text up to fifty characters,
  2711. # so the digits have to be checked against the range
  2712. # of the integer primary key they are about to be
  2713. # compared with. Postgres raises on an out-of-range
  2714. # integer rather than simply not matching, and that
  2715. # would poison this session and abandon the rest of
  2716. # the cleanup pass.
  2717. lp_ref = (spool.slicer_filament or "").strip()
  2718. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2719. from backend.app.models.local_preset import LocalPreset as _LP
  2720. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2721. if lp_type:
  2722. spool_types.add(printer_filament_type(lp_type).upper())
  2723. if (
  2724. _colors_similar(cur_color, spool_color)
  2725. and printer_filament_type(cur_type).upper() in spool_types
  2726. ):
  2727. logger.info(
  2728. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2729. assignment.spool_id,
  2730. assignment.ams_id,
  2731. assignment.tray_id,
  2732. )
  2733. assignment.fingerprint_color = cur_color
  2734. assignment.fingerprint_type = cur_type
  2735. continue
  2736. logger.info(
  2737. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2738. assignment.spool_id,
  2739. assignment.ams_id,
  2740. assignment.tray_id,
  2741. cur_color,
  2742. cur_type,
  2743. fp_color,
  2744. fp_type,
  2745. spool.rgba if spool else "?",
  2746. spool.material if spool else "?",
  2747. )
  2748. stale.append(assignment) # Spool changed
  2749. slot_unlink_grace.settle(printer_id, "inventory", held)
  2750. # Snapshot slots before delete — ORM attribute access after the
  2751. # commit would refresh against a deleted row.
  2752. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2753. for a in stale:
  2754. await db.delete(a)
  2755. if stale:
  2756. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2757. # Commit any changes (stale deletions and/or fingerprint updates)
  2758. await db.commit()
  2759. # Tell open browsers the assignment is gone (#2575). Only the manual
  2760. # REST assign/unassign endpoints broadcast this event; without it the
  2761. # frontend's spool-assignments cache keeps rendering the unlinked
  2762. # spool on the slot until an unrelated refetch — which reads exactly
  2763. # like "the fix didn't work" (reporter verified: a browser refresh
  2764. # after the swap showed the correct state all along).
  2765. for ams_id, tray_id in unlinked_slots:
  2766. await ws_manager.broadcast(
  2767. {
  2768. "type": "spool_assignment_changed",
  2769. "printer_id": printer_id,
  2770. "ams_id": ams_id,
  2771. "tray_id": tray_id,
  2772. }
  2773. )
  2774. except Exception as e:
  2775. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2776. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2777. """Delete Spoolman slot rows whose held removal has run its grace period.
  2778. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2779. talks to Spoolman for every tray; this only needs the local rows, so it
  2780. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2781. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2782. not in a slot the presence bit calls occupied -- and nothing else.
  2783. """
  2784. logger = logging.getLogger(__name__)
  2785. try:
  2786. async with async_session() as db:
  2787. from backend.app.api.routes.settings import get_setting
  2788. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2789. from backend.app.services.ams_slot_presence import spool_present
  2790. enabled = await get_setting(db, "spoolman_enabled")
  2791. if not enabled or enabled.lower() != "true":
  2792. return
  2793. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2794. if sync_mode and sync_mode != "auto":
  2795. return
  2796. trays: dict[tuple[int, int], dict] = {}
  2797. for ams_unit in ams_data or []:
  2798. if not isinstance(ams_unit, dict):
  2799. continue
  2800. for tray in ams_unit.get("tray", []):
  2801. if isinstance(tray, dict):
  2802. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2803. rows = (
  2804. (
  2805. await db.execute(
  2806. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2807. )
  2808. )
  2809. .scalars()
  2810. .all()
  2811. )
  2812. held: set[tuple] = set()
  2813. expired: list[tuple[int, int]] = []
  2814. for row in rows:
  2815. tray = trays.get((row.ams_id, row.tray_id))
  2816. if tray is None or printing_now:
  2817. continue
  2818. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2819. continue
  2820. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2821. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2822. continue
  2823. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2824. expired.append((row.ams_id, row.tray_id))
  2825. else:
  2826. held.add(hold_key)
  2827. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2828. if not expired:
  2829. return
  2830. # A statement rather than ORM deletes, like the sync pass: the two
  2831. # can overlap, and a row the other already removed must not fail
  2832. # this commit.
  2833. for ams_id, tray_id in expired:
  2834. await db.execute(
  2835. delete(SpoolmanSlotAssignment).where(
  2836. SpoolmanSlotAssignment.printer_id == printer_id,
  2837. SpoolmanSlotAssignment.ams_id == ams_id,
  2838. SpoolmanSlotAssignment.tray_id == tray_id,
  2839. )
  2840. )
  2841. await db.commit()
  2842. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2843. for ams_id, tray_id in expired:
  2844. await ws_manager.broadcast(
  2845. {
  2846. "type": "spool_assignment_changed",
  2847. "printer_id": printer_id,
  2848. "ams_id": ams_id,
  2849. "tray_id": tray_id,
  2850. }
  2851. )
  2852. except Exception as e:
  2853. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2854. async def _recheck_held_unlinks(printer_id: int) -> None:
  2855. """Re-run just the slot cleanup against the printer's current AMS state.
  2856. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2857. passes otherwise run only when the AMS hash changes, and a slot that went
  2858. empty and stayed empty may never change it again.
  2859. """
  2860. status = printer_manager.get_status(printer_id)
  2861. # A disconnected printer's state is its last report, not a new one: acting
  2862. # on it would "confirm" a removal nobody has seen for the whole grace
  2863. # period. Leave the holds; the first push after reconnecting decides.
  2864. if status is None or not status.connected:
  2865. return
  2866. ams_raw = status.raw_data.get("ams")
  2867. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2868. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2869. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2870. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2871. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2872. async def on_ams_change(printer_id: int, ams_data: list):
  2873. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2874. logger = logging.getLogger(__name__)
  2875. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2876. # still being charged, skip weight sync later. on_print_complete may pop
  2877. # _active_sessions during our awaits (#880).
  2878. from backend.app.services.usage_tracker import printer_is_charging
  2879. _print_active = printer_is_charging(printer_id)
  2880. # A slot that reports empty while a print is running is a filament runout,
  2881. # not a spool swap: the spool is still physically in the AMS, just
  2882. # consumed. Dropping either inventory backend's slot link there loses the
  2883. # only record of which spool fed the print, so the completion path can't
  2884. # charge the runout segment to anything. Both cleanup passes below consult
  2885. # this; computed once, up front, so neither depends on the other having run.
  2886. _unlink_state = printer_manager.get_status(printer_id)
  2887. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2888. # The session alone is not enough: a restart that finds a stale persisted
  2889. # session registers none for the print that is running.
  2890. _print_active = _print_active or printing_now
  2891. # MQTT relay - publish AMS change
  2892. try:
  2893. printer_info = printer_manager.get_printer(printer_id)
  2894. if printer_info:
  2895. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2896. except Exception:
  2897. pass # Don't fail AMS callback if MQTT fails
  2898. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2899. # This ensures frontend gets immediate updates when AMS slots are configured
  2900. try:
  2901. state = printer_manager.get_status(printer_id)
  2902. if state:
  2903. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2904. await ws_manager.send_printer_status(
  2905. printer_id,
  2906. printer_state_to_dict(
  2907. state,
  2908. printer_id,
  2909. printer_manager.get_model(printer_id),
  2910. printer_manager.get_drying_targets(printer_id),
  2911. ),
  2912. )
  2913. except Exception as e:
  2914. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2915. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2916. # Spools whose tag this pass assigned to a slot; their other slots are
  2917. # released below, once this printer's lock is let go (#3427).
  2918. rfid_assigned: list[tuple[int, tuple[int, int, int]]] = []
  2919. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2920. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2921. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2922. # "no existing assignment" for the same (printer, ams, tray) and race to
  2923. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2924. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2925. # bug stayed latent there. See services/ams_assignment_lock for details.
  2926. try:
  2927. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2928. from sqlalchemy.orm import selectinload
  2929. from backend.app.api.routes.settings import get_setting
  2930. from backend.app.models.spool import Spool
  2931. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2932. from backend.app.services.spool_tag_matcher import (
  2933. auto_assign_spool,
  2934. create_spool_from_tray,
  2935. find_matching_untagged_spool,
  2936. get_spool_by_tag,
  2937. is_bambu_tag,
  2938. is_valid_tag,
  2939. link_tag_to_inventory_spool,
  2940. tag_belongs_to_archived_spool,
  2941. )
  2942. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2943. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2944. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2945. if not _spoolman_on or _spoolman_on.lower() != "true":
  2946. for ams_unit in ams_data:
  2947. if not isinstance(ams_unit, dict):
  2948. continue
  2949. ams_id = int(ams_unit.get("id", 0))
  2950. for tray in ams_unit.get("tray", []):
  2951. if not isinstance(tray, dict):
  2952. continue
  2953. tray_id = int(tray.get("id", 0))
  2954. tag_uid = tray.get("tag_uid", "")
  2955. tray_uuid = tray.get("tray_uuid", "")
  2956. tray_info_idx = tray.get("tray_info_idx", "")
  2957. if not tray.get("tray_type"):
  2958. # Slot reported empty — drop any cached unknown-tag
  2959. # broadcast so reinserting the same spool re-prompts.
  2960. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2961. continue # Empty slot
  2962. # Check if assignment already exists for this slot
  2963. existing = await db.execute(
  2964. select(SA)
  2965. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2966. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2967. )
  2968. existing_assignment = existing.scalar_one_or_none()
  2969. if existing_assignment:
  2970. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2971. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2972. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2973. # Skip during active prints: the usage tracker handles deduction
  2974. # precisely via 3MF data on print completion. Without this guard the
  2975. # AMS remain% SET and the usage tracker ADD both fire from the same
  2976. # MQTT message, doubling the deduction (#880).
  2977. if _print_active:
  2978. continue
  2979. remain_raw = tray.get("remain")
  2980. if (
  2981. remain_raw is not None
  2982. and existing_assignment.spool
  2983. and not existing_assignment.spool.weight_locked
  2984. ):
  2985. try:
  2986. remain_val = int(remain_raw)
  2987. except (TypeError, ValueError):
  2988. remain_val = -1
  2989. if 1 <= remain_val <= 100:
  2990. lw = existing_assignment.spool.label_weight or 1000
  2991. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2992. current_used = existing_assignment.spool.weight_used or 0
  2993. if new_used > current_used + 1:
  2994. # Rechecked in the statement: the spool was loaded
  2995. # before this, and a weight set by hand (or weighed)
  2996. # and locked since then must stay (WL-6).
  2997. result = cast(
  2998. CursorResult,
  2999. await db.execute(
  3000. update(Spool)
  3001. .where(
  3002. Spool.id == existing_assignment.spool_id,
  3003. Spool.weight_locked.is_not(True),
  3004. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3005. )
  3006. .values(weight_used=new_used)
  3007. ),
  3008. )
  3009. await db.commit()
  3010. if result.rowcount:
  3011. logger.info(
  3012. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3013. existing_assignment.spool_id,
  3014. current_used,
  3015. new_used,
  3016. remain_val,
  3017. )
  3018. await ws_manager.broadcast({"type": "inventory_changed"})
  3019. # A K-profile the slot lost (the default K after a reset or
  3020. # power cycle) is put back by kprofile_drift on the next idle
  3021. # push; a different real profile was picked on purpose and
  3022. # stays (#3219, item 44).
  3023. continue
  3024. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3025. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3026. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3027. # Only a spool already known by this tag is proven to be
  3028. # here; a material/colour match or a new spool is not
  3029. # grounds to take it out of other slots (#3427).
  3030. known_by_tag = spool is not None
  3031. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3032. # An archived spool still in the AMS: the slot
  3033. # stays free rather than adopting its tag.
  3034. continue
  3035. if not spool:
  3036. # Try matching an untagged inventory spool (same material/color)
  3037. spool = await find_matching_untagged_spool(db, tray)
  3038. if spool:
  3039. await link_tag_to_inventory_spool(db, spool, tray)
  3040. elif _auto_add_unknown:
  3041. spool = await create_spool_from_tray(db, tray)
  3042. else:
  3043. # Auto-add disabled: surface the slot so the
  3044. # user can add it manually via the UI.
  3045. await _broadcast_unknown_tag(
  3046. printer_id=printer_id,
  3047. ams_id=ams_id,
  3048. tray_id=tray_id,
  3049. tag_uid=tag_uid,
  3050. tray_uuid=tray_uuid,
  3051. tray_type=tray.get("tray_type"),
  3052. tray_color=tray.get("tray_color"),
  3053. tray_sub_brands=tray.get("tray_sub_brands"),
  3054. tray_count=len(ams_unit.get("tray", [])),
  3055. )
  3056. continue
  3057. # Slot matched (existing tag, untagged inventory
  3058. # match, or freshly auto-created spool) — drop any
  3059. # stale dedup so a future tag swap re-prompts.
  3060. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3061. await auto_assign_spool(
  3062. printer_id,
  3063. ams_id,
  3064. tray_id,
  3065. spool,
  3066. printer_manager,
  3067. db,
  3068. tray_info_idx=tray_info_idx,
  3069. )
  3070. await db.commit()
  3071. if known_by_tag:
  3072. rfid_assigned.append((spool.id, (printer_id, ams_id, tray_id)))
  3073. await ws_manager.broadcast(
  3074. {
  3075. "type": "spool_auto_assigned",
  3076. "printer_id": printer_id,
  3077. "ams_id": ams_id,
  3078. "tray_id": tray_id,
  3079. "spool_id": spool.id,
  3080. }
  3081. )
  3082. logger.info(
  3083. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3084. spool.id,
  3085. printer_id,
  3086. ams_id,
  3087. tray_id,
  3088. )
  3089. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3090. db, tag_uid, tray_uuid
  3091. ):
  3092. # Non-BL spool with some tag — let user choose (not
  3093. # an archived one's, whose slot stays free)
  3094. await _broadcast_unknown_tag(
  3095. printer_id=printer_id,
  3096. ams_id=ams_id,
  3097. tray_id=tray_id,
  3098. tag_uid=tag_uid,
  3099. tray_uuid=tray_uuid,
  3100. tray_type=tray.get("tray_type"),
  3101. tray_color=tray.get("tray_color"),
  3102. tray_sub_brands=tray.get("tray_sub_brands"),
  3103. tray_count=len(ams_unit.get("tray", [])),
  3104. )
  3105. # No-tag slots (generic non-RFID filament) are left alone:
  3106. # nothing to identify, prompting "+ Add" would just create
  3107. # ghost spools with empty tags on every confirm.
  3108. except Exception as e:
  3109. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3110. if rfid_assigned:
  3111. from backend.app.services.spool_relocation import INTERNAL, release_other_slots
  3112. for spool_id, slot in rfid_assigned:
  3113. try:
  3114. await release_other_slots(INTERNAL, spool_id, slot)
  3115. except Exception as e:
  3116. logger.warning("Releasing spool %s from its other slots failed: %s", spool_id, e, exc_info=True)
  3117. try:
  3118. async with async_session() as db:
  3119. from backend.app.api.routes.settings import get_setting
  3120. from backend.app.models.printer import Printer
  3121. # Check if Spoolman is enabled
  3122. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3123. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3124. return
  3125. # Check sync mode
  3126. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3127. if sync_mode and sync_mode != "auto":
  3128. return # Only sync on auto mode
  3129. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3130. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3131. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3132. # always owned by per-print tracking, never by AMS auto-sync. The
  3133. # setting is still read by the settings UI for backwards compat but
  3134. # has no effect on the sync path here.
  3135. # Get Spoolman URL
  3136. spoolman_url = await get_setting(db, "spoolman_url")
  3137. if not spoolman_url:
  3138. return
  3139. # Get or create Spoolman client
  3140. client = await get_spoolman_client()
  3141. if not client:
  3142. try:
  3143. client = await init_spoolman_client(spoolman_url)
  3144. except ValueError as exc:
  3145. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3146. return
  3147. # Check if Spoolman is reachable
  3148. if not await client.health_check():
  3149. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3150. return
  3151. # Get printer name for location
  3152. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3153. printer = result.scalar_one_or_none()
  3154. printer_name = printer.name if printer else f"Printer {printer_id}"
  3155. # OPTIMIZATION: Fetch all spools once before processing trays
  3156. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3157. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3158. try:
  3159. cached_spools = await client.get_spools()
  3160. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3161. except Exception as e:
  3162. logger.error(
  3163. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3164. printer_id,
  3165. e,
  3166. )
  3167. return
  3168. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3169. from sqlalchemy.orm import selectinload
  3170. from backend.app.models.spool_assignment import SpoolAssignment
  3171. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3172. from backend.app.services.ams_slot_presence import spool_present
  3173. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3174. # Built-in remaining weight, used by sync_ams_tray only when the
  3175. # firmware reports an unusable remain%/tray_weight for a slot.
  3176. #
  3177. # Left empty since #2812. This block runs in Spoolman mode only,
  3178. # and until then the built-in table was emptied on the switch, so
  3179. # there was never anything here to read and the fallback was inert.
  3180. # Preserving those rows makes it live again, and it is keyed by slot
  3181. # rather than by spool: after a mode switch the tray may well hold
  3182. # different filament, and ``create_spool`` writes ``remaining_weight``
  3183. # unconditionally, so a stale figure would be seeded into a brand new
  3184. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3185. # intent survives for whoever revisits the cross-mode fallback.
  3186. inventory_weights: dict[tuple[int, int], float] = {}
  3187. if not await spoolman_owns_assignments(db):
  3188. try:
  3189. assign_result = await db.execute(
  3190. select(SpoolAssignment)
  3191. .options(selectinload(SpoolAssignment.spool))
  3192. .where(SpoolAssignment.printer_id == printer_id)
  3193. )
  3194. for assignment in assign_result.scalars().all():
  3195. spool = assignment.spool
  3196. if spool and spool.label_weight > 0:
  3197. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3198. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3199. except Exception as e:
  3200. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3201. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3202. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3203. slot_map_read = False
  3204. try:
  3205. slot_result = await db.execute(
  3206. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3207. )
  3208. for slot in slot_result.scalars().all():
  3209. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3210. slot_map_read = True
  3211. except Exception as e:
  3212. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3213. # Sync each AMS tray and collect slot changes for DB persistence
  3214. synced = 0
  3215. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3216. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3217. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3218. for ams_unit in ams_data:
  3219. if not isinstance(ams_unit, dict):
  3220. continue
  3221. ams_id = int(ams_unit.get("id", 0))
  3222. trays = ams_unit.get("tray", [])
  3223. for tray_data in trays:
  3224. if not isinstance(tray_data, dict):
  3225. continue
  3226. tray_id_raw = int(tray_data.get("id", 0))
  3227. tray = client.parse_ams_tray(ams_id, tray_data)
  3228. if not tray:
  3229. # Empty tray slot — record for local assignment cleanup
  3230. # and drop any cached unknown-tag broadcast so a
  3231. # reinserted spool re-prompts.
  3232. #
  3233. # Not during a running print: a slot that empties there
  3234. # is a filament runout, and the spool is still in the
  3235. # AMS. `spoolman_slot_assignments` is how a tag-less
  3236. # spool assigned through the Bambuddy UI is resolved at
  3237. # completion (#1459), so deleting the row mid-print
  3238. # loses the runout segment's usage — the same failure
  3239. # the internal inventory's auto-unlink had.
  3240. #
  3241. # Nor when firmware's presence bit says the slot is
  3242. # occupied. parse_ams_tray calls a tray with no type or
  3243. # no colour empty, and a spool the AMS cannot read has
  3244. # neither until something configures it — so a tag-less
  3245. # spool assigned through the UI had its row deleted by
  3246. # the first idle push after it was inserted. Same
  3247. # deletion as the internal inventory's in #3100, same
  3248. # answer, so the two modes stay in step.
  3249. #
  3250. # And only once the slot has stayed empty for the grace
  3251. # period -- the internal inventory's #3186 answer, for
  3252. # the same one-push blank.
  3253. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3254. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3255. if not printing_now and (
  3256. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3257. ):
  3258. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3259. empty_slots.append((ams_id, tray_id_raw))
  3260. else:
  3261. spoolman_held.add(hold_key)
  3262. logger.info(
  3263. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3264. "unlinking if it is still empty in %ds",
  3265. ams_id,
  3266. tray_id_raw,
  3267. linked_spool,
  3268. int(slot_unlink_grace.GRACE_SECONDS),
  3269. )
  3270. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3271. continue
  3272. spool_tag = (
  3273. tray.tray_uuid
  3274. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3275. else tray.tag_uid
  3276. )
  3277. # Provide the hint only when no RFID is available
  3278. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3279. try:
  3280. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3281. result = await client.sync_ams_tray(
  3282. tray,
  3283. printer_name,
  3284. db,
  3285. # Per-print tracking is the only weight writer (#1119).
  3286. # AMS auto-sync still maintains spool metadata / slot
  3287. # assignments but no longer touches remaining_weight.
  3288. disable_weight_sync=True,
  3289. cached_spools=cached_spools,
  3290. inventory_remaining=inv_remaining,
  3291. spoolman_spool_id_hint=hint,
  3292. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3293. )
  3294. if result is None and spool_tag and not auto_add_unknown_rfid:
  3295. # Spoolman skipped auto-create per user setting — surface
  3296. # the slot so the UI can offer "+ Add to inventory".
  3297. await _broadcast_unknown_tag(
  3298. printer_id=printer_id,
  3299. ams_id=ams_id,
  3300. tray_id=tray.tray_id,
  3301. tag_uid=tray.tag_uid or "",
  3302. tray_uuid=tray.tray_uuid or "",
  3303. tray_type=tray.tray_type,
  3304. tray_color=tray.tray_color,
  3305. tray_sub_brands=tray.tray_sub_brands,
  3306. tray_count=len(trays),
  3307. )
  3308. elif result:
  3309. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3310. if result:
  3311. synced += 1
  3312. if result.get("id"):
  3313. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3314. # If a new spool was created, add it to the cache
  3315. # so subsequent trays can find it if they reference the same tag
  3316. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3317. if not spool_exists:
  3318. cached_spools.append(result)
  3319. logger.debug(
  3320. "[Printer %s] Added newly created spool %s to cache",
  3321. printer_id,
  3322. result["id"],
  3323. )
  3324. # Reconcile slot_preset_mappings (the same row internal
  3325. # mode keeps in sync via inventory + spool_tag_matcher).
  3326. # Without this the slot card surfaces the previous spool's
  3327. # preset name — same bug shape, different inventory mode.
  3328. from backend.app.services.slot_preset_writer import (
  3329. upsert_slot_preset_for_spoolman_spool,
  3330. )
  3331. await upsert_slot_preset_for_spoolman_spool(
  3332. db=db,
  3333. spoolman_spool=result,
  3334. tray_info_idx=tray.tray_info_idx or "",
  3335. tray_sub_brands=tray.tray_sub_brands or "",
  3336. tray_type=tray.tray_type or "",
  3337. printer_id=printer_id,
  3338. ams_id=ams_id,
  3339. tray_id=tray.tray_id,
  3340. )
  3341. except Exception as e:
  3342. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3343. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3344. if synced > 0:
  3345. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3346. # Persist slot assignment changes to the local table: only slots
  3347. # whose spool this pass changed, and only while they still hold what
  3348. # it read before awaiting Spoolman, so a spool assigned by hand in
  3349. # between stays (SSA-3). The changed slots are announced: the slot
  3350. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3351. # tray, so with no event it kept the previous spool's preset name.
  3352. if slot_changes or empty_slots:
  3353. from backend.app.services.spoolman_slot_sync import write_slot_results
  3354. try:
  3355. await write_slot_results(
  3356. db,
  3357. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3358. if slot_map_read
  3359. else None,
  3360. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3361. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3362. )
  3363. except Exception as e:
  3364. await db.rollback()
  3365. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3366. except Exception as e:
  3367. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3368. # Largest finish photo attached to a notification; a bigger one is still linked.
  3369. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3370. async def _finish_photo_for_notification(
  3371. db, archive, archive_id: int, filename: str
  3372. ) -> tuple[str | None, bytes | None]:
  3373. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3374. With authentication off the link is the archive's own photo route, as it
  3375. always was: it opens without a login and doesn't expire. With
  3376. authentication on that route needs a media token, which nothing tapping a
  3377. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3378. link only ever answered 401. The photo is then saved as a notification
  3379. photo as well (utils/notification_photos.py) and the link points there: an
  3380. unguessable name that opens this one photo and nothing else, for 3 days.
  3381. The link is relative when no External URL is set. Bytes over
  3382. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3383. ``(None, None)`` when the photo can't be found.
  3384. """
  3385. from backend.app.api.routes.settings import get_setting
  3386. from backend.app.core.auth import is_auth_enabled
  3387. from backend.app.utils.archive_paths import find_archive_photo
  3388. from backend.app.utils.notification_photos import save_notification_photo
  3389. log = logging.getLogger(__name__)
  3390. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3391. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3392. photo_bytes: bytes | None = None
  3393. try:
  3394. photo_path = find_archive_photo(archive, filename)
  3395. if photo_path is not None:
  3396. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3397. except Exception as e:
  3398. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3399. try:
  3400. auth_on = await is_auth_enabled(db)
  3401. except Exception:
  3402. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3403. if auth_on:
  3404. url = None
  3405. if photo_bytes:
  3406. try:
  3407. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3408. url = f"{base}/api/v1/notifications/photos/{name}"
  3409. except Exception as e:
  3410. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3411. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3412. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3413. return url, None
  3414. if photo_bytes:
  3415. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3416. return url, photo_bytes
  3417. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3418. """Capture a camera snapshot for notification image attachment.
  3419. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3420. Uses: external camera > buffered frame > fresh capture.
  3421. Turns the chamber light on for the picture when the printer asks for it
  3422. (#1655). ``light=False`` is for callers that capture all through a print,
  3423. where the light would flash with every frame.
  3424. """
  3425. if not printer:
  3426. return None
  3427. async with camera_light(printer if light else None):
  3428. return await _capture_snapshot_frame(printer_id, printer, logger)
  3429. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3430. """The capture behind ``_capture_snapshot_for_notification``."""
  3431. try:
  3432. from backend.app.api.routes.settings import get_setting
  3433. async with async_session() as db:
  3434. capture_enabled = await get_setting(db, "capture_finish_photo")
  3435. if capture_enabled is not None and capture_enabled.lower() != "true":
  3436. return None
  3437. # Try external camera first
  3438. if printer.external_camera_enabled and printer.external_camera_url:
  3439. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3440. from backend.app.api.routes.camera import live_frame_for_capture
  3441. from backend.app.services.external_camera import capture_frame
  3442. # An external camera allows one reader, so capturing while a viewer
  3443. # is attached fails (#2707). A None here falls through to the paths
  3444. # below exactly as a failed capture did.
  3445. defer, buffered = live_frame_for_capture(printer_id)
  3446. if defer:
  3447. frame_data = buffered
  3448. else:
  3449. frame_data = await capture_frame(
  3450. printer.external_camera_url,
  3451. printer.external_camera_type or "mjpeg",
  3452. snapshot_url=printer.external_camera_snapshot_url,
  3453. )
  3454. if frame_data and len(frame_data) <= 2_500_000:
  3455. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3456. return _apply_camera_rotation(frame_data, printer, logger)
  3457. # Try buffered frame from active stream
  3458. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3459. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3460. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3461. buffered_frame = get_buffered_frame(printer_id)
  3462. if (active_for_printer or active_chamber) and buffered_frame:
  3463. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3464. if len(buffered_frame) <= 2_500_000:
  3465. return _apply_camera_rotation(buffered_frame, printer, logger)
  3466. # Fresh capture from printer camera
  3467. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3468. from backend.app.services.camera import capture_camera_frame_bytes
  3469. frame_data = await capture_camera_frame_bytes(
  3470. printer.ip_address, printer.access_code, printer.model, timeout=15
  3471. )
  3472. if frame_data and len(frame_data) <= 2_500_000:
  3473. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3474. return _apply_camera_rotation(frame_data, printer, logger)
  3475. except Exception as e:
  3476. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3477. return None
  3478. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3479. """#1867: bank a recent in-print camera frame for the finish photo.
  3480. Called on every layer change and (#2547) on every print-progress advance.
  3481. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3482. path has a pre-End-G-code image for prints that end with a plate swap.
  3483. Both drivers are print telemetry that stops the instant printing ends: no
  3484. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3485. plate swap) executes. So the last banked frame is always the finished print,
  3486. never the swapped plate — that property is what the #1867 path relies on and
  3487. it must survive any change to the throttle below.
  3488. Layer changes alone were not enough: they stop when the *final* layer
  3489. begins, which on a three-minute last layer left the bank stale by the whole
  3490. length of that layer (#2547). Progress keeps ticking through it.
  3491. Best-effort: any failure just leaves the previous banked frame.
  3492. """
  3493. logger = logging.getLogger(__name__)
  3494. client = printer_manager.get_client(printer_id)
  3495. state = client.state if client else None
  3496. if not state or state.state != "RUNNING":
  3497. return
  3498. # Only during actual extrusion — firmware ticks layer_num during the
  3499. # pre-print calibration sequence, whose sub-stages are non-zero.
  3500. if state.mc_print_sub_stage not in (None, 0):
  3501. return
  3502. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3503. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3504. # now that progress advances also drive banking, that exemption would fire a
  3505. # camera grab on every percent tick of the last layer. Bambu printers accept
  3506. # one RTSP client at a time, so each grab contends with the live view.
  3507. now = time.monotonic()
  3508. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3509. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3510. return
  3511. total = state.total_layers or 0
  3512. try:
  3513. async with async_session() as db:
  3514. from backend.app.models.printer import Printer
  3515. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3516. printer = result.scalar_one_or_none()
  3517. if not printer:
  3518. return
  3519. # Reuses the notification snapshot path, which honours the
  3520. # `capture_finish_photo` setting (returns None when disabled) so we
  3521. # don't bank frames the user never asked for. Without the chamber light
  3522. # (#1655): this runs every 25 seconds for the whole print.
  3523. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3524. if frame:
  3525. _inprint_frame_bank[printer_id] = frame
  3526. _inprint_frame_bank_ts[printer_id] = now
  3527. logger.debug(
  3528. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3529. printer_id,
  3530. layer_num,
  3531. total,
  3532. len(frame),
  3533. )
  3534. except Exception as e:
  3535. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3536. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3537. """Apply camera rotation to snapshot image if configured."""
  3538. from backend.app.services.camera import apply_camera_rotation
  3539. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3540. async def _send_print_start_notification(
  3541. printer_id: int,
  3542. data: dict,
  3543. archive_data: dict | None = None,
  3544. logger=None,
  3545. ):
  3546. """Helper to send print start notification with optional archive data."""
  3547. if logger is None:
  3548. logger = logging.getLogger(__name__)
  3549. try:
  3550. async with async_session() as db:
  3551. from backend.app.models.printer import Printer
  3552. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3553. printer = result.scalar_one_or_none()
  3554. printer_name = printer.name if printer else f"Printer {printer_id}"
  3555. # Capture camera snapshot for notification image attachment
  3556. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3557. if image_data:
  3558. if archive_data is None:
  3559. archive_data = {}
  3560. archive_data["image_data"] = image_data
  3561. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3562. # Send user-specific email notification for print start
  3563. if archive_data and archive_data.get("created_by_id"):
  3564. await notification_service.send_user_print_email(
  3565. event_type="user_print_start",
  3566. created_by_id=archive_data["created_by_id"],
  3567. printer_name=printer_name,
  3568. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3569. db=db,
  3570. )
  3571. except Exception as e:
  3572. logger.warning("Notification on_print_start failed: %s", e)
  3573. async def _dispatch_user_print_email(
  3574. status: str,
  3575. created_by_id: int | None,
  3576. printer_name: str,
  3577. filename: str,
  3578. db,
  3579. image_data: bytes | None = None,
  3580. finish_photo_url: str | None = None,
  3581. ) -> None:
  3582. """Send a user-specific print-completion email based on print status.
  3583. Maps the normalised print status to the correct event type and delegates
  3584. to :meth:`NotificationService.send_user_print_email`. A single helper
  3585. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3586. "stopped"`` dispatch block at every call site.
  3587. Does nothing if *created_by_id* is ``None``.
  3588. """
  3589. if created_by_id is None:
  3590. return
  3591. if status == "completed":
  3592. event_type = "user_print_complete"
  3593. elif status == "failed":
  3594. event_type = "user_print_failed"
  3595. elif status in ("stopped", "aborted", "cancelled"):
  3596. event_type = "user_print_stopped"
  3597. else:
  3598. return
  3599. await notification_service.send_user_print_email(
  3600. event_type=event_type,
  3601. created_by_id=created_by_id,
  3602. printer_name=printer_name,
  3603. filename=filename,
  3604. db=db,
  3605. image_data=image_data,
  3606. finish_photo_url=finish_photo_url,
  3607. )
  3608. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3609. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3610. try:
  3611. from backend.app.services.archive import extract_printable_objects_from_archive
  3612. client = printer_manager.get_client(printer_id)
  3613. if not client:
  3614. return
  3615. # Extract with positions for UI overlay, scoped to the plate that
  3616. # is printing — resolve_plate_id is the same resolver /cover uses,
  3617. # so the object list can't disagree with the thumbnail it is drawn
  3618. # over (#2522).
  3619. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3620. app_settings.base_dir / archive.file_path,
  3621. plate_number=resolve_plate_id(client.state),
  3622. )
  3623. if printable_objects:
  3624. client.state.printable_objects = printable_objects
  3625. client.state.printable_objects_bbox_all = bbox_all
  3626. client.state.skipped_objects = []
  3627. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3628. except Exception as e:
  3629. logger.debug("Failed to extract printable objects from archive: %s", e)
  3630. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3631. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3632. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3633. handler must not wait for it. Kept only while the printer is still on
  3634. the print they were read for: a new print replaces the list.
  3635. ``warned_layers``: pauses this print was already warned about, kept on its
  3636. archive, so a restart does not send the heads-up again.
  3637. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3638. is on. Its pauses up to there are behind it, though the printer's layer
  3639. reads 0 until it reports the next one.
  3640. """
  3641. client = printer_manager.get_client(printer_id)
  3642. if not client:
  3643. return
  3644. state = client.state
  3645. read_for = state.pause_points
  3646. try:
  3647. plate_id = resolve_plate_id(state)
  3648. except Exception:
  3649. # Never at the cost of the print-start handler this runs inside.
  3650. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3651. return
  3652. async def _load() -> None:
  3653. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3654. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3655. if state.pause_points is not read_for:
  3656. return
  3657. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3658. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3659. if points:
  3660. logging.getLogger(__name__).info(
  3661. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3662. len(points),
  3663. printer_id,
  3664. [p.layer for p in points],
  3665. )
  3666. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3667. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3668. """Pauses for a print start taken as the resumption of a running print.
  3669. A restart while the print was paused makes its resume look like a new
  3670. print (#2984): the pauses warned about and passed are kept from before.
  3671. """
  3672. client = printer_manager.get_client(printer_id)
  3673. state = client.state if client else None
  3674. _load_pauses_from_3mf(
  3675. app_settings.base_dir / archive.file_path,
  3676. printer_id,
  3677. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3678. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3679. )
  3680. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3681. """Put the skip-objects list back after a restart mid-print.
  3682. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3683. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3684. which the #1304 guard suppresses on the first RUNNING push after startup.
  3685. Everything else this hook restores (the archive, the usage-tracking session,
  3686. the timelapse baseline) was already handled; the object list was not, so a
  3687. restart mid-print took skip-objects away for the rest of that print.
  3688. Nothing recovered it either: the printer card gates its Skip button on the
  3689. object count, and the one endpoint that can rebuild the list is reachable
  3690. only from the modal that button opens.
  3691. The archive is the running print's as ``running_print_archive`` finds it:
  3692. by subtask_id, or for a print that reports none by the archive bound to it
  3693. (#3327), never by name: a leftover ``status="printing"`` row from a
  3694. completion we never saw must not hand this print someone else's objects.
  3695. After a restart that binding exists only for Bambuddy's own prints, so a
  3696. print that reports no subtask_id loads nothing rather than a guess; the
  3697. reload path on ``GET /print/objects`` covers that case on demand.
  3698. """
  3699. client = printer_manager.get_client(printer_id)
  3700. if client is None or (client.state.printable_objects and client.state.pause_points):
  3701. return
  3702. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3703. if archive is not None and archive.file_path:
  3704. if not client.state.printable_objects:
  3705. _load_objects_from_archive(archive, printer_id, logger)
  3706. # The slicer's pauses are in-memory only as well (#2984).
  3707. if not client.state.pause_points:
  3708. _load_pauses_from_3mf(
  3709. app_settings.base_dir / archive.file_path,
  3710. printer_id,
  3711. warned_layers=pause_eta.warned_layers_of(archive, state),
  3712. )
  3713. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3714. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3715. # past it; the second covers a handshake that failed again on the way back and
  3716. # armed a fresh one. Module-level so tests can shrink them.
  3717. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3718. # Retry ladder for the other temporary give-up: the file service answered and
  3719. # the transfer still did not finish, which at print start is usually the printer
  3720. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3721. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3722. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3723. # two cover a printer that stays busy well into the print.
  3724. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3725. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3726. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3727. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3728. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3729. # by view, so two views race), the cool-off retry task, and print completion.
  3730. # Without this they each read file_path == "" and each run a full copy, so the row
  3731. # ends up pointing at one timestamped directory while the others sit orphaned.
  3732. #
  3733. # Keyed by printer rather than archive because a printer runs one print at a time,
  3734. # which makes the two equally strong here — and it bounds the dict by printer
  3735. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3736. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3737. # resuming, so "no waiters" is not a question this API can answer.
  3738. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3739. # How many of a printer's newest archives a touchscreen reprint is compared
  3740. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3741. # print start from reading a long history's extra_data.
  3742. _REPEAT_LOOKBACK = 200
  3743. async def _archived_3mf_for_repeat(
  3744. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3745. ):
  3746. """The newest archive of the job this printer is running again, with its 3MF.
  3747. A "Print again" on the printer's screen never names the file on the card:
  3748. it reports its own history copy under a generic name
  3749. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3750. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3751. not the card file's name, so every lookup built from it misses (#3307).
  3752. An earlier run that was archived recorded that same title and plate in its
  3753. ``_print_data``, and holds the 3MF.
  3754. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3755. known on both sides must agree: the same title and plate re-sliced is
  3756. another job. None when nothing matches.
  3757. """
  3758. from backend.app.models.archive import PrintArchive
  3759. if not subtask_name or not gcode_file:
  3760. return None
  3761. rows = (
  3762. (
  3763. await db.execute(
  3764. select(PrintArchive)
  3765. .where(
  3766. PrintArchive.printer_id == printer_id,
  3767. PrintArchive.deleted_at.is_(None),
  3768. PrintArchive.file_path.isnot(None),
  3769. PrintArchive.file_path != "",
  3770. )
  3771. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3772. .limit(_REPEAT_LOOKBACK)
  3773. )
  3774. )
  3775. .scalars()
  3776. .all()
  3777. )
  3778. for archive in rows:
  3779. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3780. run = extra.get("_print_data")
  3781. if not isinstance(run, dict):
  3782. continue
  3783. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3784. continue
  3785. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3786. continue
  3787. if not (app_settings.base_dir / archive.file_path).is_file():
  3788. continue
  3789. return archive
  3790. return None
  3791. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3792. """Fill in a no-3MF archive from a 3MF that turned up later.
  3793. Returns True when the row was upgraded. Safe to call speculatively: it
  3794. verifies the archive still exists, is still a fallback, and that the file
  3795. is a readable 3MF before touching anything.
  3796. Serialised per printer — see ``_fallback_recovery_locks``.
  3797. """
  3798. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3799. async with lock:
  3800. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3801. async def _recover_fallback_archive_locked(
  3802. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3803. ) -> bool:
  3804. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3805. ``price`` is False when the print's end is being handled: the archive
  3806. still reads "printing" then, and its end prices it.
  3807. """
  3808. import zipfile
  3809. from backend.app.models.archive import PrintArchive
  3810. from backend.app.services.archive import ArchiveService
  3811. logger = logging.getLogger(__name__)
  3812. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3813. return False
  3814. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3815. # A truncated or half-written download is worse than no download: it
  3816. # would replace an honest empty archive with wrong metadata.
  3817. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3818. return False
  3819. async with async_session() as db:
  3820. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3821. if archive is None or archive.deleted_at is not None:
  3822. return False
  3823. if archive.file_path:
  3824. # Already recovered, or never was a fallback. Either way there is a
  3825. # real 3MF attached and overwriting it is not this function's job.
  3826. return False
  3827. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3828. service = ArchiveService(db)
  3829. recovered = await service.archive_print(
  3830. printer_id=printer_id,
  3831. source_file=source_3mf,
  3832. print_data={**print_data, "status": archive.status or "printing"},
  3833. subtask_id=archive.subtask_id,
  3834. update_archive_id=archive.id,
  3835. )
  3836. if recovered is None:
  3837. return False
  3838. logger.info(
  3839. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3840. archive_id,
  3841. source_3mf,
  3842. recovered.file_size,
  3843. )
  3844. # Spoolman's tracking stored no 3MF usage at print start and would
  3845. # charge the AMS remain% change; the built-in tracker reads the archive
  3846. # at completion and needs nothing. Also at the print's end (``price``
  3847. # False): that recovery runs inside the close-out, before the charge.
  3848. try:
  3849. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3850. from backend.app.services.usage_tracker import is_completing
  3851. await attach_recovered_3mf(
  3852. printer_id,
  3853. recovered.id,
  3854. recovered.file_path,
  3855. db,
  3856. printer_manager,
  3857. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3858. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3859. )
  3860. except Exception:
  3861. logger.warning(
  3862. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3863. )
  3864. if price and recovered.status == "printing" and recovered.file_path:
  3865. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3866. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3867. if price and recovered.status == "printing":
  3868. # Print start priced it from the default rate, having no 3MF to
  3869. # estimate from; now it has one. An ended print is left alone: its
  3870. # end prices it. A print Bambuddy didn't dispatch has no start
  3871. # plate; the one the archive just read from the 3MF stands in.
  3872. _schedule_archive_cost_estimate(
  3873. printer_id,
  3874. recovered.id,
  3875. printer_manager,
  3876. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3877. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3878. session_factory=async_session,
  3879. )
  3880. # `archive_updated`, not `archive_created` — the row was already on the
  3881. # Archives page as an empty card and is now filled in, not new.
  3882. await ws_manager.send_archive_updated(
  3883. {
  3884. "id": recovered.id,
  3885. "printer_id": recovered.printer_id,
  3886. "filename": recovered.filename,
  3887. "print_name": recovered.print_name,
  3888. "status": recovered.status,
  3889. }
  3890. )
  3891. return True
  3892. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3893. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3894. Called from the paths that pull a 3MF for a print that is already under way
  3895. — chiefly the cover endpoint, which downloads the very file the archive flow
  3896. could not get and, before #2957, used it for a thumbnail and nothing else.
  3897. The bytes are already local, so this costs a parse and a row update.
  3898. No-op when the running print has a real archive, which is the common case.
  3899. """
  3900. from backend.app.models.archive import PrintArchive
  3901. logger = logging.getLogger(__name__)
  3902. # `_active_prints` is keyed on the raw names seen at print start — the
  3903. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3904. # Callers here arrive with whichever variant their own path produced, so
  3905. # match on the same normalization the download cache uses rather than on an
  3906. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3907. # endpoint find an archive registered under "Desktop_Goose".
  3908. wanted = normalize_3mf_name(name)
  3909. archive_id = None
  3910. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3911. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3912. archive_id = value
  3913. break
  3914. if archive_id is None:
  3915. return False
  3916. async with async_session() as db:
  3917. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3918. # Cheap pre-check so the common case (a normal archive) does no work.
  3919. if archive is None or archive.file_path or archive.deleted_at is not None:
  3920. return False
  3921. try:
  3922. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3923. except Exception as e:
  3924. # Recovery is opportunistic. A failure here must never take down the
  3925. # caller, which is usually just trying to render a thumbnail.
  3926. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3927. return False
  3928. def _schedule_fallback_3mf_retry(
  3929. printer_id: int,
  3930. archive_id: int,
  3931. filenames: list[str],
  3932. delays: tuple[float, ...] | None = None,
  3933. reason: str = REASON_FTPS_COOLOFF,
  3934. ) -> None:
  3935. """Re-attempt the 3MF download after a temporary give-up.
  3936. ``reason`` says which give-up this is, and picks the default ladder: an
  3937. FTPS cool-off has to be waited out, while a transfer that timed out under
  3938. contention is worth asking about again straight away (#3063). It is only
  3939. read for the ladder and the log line -- the retry itself is identical, since
  3940. in both cases the file is on the printer and the last attempt at it failed
  3941. for a reason that does not last.
  3942. """
  3943. logger = logging.getLogger(__name__)
  3944. if delays is None:
  3945. delays = (
  3946. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3947. if reason == REASON_FTP_TRANSFER_FAILED
  3948. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3949. )
  3950. async def _retry() -> None:
  3951. from backend.app.models.archive import PrintArchive
  3952. from backend.app.models.printer import Printer
  3953. for delay in delays:
  3954. await asyncio.sleep(delay)
  3955. async with async_session() as db:
  3956. archive = (
  3957. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3958. ).scalar_one_or_none()
  3959. if archive is None or archive.deleted_at is not None or archive.file_path:
  3960. return
  3961. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3962. if printer is None:
  3963. return
  3964. # Read the fields while the session is open rather than touching
  3965. # a detached instance minutes later, mid-download.
  3966. printer_ip = printer.ip_address
  3967. printer_code = printer.access_code
  3968. printer_model = printer.model
  3969. # Someone else may have fetched it in the meantime — the cover
  3970. # endpoint routinely does, and its copy is the same bytes.
  3971. for name in filenames:
  3972. cached = get_cached_3mf(printer_id, name)
  3973. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3974. return
  3975. if ftps_handshake_blocked(printer_ip):
  3976. logger.info(
  3977. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3978. printer_id,
  3979. archive_id,
  3980. )
  3981. continue
  3982. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3983. for candidate in filenames:
  3984. # Bare name only. These come from the print-start flow, which
  3985. # already strips the path, but the local temp write must not
  3986. # depend on that holding for every future caller — a name that
  3987. # is absolute or contains ".." would otherwise escape the data
  3988. # volume via the `/` operator.
  3989. name = Path(candidate).name
  3990. if not name or name in (".", ".."):
  3991. continue
  3992. if not name.endswith(".3mf"):
  3993. name = f"{name}.3mf"
  3994. temp_path = app_settings.archive_dir / "temp" / name
  3995. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3996. try:
  3997. hit = await download_file_try_paths_async(
  3998. printer_ip,
  3999. printer_code,
  4000. ftp_probe_paths(name),
  4001. temp_path,
  4002. socket_timeout=ftp_timeout,
  4003. printer_model=printer_model,
  4004. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  4005. )
  4006. except Exception as e:
  4007. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  4008. continue
  4009. if not hit:
  4010. continue
  4011. cache_3mf_download(printer_id, name, temp_path)
  4012. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  4013. return
  4014. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  4015. async def _guarded() -> None:
  4016. try:
  4017. await _retry()
  4018. except asyncio.CancelledError:
  4019. raise
  4020. except Exception as e:
  4021. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4022. finally:
  4023. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4024. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4025. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4026. if existing and not existing.done():
  4027. existing.cancel()
  4028. task = asyncio.create_task(_guarded())
  4029. _fallback_3mf_retry_tasks[printer_id] = task
  4030. logger.info(
  4031. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4032. archive_id,
  4033. reason,
  4034. printer_id,
  4035. ", ".join(f"{d:g}s" for d in delays),
  4036. )
  4037. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4038. """Whether an archive created here should ask for the print's outcome (#1898).
  4039. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4040. branches below: a queued job already has its archive and takes the
  4041. expected-print branch, where the queue item's own ``confirm_outcome``
  4042. decides. The queue is still consulted, because a restart mid-print empties
  4043. ``_expected_prints`` — without the check the setting could override a queue
  4044. item that deliberately has the flag off. Any failure answers "don't ask":
  4045. an unwanted prompt is worse than a missing one, and this must never be the
  4046. reason a print goes unarchived.
  4047. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4048. leaves one behind when a completion cannot be matched to it
  4049. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4050. only takes it back once the printer has sat connected and terminal for
  4051. minutes. Until then every screen-started print on that printer would
  4052. silently lose its prompt, so the row is held against ``observed_name`` by
  4053. the same comparison a completion uses: a positive disagreement means the row
  4054. is about some other run and this print is external after all.
  4055. """
  4056. logger = logging.getLogger(__name__)
  4057. try:
  4058. # A savepoint rather than a rollback of the caller's transaction on
  4059. # failure: a failed statement leaves the transaction unusable, but a
  4060. # full rollback also expires every object the caller has loaded (the
  4061. # printer, the archive it just created), and on an async session the
  4062. # next attribute read then raises instead of reloading. Everything here
  4063. # is a read, so undoing the savepoint loses nothing.
  4064. async with db.begin_nested():
  4065. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4066. except Exception as e:
  4067. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4068. return False
  4069. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4070. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4071. from backend.app.api.routes.settings import get_setting, setting_is_true
  4072. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4073. return False
  4074. from backend.app.models.print_queue import PrintQueueItem
  4075. dispatched_here = await db.scalar(
  4076. select(PrintQueueItem)
  4077. .where(
  4078. PrintQueueItem.printer_id == printer_id,
  4079. PrintQueueItem.status == "printing",
  4080. )
  4081. .limit(1)
  4082. )
  4083. if dispatched_here is None:
  4084. return True
  4085. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4086. observed = (observed_name or "").strip()
  4087. if not expected or not observed or _subtask_names_match(expected, observed):
  4088. logger.info(
  4089. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4090. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4091. printer_id,
  4092. dispatched_here.id,
  4093. )
  4094. return False
  4095. logger.info(
  4096. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4097. "%r; treating this as an externally started print.",
  4098. dispatched_here.id,
  4099. printer_id,
  4100. expected,
  4101. observed,
  4102. )
  4103. return True
  4104. async def _dispatch_outcome_confirmation_safely(
  4105. db,
  4106. printer_id: int,
  4107. printer_name: str,
  4108. data: dict,
  4109. archive_id: int,
  4110. archive_data: dict | None = None,
  4111. run_id: int | None = None,
  4112. ) -> None:
  4113. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4114. The completion task sends the per-user print email on the same session
  4115. right after the prompt. A failed statement in the prompt leaves that
  4116. session needing a rollback, and without one the email step fails with
  4117. PendingRollbackError; the prompt is the optional part, so it must not be
  4118. the reason the email never goes out.
  4119. """
  4120. try:
  4121. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4122. except Exception as e:
  4123. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4124. try:
  4125. await db.rollback()
  4126. except Exception:
  4127. pass
  4128. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4129. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4130. who may change everyone's archives. None (everyone on the printer) with auth
  4131. off, or for a print nobody owns."""
  4132. from sqlalchemy.orm import selectinload
  4133. from backend.app.core.auth import is_auth_enabled
  4134. from backend.app.core.permissions import Permission
  4135. from backend.app.models.user import User
  4136. if owner_id is None or not await is_auth_enabled(db):
  4137. return None
  4138. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4139. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4140. async def dispatch_outcome_confirmation(
  4141. db,
  4142. printer_id: int,
  4143. printer_name: str,
  4144. data: dict,
  4145. archive_id: int,
  4146. archive_data: dict | None = None,
  4147. *,
  4148. run_id: int | None = None,
  4149. ) -> bool:
  4150. """Emit the post-print outcome prompt for a completed print (#1898).
  4151. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4152. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4153. for a print Bambuddy did not start, copied onto the run at its start) and
  4154. ``user_verdict`` being unset is what makes the question still open. Mints
  4155. the run's capability token the one-tap verdict links carry: plates of one
  4156. archive each have their own question. Without a run, the archive's, as
  4157. before runs.
  4158. Lives here rather than inline in ``on_print_complete``'s notification task
  4159. because that task swallows every exception: extracted, the gate and the two
  4160. emissions can be driven by a test, which is the only thing standing between
  4161. a regression here and a farm that quietly stops asking.
  4162. Returns whether a prompt was sent.
  4163. """
  4164. logger = logging.getLogger(__name__)
  4165. from backend.app.models.archive import PrintArchive
  4166. from backend.app.models.print_log import PrintLogEntry
  4167. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4168. if confirm_archive is None:
  4169. return False
  4170. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4171. if run is not None and run.archive_id != archive_id:
  4172. run = None
  4173. # The run carries the opt-in from its start; one logged before it did
  4174. # (None) asks as its archive does.
  4175. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4176. holder = run if run is not None else confirm_archive
  4177. if not (asks.confirm_requested and holder.user_verdict is None):
  4178. return False
  4179. import secrets as _secrets
  4180. # A spent token stays on the row so the one-tap route can recognise it, so
  4181. # "has a token" no longer means "answerable". A prompt going out now needs a
  4182. # live one: mint a new token whenever the stored one is already spent, or
  4183. # every button in the new message would land on the already-answered page.
  4184. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4185. holder.confirm_token = _secrets.token_urlsafe(32)
  4186. holder.confirm_token_used_at = None
  4187. await db.commit()
  4188. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4189. base = await get_external_base_url(db)
  4190. if not await get_setting(db, "external_url"):
  4191. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4192. # absolute URL, so an unconfigured install used to get a message body
  4193. # with two unusable relative paths and no buttons at all. The shared
  4194. # fallback at least produces tappable links; say which setting makes
  4195. # them resolve from a phone.
  4196. logger.warning(
  4197. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4198. "Set Settings → External URL so they resolve away from this host.",
  4199. base,
  4200. )
  4201. token = holder.confirm_token
  4202. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4203. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4204. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4205. await ws_manager.send_print_confirm_request(
  4206. printer_id,
  4207. {
  4208. "archive_id": archive_id,
  4209. "run_id": run.id if run is not None else None,
  4210. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4211. },
  4212. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4213. )
  4214. await notification_service.on_print_confirm_request(
  4215. printer_id,
  4216. printer_name,
  4217. data,
  4218. db,
  4219. archive_data=archive_data,
  4220. good_url=good_url,
  4221. reject_url=reject_url,
  4222. confirm_url=confirm_url,
  4223. archive_id=archive_id,
  4224. run_id=run.id if run is not None else None,
  4225. )
  4226. return True
  4227. async def _printer_gone(db, printer_id: int) -> bool:
  4228. """Whether the printer was deleted. A column read: the session's loaded
  4229. Printer would otherwise answer for the database."""
  4230. from backend.app.models.printer import Printer
  4231. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4232. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4233. """Remove the archive just written if its printer was deleted meanwhile.
  4234. The delete route sweeps the printer's archives before it commits, so a row
  4235. committed after that sweep (the check before writing passed while the
  4236. delete was still uncommitted) is left for a printer that will never report
  4237. the print's end. A row the sweep reached is the route's: deleted with the
  4238. printer's archives, or detached (printer_id NULL) when the user kept them,
  4239. and then left as it is. Either way nothing is registered for it. Run after
  4240. the archive's commit, before anything is registered for it.
  4241. """
  4242. from backend.app.models.archive import PrintArchive
  4243. if not await _printer_gone(db, printer_id):
  4244. return False
  4245. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4246. if owner == printer_id:
  4247. logging.getLogger(__name__).info(
  4248. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4249. )
  4250. await ArchiveService(db).delete_archive(archive_id)
  4251. await forget_printer(printer_id)
  4252. return True
  4253. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4254. """After an IntegrityError on a print start's archive write: whether it was
  4255. the printer being deleted, forgotten then (the caller returns).
  4256. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4257. commit, so an archive written or adopted for it meanwhile (one that sets
  4258. printer_id) waits and the printer's foreign key then refuses it. That is
  4259. the printer being deleted, not an error; anything else is re-raised by the
  4260. caller.
  4261. """
  4262. await db.rollback()
  4263. if not await _printer_gone(db, printer_id):
  4264. return False
  4265. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4266. await forget_printer(printer_id)
  4267. return True
  4268. async def _forget_if_printer_gone(printer_id: int) -> None:
  4269. """At the end of a print start: the slow steps after the last check (smart
  4270. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4271. printer's delete and its forget_printer, and then wrote state back.
  4272. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4273. SQLite; PostgreSQL refuses it.)
  4274. Its own session: those steps can leave the handler's needing a rollback (a
  4275. write to the archive the delete removed). Never raises: it runs inside the
  4276. fallback branch's try, whose except reports the archive as failed.
  4277. """
  4278. try:
  4279. async with async_session() as db:
  4280. gone = await _printer_gone(db, printer_id)
  4281. if gone:
  4282. await forget_printer(printer_id)
  4283. except Exception:
  4284. logging.getLogger(__name__).warning(
  4285. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4286. )
  4287. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4288. """Tell the UI a plate check could not run. It does not block the print,
  4289. but an unchecked plate is not an empty one."""
  4290. try:
  4291. await ws_manager.broadcast(
  4292. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4293. )
  4294. except Exception as e:
  4295. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4296. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4297. """The ``_expected_prints`` keys a print start may be registered under."""
  4298. keys: list[tuple[int, str]] = []
  4299. if subtask_name:
  4300. keys.append((printer_id, subtask_name))
  4301. keys.append((printer_id, f"{subtask_name}.3mf"))
  4302. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4303. if filename:
  4304. fname = filename.split("/")[-1] if "/" in filename else filename
  4305. keys.append((printer_id, fname))
  4306. # Strip extensions to match
  4307. base = fname.replace(".gcode", "").replace(".3mf", "")
  4308. keys.append((printer_id, base))
  4309. keys.append((printer_id, f"{base}.3mf"))
  4310. return keys
  4311. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4312. """Whether this print start is one Bambuddy sent to the printer."""
  4313. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4314. return True
  4315. from backend.app.models.archive import PrintArchive
  4316. from backend.app.models.print_queue import PrintQueueItem
  4317. # The queue row the scheduler sets to printing before it sends -- but only
  4318. # when it was sent as this print: a row left printing by a run whose end
  4319. # was missed names another file.
  4320. dispatched_names = (
  4321. await db.execute(
  4322. select(PrintArchive.filename)
  4323. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4324. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4325. )
  4326. ).scalars()
  4327. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4328. return any(
  4329. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4330. for dispatched in dispatched_names
  4331. if dispatched
  4332. for seen in observed
  4333. )
  4334. async def on_print_start(printer_id: int, data: dict):
  4335. """Handle print start - archive the 3MF file immediately."""
  4336. logger = logging.getLogger(__name__)
  4337. # The print's start, before the 3MF download that the archive waits for
  4338. # (#3327): a minute of it would otherwise be missing from the print time.
  4339. detected_at = datetime.now(timezone.utc)
  4340. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4341. try:
  4342. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4343. except Exception:
  4344. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4345. # Clear any stale user-stopped flag from previous print cycles
  4346. _user_stopped_printers.discard(printer_id)
  4347. _kill_switch_stopped.discard(printer_id)
  4348. # A new print starts its milestones from zero (#3211). The status path only
  4349. # resets on progress below 5 while not printing, which a printer that goes
  4350. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4351. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4352. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4353. _last_progress_milestone[printer_id] = 0
  4354. _kill_switch_notification_tasks.pop(printer_id, None)
  4355. # #1721: drop any leftover pre-captured finish frame from a prior print
  4356. # so a never-consumed cache entry can't bleed into the new print's photo.
  4357. _stage22_finish_frames.pop(printer_id, None)
  4358. # #1867: same for the in-print frame bank — a queued print must not reuse
  4359. # the previous job's banked frame.
  4360. _inprint_frame_bank.pop(printer_id, None)
  4361. _inprint_frame_bank_ts.pop(printer_id, None)
  4362. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4363. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4364. # print's flag instead of inheriting it.
  4365. print_dispatch_context.adopt(printer_id)
  4366. # Cancel any active bed cooldown waiter for this printer
  4367. if _bed_cool_waiters.pop(printer_id, None):
  4368. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4369. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4370. from backend.app.api.routes.printers import clear_cover_cache
  4371. clear_cover_cache(printer_id)
  4372. await ws_manager.send_print_start(printer_id, data)
  4373. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4374. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4375. # MQTT relay - publish print start
  4376. try:
  4377. printer_info = printer_manager.get_printer(printer_id)
  4378. if printer_info:
  4379. await mqtt_relay.on_print_start(
  4380. printer_id,
  4381. printer_info.name,
  4382. printer_info.serial_number,
  4383. data.get("filename", ""),
  4384. data.get("subtask_name", ""),
  4385. )
  4386. except Exception:
  4387. pass # Don't fail print start callback if MQTT fails
  4388. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4389. # and mapping, and the seeded tray-change log.
  4390. #
  4391. # Unconditional, for both inventory backends. This only *captures* — the
  4392. # writing is still split, with the internal tracker skipped at completion
  4393. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4394. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4395. # tray-change log, and that log is the only record of which spool fed
  4396. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4397. # it on one side only would leave Spoolman users with the mid-print
  4398. # restart bug this fixes for everyone else.
  4399. try:
  4400. async with async_session() as db:
  4401. from backend.app.api.routes.settings import get_setting
  4402. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4403. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4404. await usage_on_print_start(
  4405. printer_id,
  4406. data,
  4407. printer_manager,
  4408. db=db,
  4409. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4410. )
  4411. except Exception as e:
  4412. logger.warning("Usage tracker on_print_start failed: %s", e)
  4413. # Track if notification was sent (to avoid sending twice)
  4414. notification_sent = False
  4415. # Smart plug automation: turn on plug when print starts
  4416. try:
  4417. async with async_session() as db:
  4418. await smart_plug_manager.on_print_start(printer_id, db)
  4419. except Exception as e:
  4420. logger.warning("Smart plug on_print_start failed: %s", e)
  4421. async with async_session() as db:
  4422. from backend.app.models.printer import Printer
  4423. from backend.app.services.bambu_ftp import list_files_async
  4424. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4425. printer = result.scalar_one_or_none()
  4426. # Plate detection check - pause if objects detected on build plate
  4427. logger.info(
  4428. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4429. )
  4430. if printer and printer.plate_detection_enabled:
  4431. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4432. # Release the pooled DB connection before the plate-detection camera
  4433. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4434. # printer SELECT has run so far — nothing to persist — so this commit
  4435. # is a data-noop that ends the read transaction and returns the
  4436. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4437. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4438. # archive lookups below re-acquire a fresh connection on next execute.
  4439. await db.commit()
  4440. try:
  4441. from backend.app.services.plate_detection import check_plate_empty
  4442. # Build ROI tuple from printer settings if available
  4443. roi = None
  4444. if all(
  4445. [
  4446. printer.plate_detection_roi_x is not None,
  4447. printer.plate_detection_roi_y is not None,
  4448. printer.plate_detection_roi_w is not None,
  4449. printer.plate_detection_roi_h is not None,
  4450. ]
  4451. ):
  4452. roi = (
  4453. printer.plate_detection_roi_x,
  4454. printer.plate_detection_roi_y,
  4455. printer.plate_detection_roi_w,
  4456. printer.plate_detection_roi_h,
  4457. )
  4458. # The light is held, not switched, so a live view opened
  4459. # meanwhile keeps it when the check lets go (SP-C11). Every
  4460. # printer, whatever the camera light mode: detection needs it.
  4461. plate_photo_data = None
  4462. objects_detected = False
  4463. check_failure: str | None = None
  4464. async with camera_light(printer, any_mode=True, settle=2.5):
  4465. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4466. plate_result = await check_plate_empty(
  4467. printer_id=printer_id,
  4468. ip_address=printer.ip_address,
  4469. access_code=printer.access_code,
  4470. model=printer.model,
  4471. include_debug_image=False,
  4472. external_camera_url=printer.external_camera_url,
  4473. external_camera_type=printer.external_camera_type,
  4474. use_external=printer.external_camera_enabled,
  4475. roi=roi,
  4476. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4477. )
  4478. # No reference to compare against is a check that did not
  4479. # run either: say so rather than call the plate empty.
  4480. check_failure = getattr(plate_result, "failure_reason", None) or (
  4481. "not_calibrated" if plate_result.needs_calibration else None
  4482. )
  4483. objects_detected = not check_failure and not plate_result.is_empty
  4484. if objects_detected:
  4485. # Objects detected - pause the print!
  4486. logger.warning(
  4487. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4488. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4489. )
  4490. pause_client = printer_manager.get_client(printer_id)
  4491. if pause_client:
  4492. pause_client.pause_print()
  4493. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4494. # Snapshot while the light's still on — restoring it first
  4495. # would leave the notification with a dark photo.
  4496. try:
  4497. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4498. except Exception as snap_err:
  4499. logger.warning(
  4500. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4501. )
  4502. if objects_detected:
  4503. # Send notification about plate not empty
  4504. await ws_manager.broadcast(
  4505. {
  4506. "type": "plate_not_empty",
  4507. "printer_id": printer_id,
  4508. "printer_name": printer.name,
  4509. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4510. }
  4511. )
  4512. # Also send push notification
  4513. try:
  4514. await notification_service.on_plate_not_empty(
  4515. printer_id=printer_id,
  4516. printer_name=printer.name,
  4517. db=db,
  4518. difference_percent=plate_result.difference_percent,
  4519. image_data=plate_photo_data,
  4520. )
  4521. except Exception as notif_err:
  4522. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4523. elif check_failure:
  4524. logger.warning(
  4525. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4526. printer_id,
  4527. check_failure,
  4528. plate_result.message,
  4529. )
  4530. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4531. else:
  4532. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4533. except Exception as plate_err:
  4534. # Don't block print on plate detection errors
  4535. logger.warning(
  4536. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4537. printer_id,
  4538. plate_err,
  4539. )
  4540. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4541. if not printer:
  4542. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4543. if not notification_sent:
  4544. await _send_print_start_notification(printer_id, data, logger=logger)
  4545. return
  4546. # Skip the printer's own jobs — a calibration run is not a user's print.
  4547. # See is_internal_printer_job for what counts and why both fields are
  4548. # tested; the pressure-advance line reports as a subtask name with no
  4549. # /usr/ path, which the old prefix-only test here missed entirely.
  4550. #
  4551. # No notification either. The event describes the printer calibrating
  4552. # itself, so "Print started" is as wrong as the archive was, and the
  4553. # matching completion is suppressed in on_print_complete for the same
  4554. # reason. Checked before the auto-archive switches, whose "off" path
  4555. # still notifies.
  4556. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4557. # print Bambuddy dispatched is never one, whatever it is called.
  4558. # Dispatched = an expected print, or, after a restart that lost those,
  4559. # a queue job printing on the printer.
  4560. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4561. (data.get("filename") or "").startswith("/usr/")
  4562. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4563. ):
  4564. logger.info(
  4565. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4566. data.get("filename", ""),
  4567. data.get("subtask_name", ""),
  4568. )
  4569. return
  4570. # The global switch is the master: off, no printer archives prints
  4571. # started outside Bambuddy; on, each printer's own switch decides.
  4572. from backend.app.api.routes.settings import get_setting
  4573. _global_auto_archive = await get_setting(db, "auto_archive")
  4574. archives_prints = printer.auto_archive and (
  4575. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4576. )
  4577. if not archives_prints:
  4578. # auto-archive disabled — check if there's an expected print (dispatched
  4579. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4580. # If so, fall through to the expected-print handling below so the archive
  4581. # is tracked in _active_prints and usage tracking works at completion.
  4582. _fn = data.get("filename", "")
  4583. _sn = data.get("subtask_name", "")
  4584. _check_keys: list[tuple[int, str]] = []
  4585. if _sn:
  4586. _check_keys += [
  4587. (printer_id, _sn),
  4588. (printer_id, f"{_sn}.3mf"),
  4589. (printer_id, f"{_sn}.gcode.3mf"),
  4590. ]
  4591. if _fn:
  4592. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4593. _check_keys.append((printer_id, _base_fn))
  4594. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4595. _check_keys += [
  4596. (printer_id, _no_archive_base),
  4597. (printer_id, f"{_no_archive_base}.3mf"),
  4598. ]
  4599. _has_expected = any(k in _expected_prints for k in _check_keys)
  4600. if not _has_expected:
  4601. # No expected print — truly external print (started from slicer/touchscreen)
  4602. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4603. if not notification_sent:
  4604. _no_archive_creator: int | None = None
  4605. for _key in _check_keys:
  4606. _expected_prints.pop(_key, None)
  4607. _expected_print_registered_at.pop(_key, None)
  4608. popped_creator = _expected_print_creators.pop(_key, None)
  4609. if _no_archive_creator is None:
  4610. _no_archive_creator = popped_creator
  4611. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4612. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4613. return
  4614. else:
  4615. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4616. # Get the filename and subtask_name
  4617. filename = data.get("filename", "")
  4618. subtask_name = data.get("subtask_name", "")
  4619. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4620. # present, it lets us match an archive across a backend restart (#972):
  4621. # same id → same print → resume the existing row instead of cancelling
  4622. # it and recreating from scratch (which loses started_at). Treat "0"
  4623. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4624. raw_mqtt = data.get("raw_data") or {}
  4625. subtask_id = raw_mqtt.get("subtask_id")
  4626. if subtask_id is not None:
  4627. subtask_id = str(subtask_id).strip()
  4628. if subtask_id in ("", "0"):
  4629. subtask_id = None
  4630. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4631. if not filename and not subtask_name:
  4632. # Send notification without archive data (no filename)
  4633. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4634. if not notification_sent:
  4635. await _send_print_start_notification(printer_id, data, logger=logger)
  4636. return
  4637. # Check if this is an expected print from reprint/scheduled
  4638. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4639. expected_archive_id = None
  4640. # Who queued it, taken with the entries it was registered beside: left
  4641. # behind once those are gone (the archive deleted mid-dispatch, or the
  4642. # start notification already sent), the expiry never saw it, and an
  4643. # unrelated later print of that name was attributed to that user (EP-2).
  4644. fallback_creator = None
  4645. for key in expected_keys:
  4646. expected_archive_id = _expected_prints.pop(key, None)
  4647. _expected_print_registered_at.pop(key, None)
  4648. if expected_archive_id:
  4649. # Clean up other possible keys for this print
  4650. for other_key in expected_keys:
  4651. _expected_prints.pop(other_key, None)
  4652. _expected_print_registered_at.pop(other_key, None)
  4653. creator = _expected_print_creators.pop(other_key, None)
  4654. if fallback_creator is None:
  4655. fallback_creator = creator
  4656. break
  4657. if expected_archive_id:
  4658. # This is a reprint/scheduled print - use existing archive, don't create new one
  4659. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4660. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4661. # Bambuddy's once the expected entry is consumed here.
  4662. _owned_print_archive_ids.add(expected_archive_id)
  4663. from backend.app.models.archive import PrintArchive
  4664. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4665. archive = result.scalar_one_or_none()
  4666. # Deleted after this handler loaded it (the plate check waits
  4667. # seconds) but before the route forgot the expected print: the
  4668. # archive the route kept or deleted is left as the route left it.
  4669. if archive and await _printer_gone(db, printer_id):
  4670. logger.info(
  4671. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4672. )
  4673. await forget_printer(printer_id)
  4674. return
  4675. if archive:
  4676. # As it was before this adoption: put back if the printer turns
  4677. # out to have been deleted while it was adopted (below).
  4678. before_adoption = {
  4679. attr.columns[0].name: getattr(archive, attr.key)
  4680. for attr in sa_inspect(PrintArchive).column_attrs
  4681. if attr.key != "id"
  4682. }
  4683. # Update archive status to printing
  4684. archive.status = "printing"
  4685. archive.started_at = datetime.now(timezone.utc)
  4686. # The previous run's outcome is not this one's: a reprint that
  4687. # completes must not keep showing why the last one failed.
  4688. archive.failure_reason = None
  4689. archive.completed_at = None
  4690. # The previous run's answer is still on this row and the
  4691. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4692. # so without a reset the second run inherits the first run's
  4693. # verdict: no prompt at all, and a green "good" badge on a run
  4694. # nobody ever judged.
  4695. if archive.confirm_requested:
  4696. archive.user_verdict = None
  4697. archive.user_verdict_source = None
  4698. archive.user_verdict_at = None
  4699. archive.confirm_token = None
  4700. archive.confirm_token_used_at = None
  4701. # Reprint of an archive reuses the source row. Without resetting
  4702. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4703. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4704. # extracts the *original* print's last frame, which then ships in
  4705. # the completion notification (#1707). Clear the path so the
  4706. # scanner runs fresh; also unlink the old video file so reprints
  4707. # don't accumulate orphans in the archive directory. Photos list
  4708. # is left alone — accumulating one finish photo per run is fine.
  4709. # The print-start baseline (#2704) is stale for the same reason:
  4710. # it describes the printer before the previous run. The capture
  4711. # below overwrites it, but clear it here too so an early failure
  4712. # can't leave the scan diffing against the wrong snapshot.
  4713. #
  4714. # Unlinked only when it is the same plate printing again. Every
  4715. # plate of a Send All shares this archive, and the video on it
  4716. # can be the only copy of another plate's run -- the printer's
  4717. # was deleted once it attached (#3275). That one is left in the
  4718. # archive directory, which goes with the archive. A video whose
  4719. # plate is not on record (attached by hand, or before the
  4720. # column existed) is kept too where the 3MF has other plates,
  4721. # or cannot be read: nothing tells it apart from another plate's,
  4722. # and keeping costs one file where deleting can cost the only
  4723. # copy. On an archive with exactly one plate it is that plate's.
  4724. archive.timelapse_baseline = None
  4725. stale_timelapse_relpath = archive.timelapse_path
  4726. stale_timelapse_plate_id = archive.timelapse_plate_id
  4727. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4728. if stale_timelapse_relpath:
  4729. archive.timelapse_path = None
  4730. archive.timelapse_plate_id = None
  4731. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4732. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4733. from backend.app.services.archive import plate_indexes_in_3mf
  4734. plates = await asyncio.to_thread(
  4735. plate_indexes_in_3mf,
  4736. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4737. )
  4738. stale_is_this_plates = len(plates) == 1
  4739. if stale_timelapse_relpath and not stale_is_this_plates:
  4740. logger.info(
  4741. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4742. stale_timelapse_relpath,
  4743. stale_timelapse_plate_id,
  4744. expected_archive_id,
  4745. starting_plate_id,
  4746. )
  4747. # The video is deleted once the adoption stands (below).
  4748. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4749. # Persist a restart-stable id so a later restart resumes this
  4750. # archive by subtask_id instead of name-matching + duplicating
  4751. # it (#1485). The printer often hasn't echoed subtask_id back
  4752. # this soon after dispatch, so fall back to the id Bambuddy
  4753. # minted when it sent the print command. Scoped to this
  4754. # expected-print branch on purpose: an expected match means
  4755. # Bambuddy dispatched this exact print in this process, so the
  4756. # client's last-dispatch id genuinely belongs to it — using it
  4757. # for an externally-started print could mis-tag the archive.
  4758. effective_subtask_id = subtask_id
  4759. if not effective_subtask_id:
  4760. _client = printer_manager.get_client(printer_id)
  4761. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4762. if _dispatched:
  4763. effective_subtask_id = str(_dispatched).strip() or None
  4764. # Update on first-set OR on reprint (the queue dispatcher mints
  4765. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4766. # the rewrite for reprints leaves the archive holding the FIRST
  4767. # run's id; if MQTT then reconnects mid-print, the reconciler
  4768. # (#1542) compares the stale stored id against the printer's
  4769. # live id, sees a mismatch, and synthesises a bogus PRINT
  4770. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4771. # in #1807. Inequality check preserves the noop-on-stable-push
  4772. # behaviour the earlier `not archive.subtask_id` guard provided.
  4773. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4774. archive.subtask_id = effective_subtask_id
  4775. # #1403 follow-up: VP-queue archives are created with
  4776. # printer_id=None at queue-add time (we don't know which
  4777. # printer will run the job yet). When the print actually
  4778. # starts on a specific printer the expected-archive lookup
  4779. # used to skip this assignment, leaving printer_id=None
  4780. # forever — which then disables the "Scan for timelapse"
  4781. # button in ArchivesPage (gated on !archive.printer_id).
  4782. if archive.printer_id != printer_id:
  4783. archive.printer_id = printer_id
  4784. adopting_id = archive.id # a rollback expires the object
  4785. try:
  4786. await db.commit()
  4787. except (IntegrityError, StaleDataError):
  4788. # The archive stays unchanged, or is gone: "delete archives"
  4789. # removed the row under the adoption, which then matched no
  4790. # row (StaleDataError) rather than being refused.
  4791. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4792. return
  4793. raise
  4794. # The printer can be deleted between the check above and this
  4795. # commit (the route's transaction lasts seconds), and the commit
  4796. # then adopted the archive anyway: status, verdict and timelapse
  4797. # changed, and the deleted printer's id written on a row the
  4798. # route had detached or never touched. Undo the adoption.
  4799. if await _printer_gone(db, printer_id):
  4800. logger.info(
  4801. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4802. printer_id,
  4803. archive.id,
  4804. )
  4805. # Everything as before this adoption. The printer it had
  4806. # then stays, unless it was the deleted one: the route
  4807. # detached that row (kept) or deleted it (no row matches).
  4808. previous_printer = before_adoption["printer_id"]
  4809. await db.execute(
  4810. update(PrintArchive)
  4811. .where(PrintArchive.id == archive.id)
  4812. .values(
  4813. {
  4814. **before_adoption,
  4815. "printer_id": None if previous_printer == printer_id else previous_printer,
  4816. }
  4817. )
  4818. )
  4819. await db.commit()
  4820. await forget_printer(printer_id)
  4821. return
  4822. await _drop_replaced_plate_videos(
  4823. db,
  4824. archive.id,
  4825. starting_plate_id,
  4826. stale_timelapse_relpath if delete_stale_video else None,
  4827. logger,
  4828. )
  4829. # Track as active print
  4830. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4831. await _open_run_for(archive.id, printer_id, subtask_id)
  4832. # Start timelapse session if external camera is enabled (#1353).
  4833. # Queue / VP-dispatched prints land here in the expected-archive
  4834. # branch and used to skip start_session entirely — frames were
  4835. # never captured and the post-print stitch silently returned None.
  4836. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4837. # Inject ams_mapping into usage tracker session — the session was created
  4838. # before expected-print promotion, so it may have ams_mapping=None when
  4839. # the MQTT request topic subscription failed (common on P1S/A1).
  4840. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4841. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4842. if _stored_map or _stored_plate_id is not None:
  4843. try:
  4844. from backend.app.services.usage_tracker import _active_sessions
  4845. _ut_session = _active_sessions.get(printer_id)
  4846. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4847. _ut_session.ams_mapping = _stored_map
  4848. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4849. # plate_id injection covers direct-Print of plate N of a multi-plate
  4850. # 3MF — queue prints already capture it via the on_print_start queue
  4851. # lookup, but direct-Print never goes through the queue (#1697).
  4852. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4853. _ut_session.plate_id = _stored_plate_id
  4854. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4855. except Exception:
  4856. pass
  4857. # Set up energy tracking (#941: persist start on archive row)
  4858. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4859. await ws_manager.send_archive_updated(
  4860. {
  4861. "id": archive.id,
  4862. "status": "printing",
  4863. }
  4864. )
  4865. # Send notification with archive data (reprint/scheduled)
  4866. if not notification_sent:
  4867. # Use archive's created_by_id; fall back to the creator registered via
  4868. # register_expected_print (handles library-file-based queue items where
  4869. # the freshly-created archive has no created_by_id yet), taken above.
  4870. archive_data = {
  4871. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4872. "created_by_id": archive.created_by_id or fallback_creator,
  4873. }
  4874. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4875. # Extract printable objects from the archived 3MF file
  4876. _load_objects_from_archive(archive, printer_id, logger)
  4877. if archive.file_path:
  4878. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4879. # Store Spoolman tracking data for per-filament usage reporting
  4880. try:
  4881. await _store_spoolman_print_data(
  4882. printer_id,
  4883. archive.id,
  4884. archive.file_path,
  4885. db,
  4886. printer_manager,
  4887. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4888. plate_id=_get_start_plate_id(printer_id, archive.id),
  4889. )
  4890. except Exception as e:
  4891. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4892. # Price the print from its spools now rather than only at completion (#3261)
  4893. _schedule_archive_cost_estimate(
  4894. printer_id,
  4895. archive.id,
  4896. printer_manager,
  4897. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4898. plate_id=_get_start_plate_id(printer_id, archive.id),
  4899. session_factory=async_session,
  4900. )
  4901. # Capture timelapse file baseline for snapshot-diff on completion
  4902. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4903. # hit this branch — without the baseline the completion-time scan
  4904. # falls into its "take baseline now" fallback, which snapshots
  4905. # AFTER the new MP4 already exists and never matches a diff
  4906. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4907. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4908. await _forget_if_printer_gone(printer_id)
  4909. return # Skip creating a new archive
  4910. # The archive was deleted after the job was queued.
  4911. if not archives_prints:
  4912. # Only the expected print brought a printer that does not
  4913. # archive this far; with it gone, nothing is archived.
  4914. return
  4915. # Otherwise archive the print anew rather than drop it, so it still
  4916. # gets its notification, usage tracking and history.
  4917. logger.warning(
  4918. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4919. expected_archive_id,
  4920. printer_id,
  4921. )
  4922. # Check if there's already a "printing" archive for this printer/file
  4923. # This prevents duplicates when backend restarts during an active print
  4924. from backend.app.models.archive import PrintArchive
  4925. existing_archive: PrintArchive | None = None
  4926. resumed_by_run = False
  4927. # Best match: this job's run, open on the printer since the print
  4928. # started. The archive row is shared by every plate of it, and its
  4929. # printer, job id and status are the latest start's, which may be
  4930. # another printer's.
  4931. if subtask_id:
  4932. from backend.app.services.print_log import open_run_on_printer
  4933. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4934. if run is not None and run.archive_id is not None:
  4935. existing_archive = await db.scalar(
  4936. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4937. )
  4938. resumed_by_run = existing_archive is not None
  4939. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4940. # across a backend restart for the same print, so this is the most
  4941. # reliable way to reattach. Only a row still printing: a cancelled one
  4942. # has been through completion (usage, history, notifications) already,
  4943. # and reopening it would count the print twice.
  4944. if subtask_id and existing_archive is None:
  4945. by_id = await db.execute(
  4946. select(PrintArchive)
  4947. .where(PrintArchive.printer_id == printer_id)
  4948. .where(PrintArchive.subtask_id == subtask_id)
  4949. .where(PrintArchive.status == "printing")
  4950. .order_by(PrintArchive.created_at.desc())
  4951. .limit(1)
  4952. )
  4953. existing_archive = by_id.scalar_one_or_none()
  4954. # Fallback match: name-based lookup. Kept as-is for prints whose
  4955. # subtask_id is missing ("0" / local / non-cloud prints).
  4956. if existing_archive is None:
  4957. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4958. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4959. # A print started from the printer's screen names its file in full,
  4960. # so the forms above double its extension. The file itself is the
  4961. # one exact match, and nothing looser is added (#3009).
  4962. if _subtask_is_the_file(subtask_name, filename):
  4963. archive_filenames.append(subtask_name)
  4964. existing = await db.execute(
  4965. select(PrintArchive)
  4966. .where(PrintArchive.printer_id == printer_id)
  4967. .where(PrintArchive.status == "printing")
  4968. .where(
  4969. or_(
  4970. PrintArchive.print_name == check_name,
  4971. PrintArchive.filename.in_(archive_filenames),
  4972. )
  4973. )
  4974. .order_by(PrintArchive.created_at.desc())
  4975. .limit(1)
  4976. )
  4977. existing_archive = existing.scalar_one_or_none()
  4978. if existing_archive:
  4979. # subtask_id match → always resume, regardless of age. Same print,
  4980. # just a backend restart.
  4981. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4982. if subtask_match:
  4983. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4984. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4985. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  4986. _mark_owned_if_dispatched(existing_archive)
  4987. if await _run_needs_energy_start(existing_archive, printer_id, db):
  4988. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4989. if not notification_sent:
  4990. archive_data = {
  4991. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  4992. "created_by_id": existing_archive.created_by_id,
  4993. }
  4994. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4995. _load_objects_from_archive(existing_archive, printer_id, logger)
  4996. if existing_archive.file_path:
  4997. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4998. return
  4999. # Name-match only (no subtask_id to anchor on): decide resume vs.
  5000. # stale from the printer's *current* progress, not wall-clock age.
  5001. # A genuinely long print used to trip a blind 4h cutoff and have its
  5002. # live archive cancelled + duplicated on every backend restart
  5003. # (#1485). If the printer reports real progress, this name-matched
  5004. # 'printing' archive IS that ongoing print — resume it whatever its
  5005. # age. Only treat it as a stale leftover when the printer clearly
  5006. # shows a different, freshly-started print: near-0% progress on an
  5007. # archive far too old to still be at 0%. Unknown progress (printer
  5008. # not connected) never cancels — resuming is the safe default.
  5009. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  5010. live_status = printer_manager.get_status(printer_id)
  5011. live_progress = getattr(live_status, "progress", None) if live_status else None
  5012. looks_stale = (
  5013. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  5014. )
  5015. # Two subtask ids are two prints, however young the archive: one
  5016. # whose completion was missed must not swallow the next print of
  5017. # the same file. Except Bambuddy's own reprint, which reuses the
  5018. # row and mints a fresh id (#1807): the id it last sent says so,
  5019. # and after a restart, which forgets it, this printer's queue job
  5020. # running the archive.
  5021. if (
  5022. not looks_stale
  5023. and subtask_id
  5024. and existing_archive.subtask_id
  5025. and existing_archive.subtask_id != subtask_id
  5026. ):
  5027. _client = printer_manager.get_client(printer_id)
  5028. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5029. if _dispatched:
  5030. looks_stale = _dispatched != subtask_id
  5031. else:
  5032. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5033. queue_run = await db.scalar(
  5034. select(_PQI.id)
  5035. .where(_PQI.archive_id == existing_archive.id)
  5036. .where(_PQI.printer_id == printer_id)
  5037. .where(_PQI.status == "printing")
  5038. .limit(1)
  5039. )
  5040. looks_stale = queue_run is None
  5041. if looks_stale:
  5042. logger.warning(
  5043. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5044. " — marking cancelled and creating new archive",
  5045. existing_archive.id,
  5046. archive_age,
  5047. live_progress,
  5048. existing_archive.subtask_id,
  5049. subtask_id,
  5050. )
  5051. existing_archive.status = "cancelled"
  5052. # Canonical key, not a sentence (issue #2974). "No status update
  5053. # received" is what both stale paths actually observed; which of
  5054. # the two it was is already carried by ``status`` -- cancelled
  5055. # here, the reconciled outcome at the reconnect site -- so one
  5056. # key loses no information and gives the Statistics breakdown a
  5057. # single bucket instead of two untranslatable prose strings.
  5058. existing_archive.failure_reason = "noStatusUpdate"
  5059. # And its run, as before runs were opened at the start: a new
  5060. # print starts on the printer, so whatever is open there ended
  5061. # unseen. Left open, the next reconnect would close it again.
  5062. from backend.app.services.print_log import discard_open_runs
  5063. discarded = await discard_open_runs(db, printer_id)
  5064. await db.commit()
  5065. await _announce_discarded_runs(discarded, printer_id)
  5066. # Its print keys go with it; the new archive registers its own.
  5067. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5068. del _active_prints[_key]
  5069. # Fall through to create new archive (don't return)
  5070. else:
  5071. logger.info(
  5072. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5073. )
  5074. # Track this as the active print
  5075. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5076. _mark_owned_if_dispatched(existing_archive)
  5077. # Attach subtask_id retroactively so future restarts can resume.
  5078. # Compare for inequality (not "is empty") to also pick up reprint
  5079. # dispatches that mint a fresh id — see #1807 for the bogus
  5080. # "Print Stopped" the strict-empty guard caused on reconnect.
  5081. if subtask_id and existing_archive.subtask_id != subtask_id:
  5082. existing_archive.subtask_id = subtask_id
  5083. await db.commit()
  5084. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5085. # Also set up energy tracking if not already tracked (#941: persisted column)
  5086. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5087. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5088. # Send notification with archive data (existing archive)
  5089. if not notification_sent:
  5090. archive_data = {
  5091. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5092. "created_by_id": existing_archive.created_by_id,
  5093. }
  5094. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5095. # Extract printable objects from the archived 3MF file
  5096. _load_objects_from_archive(existing_archive, printer_id, logger)
  5097. if existing_archive.file_path:
  5098. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5099. return
  5100. # Build list of possible 3MF filenames to try
  5101. possible_names = []
  5102. # Bambu printers typically store files as "Name.gcode.3mf"
  5103. # The subtask_name is usually the best source for the filename
  5104. if subtask_name:
  5105. if _subtask_is_the_file(subtask_name, filename):
  5106. # A print started from the printer's own screen reports the
  5107. # file's full name, extension included. That is the file, so
  5108. # no extension is appended to it (#3009).
  5109. possible_names.append(subtask_name)
  5110. else:
  5111. # Try common Bambu naming patterns
  5112. possible_names.append(f"{subtask_name}.gcode.3mf")
  5113. possible_names.append(f"{subtask_name}.3mf")
  5114. # Try original filename with .3mf extension
  5115. if filename:
  5116. # Extract just the filename part, not the full path
  5117. fname = filename.split("/")[-1] if "/" in filename else filename
  5118. if fname.endswith(".3mf"):
  5119. possible_names.append(fname)
  5120. elif fname.endswith(".gcode"):
  5121. base = fname.rsplit(".", 1)[0]
  5122. possible_names.append(f"{base}.gcode.3mf")
  5123. possible_names.append(f"{base}.3mf")
  5124. else:
  5125. possible_names.append(f"{fname}.gcode.3mf")
  5126. possible_names.append(f"{fname}.3mf")
  5127. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5128. space_variants = []
  5129. for name in possible_names:
  5130. if " " in name:
  5131. space_variants.append(name.replace(" ", "_"))
  5132. possible_names.extend(space_variants)
  5133. # Remove duplicates while preserving order
  5134. seen = set()
  5135. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5136. logger.info("Trying filenames: %s", possible_names)
  5137. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5138. # here means none of the expected-/existing-archive write branches ran
  5139. # (they all return earlier) — only SELECTs have executed on this path, so
  5140. # this commit persists nothing; it ends the read transaction so the
  5141. # connection returns to the pool during the download. That download tries
  5142. # up to five remote paths per candidate filename with retry/backoff and
  5143. # can run for minutes under FTP contention; holding the session across it
  5144. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5145. # work runs during the download — the new-archive writes below re-acquire
  5146. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5147. await db.commit()
  5148. # Try to find and download the 3MF file
  5149. temp_path = None
  5150. downloaded_filename = None
  5151. # Cache check: cover endpoint may have already pulled this 3MF during
  5152. # the print (frontend opens the card and shows the thumbnail) — reuse
  5153. # that file instead of re-downloading 36MB over the same FTP link that
  5154. # just served it (#972). The cache keys on a normalized filename so
  5155. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5156. for try_filename in possible_names:
  5157. if not try_filename.endswith(".3mf"):
  5158. continue
  5159. cached = get_cached_3mf(printer_id, try_filename)
  5160. if cached:
  5161. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5162. temp_path = cached
  5163. downloaded_filename = try_filename
  5164. break
  5165. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5166. # H2-series and P2S the answer is routinely no — the file stays on
  5167. # internal eMMC and port 990 only ever serves external storage — and
  5168. # then the whole sweep below (six filenames x five directories x four
  5169. # retries, then the directory walk) is ~110 connections that cannot
  5170. # succeed. Skip it and say why (#2780).
  5171. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5172. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5173. # running rather than because the file is somewhere unreachable. The
  5174. # distinction is the whole of #2957: one is permanent, the other clears
  5175. # in minutes with the file still sitting on the printer.
  5176. blocked_by_ftps_cooloff = False
  5177. # Set when a probe reached the printer and still came back without the
  5178. # file -- a timeout mid-transfer, a refused connection, anything that is
  5179. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5180. # caught by name below, so a file that genuinely is not on the card
  5181. # leaves this False and schedules nothing. Anything else means the
  5182. # transfer, not the file, is what failed, and that does not last (#3063).
  5183. ftp_transfer_failed = False
  5184. # The narrower case of the above: the directory walk *listed* a file
  5185. # for this print and could not fetch it, so the file is on the card
  5186. # under a name that matches. The only failure that rules out an
  5187. # earlier run's 3MF standing in for it (#3307).
  5188. walk_transfer_failed = False
  5189. # Paths the sweep reached and could not transfer -- a timeout, not a
  5190. # 550. The directory walk lists the same folders and would download
  5191. # the same file again: on a slow A1 that was a second 300 s on the
  5192. # printer's one FTPS slot, at print start, for a file the recovery
  5193. # retry fetches with a deadline twice as long (#3308).
  5194. sweep_failed_paths: set[str] = set()
  5195. # The print's name, for a fallback archive whose `subtask_name` the
  5196. # plate guard below had to disown. Display only, and deliberately kept
  5197. # apart from `subtask_name`: that variable is what every file lookup
  5198. # here is built from, and once a name has been shown to fetch another
  5199. # plate's 3MF it must not key `_active_prints` either, or the cover
  5200. # endpoint hands the same contradicted file to
  5201. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5202. display_name_after_plate_reject: str | None = None
  5203. # Get FTP retry settings
  5204. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5205. # ...but "the printer put it on eMMC" is where it went, not whether we
  5206. # can read it. An H2D with a card in mirrors the job to /cache and
  5207. # serves it happily, and skipping on the URL alone cost that reporter
  5208. # every archive for two days (#2856). So ask the printer instead of
  5209. # guessing: the dispatch named the exact file, which is one connection
  5210. # walking five paths rather than the sweep's ~110. Only when the probe
  5211. # comes back empty does the verdict's reason stand.
  5212. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5213. if ftps_handshake_blocked(printer.ip_address):
  5214. # Deliberately NOT recorded as a cool-off give-up. This branch
  5215. # only runs on an unreachable verdict, and that verdict is the
  5216. # honest, permanent reason the archive is empty — the probe was
  5217. # a long shot on top of it. Blaming the cool-off here would
  5218. # schedule a retry for a file sitting on internal eMMC, which is
  5219. # the sweep #2780 removed (#2957).
  5220. logger.debug(
  5221. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5222. storage.probe_filename,
  5223. printer_id,
  5224. )
  5225. else:
  5226. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5227. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5228. try:
  5229. probe_hit = await download_file_try_paths_async(
  5230. printer.ip_address,
  5231. printer.access_code,
  5232. ftp_probe_paths(storage.probe_filename),
  5233. probe_path,
  5234. socket_timeout=ftp_timeout,
  5235. printer_model=printer.model,
  5236. )
  5237. except Exception as e:
  5238. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5239. probe_hit = False
  5240. if probe_hit:
  5241. downloaded_filename = storage.probe_filename
  5242. temp_path = probe_path
  5243. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5244. # Naming the path, not just the file: a printer that keeps
  5245. # uploads around for weeks can serve a same-named copy of an
  5246. # earlier slice, and without the directory in the log that
  5247. # mismatch is invisible rather than merely rare (#1820).
  5248. logger.info(
  5249. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5250. downloaded_filename,
  5251. probe_hit,
  5252. printer_id,
  5253. storage.reason,
  5254. )
  5255. if not storage.reachable and not downloaded_filename:
  5256. # Same opening words whether or not a probe ran, because that is
  5257. # the phrase support asks people to grep for — only the tail says
  5258. # which of the two happened.
  5259. logger.info(
  5260. "Skipping the 3MF lookup for printer %s: %s — %s",
  5261. printer_id,
  5262. storage.reason,
  5263. "no copy of it on external storage either"
  5264. if storage.probe_filename
  5265. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5266. )
  5267. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5268. if not try_filename.endswith(".3mf"):
  5269. continue
  5270. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5271. # printers, so try it first — deferring it to last cost #972's reporter
  5272. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5273. # landing on the path that actually had the file.
  5274. remote_paths = [
  5275. f"/{try_filename}",
  5276. f"/cache/{try_filename}",
  5277. f"/model/{try_filename}",
  5278. f"/data/{try_filename}",
  5279. f"/data/Metadata/{try_filename}",
  5280. ]
  5281. temp_path = app_settings.archive_dir / "temp" / try_filename
  5282. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5283. for remote_path in remote_paths:
  5284. if ftps_handshake_blocked(printer.ip_address):
  5285. # The printer's FTPS service is not completing a TLS
  5286. # handshake, so it has no path we could reach — walking the
  5287. # remaining candidates only re-runs the same failure
  5288. # (#2780). Fall through to the no-3MF archive now.
  5289. #
  5290. # Remember *why*, though. This is the one give-up that is
  5291. # temporary: the cool-off clears in minutes and the file was
  5292. # on the printer the whole time. The fallback archive is
  5293. # stamped with it so a retry can be scheduled, and so the
  5294. # Archives banner stops blaming storage (#2957).
  5295. blocked_by_ftps_cooloff = True
  5296. logger.warning(
  5297. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5298. printer_id,
  5299. )
  5300. break
  5301. logger.debug("Trying FTP download: %s", remote_path)
  5302. try:
  5303. if ftp_retry_enabled:
  5304. downloaded = await with_ftp_retry(
  5305. download_file_async,
  5306. printer.ip_address,
  5307. printer.access_code,
  5308. remote_path,
  5309. temp_path,
  5310. timeout=ftp_timeout,
  5311. socket_timeout=ftp_timeout,
  5312. printer_model=printer.model,
  5313. max_retries=ftp_retry_count,
  5314. retry_delay=ftp_retry_delay,
  5315. operation_name=f"Download 3MF from {remote_path}",
  5316. cooloff_ip=printer.ip_address,
  5317. non_retry_exceptions=(FileNotOnPrinterError,),
  5318. )
  5319. else:
  5320. downloaded = await download_file_async(
  5321. printer.ip_address,
  5322. printer.access_code,
  5323. remote_path,
  5324. temp_path,
  5325. timeout=ftp_timeout,
  5326. socket_timeout=ftp_timeout,
  5327. printer_model=printer.model,
  5328. )
  5329. if downloaded:
  5330. downloaded_filename = try_filename
  5331. logger.info("Downloaded: %s", remote_path)
  5332. # Populate shared cache so the cover endpoint (if it
  5333. # runs next) doesn't refetch the same 36MB over FTP.
  5334. cache_3mf_download(printer_id, try_filename, temp_path)
  5335. break
  5336. # with_ftp_retry returns None once it has spent its budget,
  5337. # and download_file_async returns False on a timeout, so an
  5338. # exhausted transfer arrives here rather than as an
  5339. # exception (#3063).
  5340. ftp_transfer_failed = True
  5341. sweep_failed_paths.add(remote_path)
  5342. except FileNotOnPrinterError:
  5343. # 550 — file isn't at this path. Advance to next candidate
  5344. # without burning the retry budget.
  5345. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5346. except Exception as e:
  5347. ftp_transfer_failed = True
  5348. sweep_failed_paths.add(remote_path)
  5349. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5350. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5351. break
  5352. # If still not found, try listing directories to find matching file
  5353. # Different printer models use different directory structures. Skipped
  5354. # when the printer's FTPS handshake is failing — the directory walk is
  5355. # five more connections that cannot get further than the download did.
  5356. if (
  5357. not downloaded_filename
  5358. and storage.reachable
  5359. and (filename or subtask_name)
  5360. and not ftps_handshake_blocked(printer.ip_address)
  5361. ):
  5362. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5363. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5364. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5365. # Every folder is listed before one file is picked, so a file named
  5366. # for the print in a later folder wins over one that merely
  5367. # contains the name in an earlier folder.
  5368. listed_paths: list[str] = []
  5369. for search_dir in search_dirs:
  5370. try:
  5371. dir_files = await list_files_async(
  5372. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5373. )
  5374. except Exception as e:
  5375. logger.debug("Failed to list %s: %s", search_dir, e)
  5376. continue
  5377. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5378. if threemf_files:
  5379. logger.info(
  5380. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5381. )
  5382. listed_paths += [
  5383. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5384. ]
  5385. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5386. if remote_full_path in sweep_failed_paths:
  5387. # Listed for this print, and its transfer already failed:
  5388. # the same as a failed walk download, without spending a
  5389. # second deadline on it. Skipping it cannot hand the walk a
  5390. # look-alike: while a file of the print's own name is
  5391. # listed, files that merely contain the name are not.
  5392. logger.info(
  5393. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5394. remote_full_path,
  5395. )
  5396. walk_transfer_failed = True
  5397. continue
  5398. fname = posixpath.basename(remote_full_path)
  5399. logger.info("Found matching file: %s", remote_full_path)
  5400. temp_path = app_settings.archive_dir / "temp" / fname
  5401. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5402. try:
  5403. if ftp_retry_enabled:
  5404. downloaded = await with_ftp_retry(
  5405. download_file_async,
  5406. printer.ip_address,
  5407. printer.access_code,
  5408. remote_full_path,
  5409. temp_path,
  5410. timeout=ftp_timeout,
  5411. socket_timeout=ftp_timeout,
  5412. printer_model=printer.model,
  5413. max_retries=ftp_retry_count,
  5414. retry_delay=ftp_retry_delay,
  5415. operation_name=f"Download 3MF from {remote_full_path}",
  5416. cooloff_ip=printer.ip_address,
  5417. )
  5418. else:
  5419. downloaded = await download_file_async(
  5420. printer.ip_address,
  5421. printer.access_code,
  5422. remote_full_path,
  5423. temp_path,
  5424. timeout=ftp_timeout,
  5425. socket_timeout=ftp_timeout,
  5426. printer_model=printer.model,
  5427. )
  5428. except Exception as e:
  5429. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5430. continue
  5431. if downloaded:
  5432. downloaded_filename = fname
  5433. logger.info("Found and downloaded: %s", remote_full_path)
  5434. cache_3mf_download(printer_id, fname, temp_path)
  5435. break
  5436. # The listing named the file, so it is on the card;
  5437. # only the transfer failed (#3063).
  5438. ftp_transfer_failed = True
  5439. walk_transfer_failed = True
  5440. # A "Print again" on the printer's screen names no file Bambuddy can
  5441. # find: only its history copy under a generic name, and the 3MF's
  5442. # internal title (#3307). When an earlier run of the same job was
  5443. # archived, its 3MF is the one being printed again. Not when the
  5444. # directory walk listed a file for this print and only its transfer
  5445. # failed: that file is on the card, and the retry fetches it. A
  5446. # cool-off or a failed sweep path is no such evidence -- the retry
  5447. # tries the same names, which this print's file never had.
  5448. reused_3mf_from: int | None = None
  5449. if not downloaded_filename and not walk_transfer_failed:
  5450. reported_layers = raw_mqtt.get("total_layer_num")
  5451. earlier = await _archived_3mf_for_repeat(
  5452. db,
  5453. printer_id,
  5454. subtask_name,
  5455. filename,
  5456. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5457. )
  5458. if earlier is not None:
  5459. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5460. # Per printer: two printers reprinting the same job at once
  5461. # must not write one temp file (archive_print names the
  5462. # archive after original_filename, not this path).
  5463. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5464. try:
  5465. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5466. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5467. except OSError as e:
  5468. # A copy that fails leaves the print the fallback archive
  5469. # it would have had, not no archive at all.
  5470. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5471. else:
  5472. temp_path = reuse_path
  5473. downloaded_filename = reuse_name
  5474. reused_3mf_from = earlier.id
  5475. cache_3mf_download(printer_id, reuse_name, temp_path)
  5476. logger.info(
  5477. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5478. printer_id,
  5479. subtask_name,
  5480. filename,
  5481. earlier.id,
  5482. )
  5483. # Validate the downloaded 3MF actually matches the plate that's running
  5484. # (#1204): subtask_name lags across consecutive plates of the same model,
  5485. # so the first FTP candidate (built from subtask_name) can land on the
  5486. # previous plate's still-resident upload. Cross-check the slice_info
  5487. # plate index against the plate parsed from gcode_file (always fresh —
  5488. # it's the field whose change triggered this callback).
  5489. if downloaded_filename and temp_path:
  5490. expected_plate = parse_plate_id(filename)
  5491. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5492. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5493. logger.warning(
  5494. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5495. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5496. downloaded_filename,
  5497. actual_plate,
  5498. expected_plate,
  5499. subtask_name,
  5500. )
  5501. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5502. retry_succeeded = False
  5503. if corrected_subtask and corrected_subtask != subtask_name:
  5504. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5505. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5506. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5507. for remote_path in (
  5508. f"/{try_filename}",
  5509. f"/cache/{try_filename}",
  5510. f"/model/{try_filename}",
  5511. f"/data/{try_filename}",
  5512. f"/data/Metadata/{try_filename}",
  5513. ):
  5514. try:
  5515. if ftp_retry_enabled:
  5516. downloaded = await with_ftp_retry(
  5517. download_file_async,
  5518. printer.ip_address,
  5519. printer.access_code,
  5520. remote_path,
  5521. retry_temp_path,
  5522. timeout=ftp_timeout,
  5523. socket_timeout=ftp_timeout,
  5524. printer_model=printer.model,
  5525. max_retries=ftp_retry_count,
  5526. retry_delay=ftp_retry_delay,
  5527. operation_name=f"Re-download 3MF from {remote_path}",
  5528. cooloff_ip=printer.ip_address,
  5529. non_retry_exceptions=(FileNotOnPrinterError,),
  5530. )
  5531. else:
  5532. downloaded = await download_file_async(
  5533. printer.ip_address,
  5534. printer.access_code,
  5535. remote_path,
  5536. retry_temp_path,
  5537. timeout=ftp_timeout,
  5538. socket_timeout=ftp_timeout,
  5539. printer_model=printer.model,
  5540. )
  5541. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5542. logger.info(
  5543. "[CALLBACK] Re-download succeeded with corrected name %s "
  5544. "(plate %s) — replacing wrong file",
  5545. try_filename,
  5546. expected_plate,
  5547. )
  5548. try:
  5549. temp_path.unlink(missing_ok=True)
  5550. except OSError:
  5551. pass
  5552. temp_path = retry_temp_path
  5553. downloaded_filename = try_filename
  5554. subtask_name = corrected_subtask
  5555. cache_3mf_download(printer_id, try_filename, temp_path)
  5556. retry_succeeded = True
  5557. break
  5558. elif downloaded:
  5559. # Wrong plate again — discard and keep trying
  5560. try:
  5561. retry_temp_path.unlink(missing_ok=True)
  5562. except OSError:
  5563. pass
  5564. except FileNotOnPrinterError:
  5565. continue
  5566. except Exception as e:
  5567. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5568. if retry_succeeded:
  5569. break
  5570. # If the retry didn't find a matching file, drop the wrong 3MF
  5571. # so the no-3MF fallback below creates an archive whose name
  5572. # at least reflects the right plate.
  5573. if not retry_succeeded:
  5574. logger.warning(
  5575. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5576. expected_plate,
  5577. )
  5578. try:
  5579. temp_path.unlink(missing_ok=True)
  5580. except OSError:
  5581. pass
  5582. temp_path = None
  5583. downloaded_filename = None
  5584. # Whatever the sweep's transport did earlier, it is not why
  5585. # this archive ends up empty: a 3MF downloaded fine, it was
  5586. # just the wrong plate. Retrying would re-fetch that same
  5587. # contradicted file under the same stale names and hand it
  5588. # to _recover_fallback_archive, which checks that a
  5589. # candidate is a readable 3MF but not which plate it is --
  5590. # so the row would be filled in with another plate's
  5591. # filament and cost, the exact swap #2957 removed (#3063).
  5592. ftp_transfer_failed = False
  5593. # Disown the name for *lookups*: it has just been shown to
  5594. # fetch another plate's 3MF, and it keys `_active_prints`
  5595. # below, where the cover endpoint's own download of that
  5596. # same name would find this archive and fill it in with the
  5597. # file we are discarding here.
  5598. #
  5599. # Keep it for the *title*, which is a separate question.
  5600. # ``swap_plate_suffix`` returns None both for a name that
  5601. # carries no "- Plate N" / "_plate_N" suffix and for no
  5602. # name at all, and those are not the same situation: a name
  5603. # without a suffix holds no stale plate number to be wrong
  5604. # about. Blanking both uses at once dropped the project
  5605. # name too, and the row fell through to the gcode_file path
  5606. # titled "plate_1" though the real name was in hand.
  5607. # #1204's own premise is consecutive plates *of the same
  5608. # model*, so the project part is right either way (#3126).
  5609. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5610. subtask_name = corrected_subtask or ""
  5611. # Deleted while the 3MF was being fetched (that can take minutes): no
  5612. # archive, timelapse or tracking for a printer that will never report
  5613. # the print's end. forget_printer again: the download registered its
  5614. # 3MF cache entry after the delete cleared the id. (A delete committing
  5615. # while the archive is written is caught after its commit.)
  5616. if await _printer_gone(db, printer_id):
  5617. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5618. await forget_printer(printer_id)
  5619. return
  5620. if not downloaded_filename or not temp_path:
  5621. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5622. # Create a fallback archive without 3MF data so the print is still tracked
  5623. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5624. try:
  5625. from backend.app.models.archive import PrintArchive
  5626. # Why the card is empty. The two temporary causes outrank the
  5627. # storage verdict because they say the sweep never got a fair
  5628. # answer: a cool-off skipped it at the transport, and a failed
  5629. # transfer reached the printer but never finished. Either way
  5630. # the file is still on the card, so reporting where the printer
  5631. # files its jobs would describe a setting that is not the
  5632. # problem (#2957, #3063).
  5633. if blocked_by_ftps_cooloff:
  5634. no_3mf_reason = REASON_FTPS_COOLOFF
  5635. elif storage.reachable and ftp_transfer_failed:
  5636. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5637. else:
  5638. no_3mf_reason = storage.reason
  5639. # Derive print name from subtask_name or filename. The
  5640. # plate guard's disowned name comes second: it is a real name
  5641. # for a real print, and only the gcode_file path is left
  5642. # otherwise -- which titles the row "plate_1" (#3126).
  5643. print_name = subtask_name or display_name_after_plate_reject or filename
  5644. if print_name:
  5645. # Clean up the name (remove extensions, path parts)
  5646. print_name = print_name.split("/")[-1]
  5647. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5648. else:
  5649. print_name = "Unknown Print"
  5650. # Recover estimated print time from MQTT (best-effort for notifications)
  5651. fallback_print_time = None
  5652. mqtt_remaining = data.get("remaining_time")
  5653. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5654. fallback_print_time = int(mqtt_remaining)
  5655. if fallback_print_time is None:
  5656. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5657. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5658. fallback_print_time = int(mc_remaining * 60)
  5659. # Best-effort filament metadata from MQTT — see
  5660. # _extract_filament_data_from_mqtt. Without this the fallback
  5661. # archive's filament fields stayed NULL even though the AMS
  5662. # state at print start was sitting right there in `data`.
  5663. # The slicer's ams_mapping (when present) narrows the result
  5664. # to slots actually used by the print (#1533).
  5665. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5666. data, _get_start_ams_mapping(data, printer_id, None)
  5667. )
  5668. # Create minimal archive entry
  5669. fallback_archive = PrintArchive(
  5670. printer_id=printer_id,
  5671. filename=filename or f"{print_name}.3mf",
  5672. file_path="", # Empty - no 3MF file available
  5673. file_size=0,
  5674. print_name=print_name,
  5675. print_time_seconds=fallback_print_time,
  5676. status="printing",
  5677. started_at=detected_at,
  5678. subtask_id=subtask_id,
  5679. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5680. filament_type=mqtt_filament_meta.get("filament_type"),
  5681. filament_color=mqtt_filament_meta.get("filament_color"),
  5682. extra_data={
  5683. "no_3mf_available": True,
  5684. # Why the card is empty, when we know -- see above. The
  5685. # banner reads this to stop telling H2/P2 owners to
  5686. # switch on a setting that is already on and would not
  5687. # have helped (#2780).
  5688. "no_3mf_reason": no_3mf_reason,
  5689. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5690. "_print_data": data,
  5691. },
  5692. )
  5693. db.add(fallback_archive)
  5694. try:
  5695. await db.commit()
  5696. except IntegrityError:
  5697. # Not "Failed to create fallback archive" below, and no
  5698. # start notification for a printer that is gone.
  5699. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5700. return
  5701. raise
  5702. await db.refresh(fallback_archive)
  5703. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5704. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5705. return
  5706. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5707. # Track as active print
  5708. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5709. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5710. # Record starting energy if smart plug available (#941: persisted column)
  5711. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5712. # Send WebSocket notification
  5713. await ws_manager.send_archive_created(
  5714. {
  5715. "id": fallback_archive.id,
  5716. "printer_id": fallback_archive.printer_id,
  5717. "filename": fallback_archive.filename,
  5718. "print_name": fallback_archive.print_name,
  5719. "status": fallback_archive.status,
  5720. }
  5721. )
  5722. # MQTT relay - publish archive created
  5723. try:
  5724. await mqtt_relay.on_archive_created(
  5725. archive_id=fallback_archive.id,
  5726. print_name=fallback_archive.print_name,
  5727. printer_name=printer.name,
  5728. status=fallback_archive.status,
  5729. )
  5730. except Exception:
  5731. pass # Don't fail if MQTT fails
  5732. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5733. try:
  5734. await _store_spoolman_print_data(
  5735. printer_id,
  5736. fallback_archive.id,
  5737. fallback_archive.file_path,
  5738. db,
  5739. printer_manager,
  5740. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5741. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5742. )
  5743. except Exception as e:
  5744. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5745. # Both temporary give-ups are worth coming back for, and for
  5746. # the same reason: the file is on the printer and the last look
  5747. # failed at the transport rather than finding nothing. One waits
  5748. # out the handshake block (#2957), the other waits for the
  5749. # printer to stop being busy (#3063). Deliberately not scheduled
  5750. # for a storage verdict: a file on internal eMMC will not appear
  5751. # at any FTPS path however long we wait, and retrying it is
  5752. # exactly the sweep #2780 removed.
  5753. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5754. # `possible_names`, not the raw MQTT strings: it is the exact
  5755. # list this flow just tried, already stripped of any path
  5756. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5757. # some firmware) and deduped.
  5758. _schedule_fallback_3mf_retry(
  5759. printer_id=printer_id,
  5760. archive_id=fallback_archive.id,
  5761. filenames=list(possible_names),
  5762. reason=no_3mf_reason,
  5763. )
  5764. # Send notification without archive data (file not found)
  5765. if not notification_sent:
  5766. await _send_print_start_notification(printer_id, data, logger=logger)
  5767. # The same baseline the other two on_print_start branches take
  5768. # (#2704), and last for the same reason they are: it lists the
  5769. # printer's timelapse directory, so a slow card must not delay
  5770. # the _active_prints registration, the energy reading, the
  5771. # archive-created event or the start notification above it.
  5772. #
  5773. # This branch never took one, so every no-3MF archive reached
  5774. # completion with no baseline in memory and none on the row, and
  5775. # the completion scan fell into its "snapshot now" fallback --
  5776. # which runs after the printer has written the video, so the new
  5777. # file landed inside the baseline and no diff ever matched
  5778. # (#2957 follow-up).
  5779. #
  5780. # Skipped when the FTPS cool-off is what produced this fallback:
  5781. # the listing needs the same connection that just failed, so it
  5782. # could only record that the card was unreadable. The scan
  5783. # handles that case by refusing to choose between candidates.
  5784. if not blocked_by_ftps_cooloff:
  5785. await _capture_timelapse_baseline_at_start(
  5786. printer, printer_id, logger, archive_id=fallback_archive.id
  5787. )
  5788. await _forget_if_printer_gone(printer_id)
  5789. return
  5790. except Exception as e:
  5791. logger.error("Failed to create fallback archive: %s", e)
  5792. # Send notification without archive data (file not found)
  5793. if not notification_sent:
  5794. await _send_print_start_notification(printer_id, data, logger=logger)
  5795. return
  5796. try:
  5797. # Archive the file with status "printing"
  5798. service = ArchiveService(db)
  5799. try:
  5800. archive = await service.archive_print(
  5801. printer_id=printer_id,
  5802. source_file=temp_path,
  5803. print_data={
  5804. **data,
  5805. "status": "printing",
  5806. # Where the 3MF came from when the printer had none to
  5807. # give (#3307), for whoever reads this archive later.
  5808. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5809. },
  5810. subtask_id=subtask_id,
  5811. started_at=detected_at,
  5812. # The reused copy's temp name carries the printer id; a
  5813. # download's is the file's own name, as before.
  5814. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5815. )
  5816. except IntegrityError:
  5817. # archive_print removed the folder it had copied the 3MF into.
  5818. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5819. return
  5820. raise
  5821. if archive:
  5822. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5823. # Set on the row rather than passed to archive_print, which also
  5824. # serves the queue dispatcher — there the queue item decides.
  5825. # Guarded because this branch has no ``except``: an unhandled
  5826. # write error would take the _active_prints registration, the
  5827. # start notification, the energy reading and the timelapse
  5828. # baseline below it with it, and a missing prompt is by far the
  5829. # cheaper failure.
  5830. archive_id = archive.id
  5831. try:
  5832. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5833. archive.confirm_requested = True
  5834. await db.commit()
  5835. except Exception as e:
  5836. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5837. # The rollback expires every loaded object, and on an async
  5838. # session reading one afterwards raises instead of
  5839. # reloading, so the two this branch goes on to use are
  5840. # fetched again. The archive itself was committed by
  5841. # archive_print; only the flag is lost.
  5842. try:
  5843. await db.rollback()
  5844. archive = await db.get(PrintArchive, archive_id)
  5845. printer = await db.get(Printer, printer_id)
  5846. except Exception as reload_error:
  5847. logger.warning(
  5848. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5849. )
  5850. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5851. return
  5852. # Track this active print (use both original filename and downloaded filename)
  5853. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5854. await _open_run_for(archive_id, printer_id, subtask_id)
  5855. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5856. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5857. # Record starting energy from smart plug if available (#941: persisted column)
  5858. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5859. await ws_manager.send_archive_created(
  5860. {
  5861. "id": archive.id,
  5862. "printer_id": archive.printer_id,
  5863. "filename": archive.filename,
  5864. "print_name": archive.print_name,
  5865. "status": archive.status,
  5866. }
  5867. )
  5868. # MQTT relay - publish archive created
  5869. try:
  5870. await mqtt_relay.on_archive_created(
  5871. archive_id=archive.id,
  5872. print_name=archive.print_name,
  5873. printer_name=printer.name,
  5874. status=archive.status,
  5875. )
  5876. except Exception:
  5877. pass # Don't fail if MQTT fails
  5878. # Send notification with archive data (new archive created)
  5879. if not notification_sent:
  5880. archive_data = {
  5881. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5882. "created_by_id": archive.created_by_id,
  5883. }
  5884. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5885. # Extract printable objects for skip object functionality
  5886. try:
  5887. from backend.app.services.archive import extract_printable_objects_from_3mf
  5888. client = printer_manager.get_client(printer_id)
  5889. if client:
  5890. with open(temp_path, "rb") as f:
  5891. threemf_data = f.read()
  5892. # Extract with positions for UI overlay, scoped to the
  5893. # plate that is printing — an all-plates 3MF carries
  5894. # every plate's objects (#2522).
  5895. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5896. threemf_data,
  5897. plate_number=resolve_plate_id(client.state),
  5898. include_positions=True,
  5899. )
  5900. if printable_objects:
  5901. # Store objects in printer state
  5902. client.state.printable_objects = printable_objects
  5903. client.state.printable_objects_bbox_all = bbox_all
  5904. client.state.skipped_objects = [] # Reset skipped objects for new print
  5905. logger.info(
  5906. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5907. )
  5908. except Exception as e:
  5909. logger.debug("Failed to extract printable objects: %s", e)
  5910. # From the archived copy: the downloaded one may be removed
  5911. # below while the pauses are still being read.
  5912. if archive is not None and archive.file_path:
  5913. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5914. # Store Spoolman tracking data for per-filament usage reporting
  5915. try:
  5916. await _store_spoolman_print_data(
  5917. printer_id,
  5918. archive.id,
  5919. archive.file_path,
  5920. db,
  5921. printer_manager,
  5922. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5923. plate_id=_get_start_plate_id(printer_id, archive_id),
  5924. )
  5925. except Exception as e:
  5926. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5927. # Price the print from its spools now rather than only at completion (#3261)
  5928. _schedule_archive_cost_estimate(
  5929. printer_id,
  5930. archive.id,
  5931. printer_manager,
  5932. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5933. plate_id=_get_start_plate_id(printer_id, archive_id),
  5934. session_factory=async_session,
  5935. )
  5936. # Capture timelapse file baseline for snapshot-diff on completion
  5937. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5938. await _forget_if_printer_gone(printer_id)
  5939. finally:
  5940. # Keep temp_path around until print completes so the cover endpoint
  5941. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5942. # the file. If the cache entry was evicted early (file vanished),
  5943. # clean up any stragglers here to avoid leaking disk on retries.
  5944. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5945. if temp_path and temp_path.exists() and cached_now != temp_path:
  5946. temp_path.unlink()
  5947. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5948. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5949. # A baseline that could not be read at print start is read again on this
  5950. # schedule while the print runs (#3412). The printer writes the video only once
  5951. # the print has ended, so a reading taken mid-print is as good as one taken at
  5952. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5953. # which is what usually makes the card unreadable, so the first reading after
  5954. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5955. # no connection is opened. The cap bounds a print that never reports an end.
  5956. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5957. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5958. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5959. # tests can shrink them without waiting out real delays.
  5960. #
  5961. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5962. # looking. Across 247 support bundles the attempt that found the video was #1
  5963. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5964. # decaying one, which is the signature of a budget that expires while files are
  5965. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5966. # prints make big videos and the printer writes them after the print ends, so
  5967. # the poll now runs for minutes and costs one FTP LIST per round.
  5968. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5969. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5970. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5971. def _timelapse_scan_max_attempts() -> int:
  5972. """Round cap for the poll, derived from the wall-clock budget.
  5973. The deadline alone is not a sufficient bound: it assumes each round really
  5974. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5975. and an FTP list that fails immediately would otherwise spin against the
  5976. printer at full speed for the whole window. Whichever bound is reached
  5977. first ends the poll.
  5978. """
  5979. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5980. # A zero interval makes the wall-clock budget meaningless; fall back to
  5981. # the round count the production interval would have given.
  5982. return 32
  5983. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5984. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5985. """The video names on *printer*'s card, and whether the card was read.
  5986. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5987. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5988. listing timed out, is indistinguishable from one holding no videos.
  5989. Everywhere that only wants to know "is there a video yet" the difference
  5990. does not matter -- both mean "not yet, retry".
  5991. It matters where an empty listing is recorded as a *baseline*. Recording
  5992. "the card held nothing" for a card that was never read means every video on
  5993. it counts as new, and the completion scan then attaches a stale video to
  5994. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5995. empty listing is asked again here in a way that tells the two apart: the
  5996. card counts as read only when every directory walked answered, with a
  5997. listing or with "no such directory". One that failed may be the one
  5998. holding the videos.
  5999. """
  6000. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  6001. files, _ = await _list_timelapse_videos(printer)
  6002. if files:
  6003. return {f.get("name", "") for f in files}, True
  6004. ip_address = getattr(printer, "ip_address", None)
  6005. printer_id = getattr(printer, "id", None)
  6006. if not ip_address:
  6007. return set(), True
  6008. # No card in the slot: nothing to read, and nothing a video could land on.
  6009. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6010. return set(), True
  6011. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6012. if ftps_handshake_blocked(ip_address):
  6013. # Below any path: every remaining one would fail the same way.
  6014. return set(), False
  6015. listing = await list_files_result_async(
  6016. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6017. )
  6018. if not (listing.available or listing.missing):
  6019. return set(), False
  6020. videos = [
  6021. f
  6022. for f in listing.files
  6023. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6024. ]
  6025. if videos:
  6026. return {f.get("name", "") for f in videos}, True
  6027. return set(), True
  6028. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6029. """List video files from printer's timelapse directory.
  6030. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6031. Returns (video_files, found_path) where video_files is a list of file dicts
  6032. and found_path is the directory where they were found, or ([], None).
  6033. An empty return does not distinguish "no videos" from "could not read the
  6034. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6035. callers use instead.
  6036. """
  6037. from backend.app.services.bambu_ftp import list_files_async
  6038. logger = logging.getLogger(__name__)
  6039. # No card in the slot means no /timelapse to walk — four connections that
  6040. # can only fail, on a path whose failures are swallowed and so would go on
  6041. # costing time silently forever (#2780).
  6042. #
  6043. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6044. # inside the loop's own try/except, so a caller that passed something
  6045. # unexpected used to get an empty listing rather than an exception. Keep
  6046. # that, instead of making this gate the first thing that can raise here.
  6047. printer_id = getattr(printer, "id", None)
  6048. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6049. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6050. return [], None
  6051. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6052. try:
  6053. found_files = await list_files_async(
  6054. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6055. )
  6056. if found_files:
  6057. video_files = [
  6058. f
  6059. for f in found_files
  6060. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6061. ]
  6062. if video_files:
  6063. return video_files, timelapse_path
  6064. except Exception as e:
  6065. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6066. continue
  6067. return [], None
  6068. async def _capture_timelapse_baseline_at_start(
  6069. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6070. ) -> None:
  6071. """Snapshot the printer's timelapse directory at print start so the
  6072. completion-time scan can pick the new file by set-difference.
  6073. Must be called from every on_print_start path that proceeds to a real
  6074. print — both the new-archive branch and the expected-archive branch (which
  6075. queue / VP-dispatched prints take). Without a baseline,
  6076. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6077. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6078. so the new file ends up in the "baseline" set and no diff ever matches.
  6079. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6080. unreliable — the snapshot-diff approach sidesteps that entirely.
  6081. When ``archive_id`` is known the baseline is also written to the archive
  6082. row, so it survives a restart and the manual "Scan for Timelapse" button
  6083. can run the same diff instead of falling back to clock-based matching
  6084. (#2704). Only baselines taken at print start are persisted — one taken at
  6085. completion already contains the new video and would poison a later scan.
  6086. """
  6087. names: set[str] | None = None
  6088. unread = False
  6089. _timelapse_baselines_unread.discard(printer_id)
  6090. try:
  6091. names, read = await _read_timelapse_baseline(printer)
  6092. unread = not read
  6093. _timelapse_baselines[printer_id] = names
  6094. if unread:
  6095. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6096. # off a card we could not read is not evidence, but it is still the
  6097. # right *default*: Bambuddy deletes each video from the printer once
  6098. # it is attached, so the usual card holds exactly one video at
  6099. # completion and an empty baseline resolves it. Persisting NULL
  6100. # instead would send completion to take its own snapshot, by which
  6101. # point this print's video is on the card and would be swallowed by
  6102. # it. The mark keeps the scan from choosing between several videos
  6103. # (#3412), and the card is read again while the print runs.
  6104. _timelapse_baselines_unread.add(printer_id)
  6105. logger.warning(
  6106. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6107. "treating it as empty for now and reading it again during the print",
  6108. printer_id,
  6109. )
  6110. logger.info(
  6111. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6112. len(names),
  6113. printer_id,
  6114. )
  6115. except Exception as e:
  6116. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6117. run_started_at: datetime | None = None
  6118. run_id: int | None = None
  6119. if archive_id is not None:
  6120. try:
  6121. async with async_session() as db:
  6122. from backend.app.models.archive import PrintArchive
  6123. from backend.app.services.print_log import open_run_on_printer
  6124. archive = await db.get(PrintArchive, archive_id)
  6125. if archive is not None:
  6126. # Written even when the listing failed, and then as NULL. A
  6127. # reprint reuses the archive row, so leaving the previous
  6128. # run's baseline in place would have the scan diff this print
  6129. # against the state of the printer before the *last* one —
  6130. # and a stale baseline reads as authoritative, where NULL
  6131. # correctly falls back to a fresh snapshot.
  6132. baseline = sorted(names) if names is not None else None
  6133. archive.timelapse_baseline = baseline
  6134. archive.timelapse_baseline_unread = unread
  6135. run_started_at = archive.started_at
  6136. # And on the run this print opened, whose scan reads it:
  6137. # the archive's is its latest start's, which another plate
  6138. # of it on another printer can take over.
  6139. run = await open_run_on_printer(db, printer_id)
  6140. if run is not None and run.archive_id == archive_id:
  6141. run.timelapse_baseline = baseline
  6142. run.timelapse_baseline_unread = unread
  6143. run_id = run.id
  6144. await db.commit()
  6145. except Exception as e:
  6146. # In-memory baseline still covers the normal completion path.
  6147. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6148. if unread and names is not None:
  6149. spawn_background_task(
  6150. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6151. name=f"reread-timelapse-baseline-{printer_id}",
  6152. )
  6153. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6154. # levelling) counts as much as the print itself.
  6155. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6156. def _schedule_timelapse_scan(
  6157. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6158. ) -> None:
  6159. """Start the completion scan with the print-start baseline: the names, and
  6160. whether they were taken off a card that could not be read. Taking them
  6161. ends any re-read still running for it. ``run_id`` is the print that
  6162. ended, whose video it looks for."""
  6163. unread = printer_id in _timelapse_baselines_unread
  6164. _timelapse_baselines_unread.discard(printer_id)
  6165. baseline = _timelapse_baselines.pop(printer_id, None)
  6166. from backend.app.services import archive_work
  6167. # Held while it looks: it finds its print by the archive's id, which a
  6168. # merge would move away (archive redesign P2).
  6169. spawn_background_task(
  6170. archive_work.held_while(
  6171. archive_id,
  6172. _scan_for_timelapse_with_retries(
  6173. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6174. ),
  6175. ),
  6176. name=f"scan-timelapse-{archive_id}",
  6177. )
  6178. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6179. """Whether to read an unread baseline again now: True to read, None to
  6180. skip this round, False once it is over -- the print it was taken for is
  6181. no longer the one on the printer, has stopped printing, or the baseline
  6182. has been read.
  6183. ``names`` is the very set object recorded at print start: completion pops
  6184. it and the next print records a new one, so identity marks the run. A
  6185. printer that is momentarily disconnected says nothing about its print, so
  6186. that only skips the round.
  6187. """
  6188. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6189. return False
  6190. state = printer_manager.get_status(printer_id)
  6191. if state is None or not state.connected:
  6192. return None
  6193. return state.state in _BASELINE_REREAD_STATES
  6194. async def _reread_unread_timelapse_baseline(
  6195. printer_id: int,
  6196. names: set[str],
  6197. archive_id: int | None,
  6198. run_started_at: datetime | None,
  6199. run_id: int | None = None,
  6200. ) -> None:
  6201. """Read again a print-start baseline the card could not give (#3412).
  6202. The printer writes the video only once the print has ended, so the card
  6203. read at any point during the print holds exactly what it held at the
  6204. start. Each round stops once the print is no longer the one the baseline
  6205. was taken for or has stopped printing, and checks that again after the
  6206. listing returns, before anything is recorded.
  6207. """
  6208. from backend.app.models.archive import PrintArchive
  6209. from backend.app.models.printer import Printer
  6210. from backend.app.services.print_log import run_of
  6211. logger = logging.getLogger(__name__)
  6212. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6213. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6214. now = _unread_baseline_round(printer_id, names)
  6215. if now is False:
  6216. return
  6217. if now is None:
  6218. continue
  6219. try:
  6220. async with async_session() as db:
  6221. printer = await db.get(Printer, printer_id)
  6222. if printer is None:
  6223. return
  6224. fresh, read = await _read_timelapse_baseline(printer)
  6225. except Exception as e:
  6226. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6227. continue
  6228. if not read:
  6229. continue
  6230. now = _unread_baseline_round(printer_id, names)
  6231. if now is False:
  6232. return
  6233. if now is None:
  6234. # The printer dropped off while the listing was out, so nothing
  6235. # says it did not end meanwhile: keep the reading for a round that
  6236. # can vouch for it.
  6237. continue
  6238. names.update(fresh)
  6239. _timelapse_baselines_unread.discard(printer_id)
  6240. logger.info(
  6241. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6242. printer_id,
  6243. len(fresh),
  6244. )
  6245. if archive_id is None:
  6246. return
  6247. try:
  6248. async with async_session() as db:
  6249. archive = await db.get(PrintArchive, archive_id)
  6250. # Only the run it was taken for: by now the row can belong to a
  6251. # reprint, whose baseline is its own.
  6252. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6253. archive.timelapse_baseline = sorted(names)
  6254. archive.timelapse_baseline_unread = False
  6255. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6256. if run is not None and run.timelapse_baseline_unread:
  6257. run.timelapse_baseline = sorted(names)
  6258. run.timelapse_baseline_unread = False
  6259. await db.commit()
  6260. except Exception as e:
  6261. # The in-memory baseline is read now, which covers completion
  6262. # unless Bambuddy restarts first.
  6263. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6264. return
  6265. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6266. """Whether the print a timelapse is for still has none: its run, by id,
  6267. exists without a video and no later print took over (``superseded``).
  6268. Without a run, the archive is still on that print's start (a newer run's
  6269. video is its own) and has none."""
  6270. from backend.app.services.print_log import run_of, superseded
  6271. if run_id is not None:
  6272. run = await run_of(db, archive.id, run_id)
  6273. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6274. return archive.timelapse_path is None and archive.started_at == run_started_at
  6275. async def _scan_for_timelapse_with_retries(
  6276. archive_id: int,
  6277. baseline_names: set[str] | None = None,
  6278. *,
  6279. plate_id: int | None = None,
  6280. baseline_unread: bool = False,
  6281. run_id: int | None = None,
  6282. ):
  6283. """Poll the printer for this print's timelapse and attach it.
  6284. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6285. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6286. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6287. (#2704). Comparing the current listing against the set of filenames that
  6288. existed when the print started needs no clock at all, because the printer
  6289. writes the video only once the print has ended.
  6290. Baseline precedence: the caller's in-memory set, then the one persisted on
  6291. the archive at print start, then a snapshot taken now. The last of those is
  6292. a poor substitute — by completion the new video may already be on the card,
  6293. in which case it lands in the "baseline" and no diff can ever match — but it
  6294. is all that is available for a print that began before Bambuddy started.
  6295. On success the video is deleted from the printer, which keeps ``/timelapse``
  6296. down to the unclaimed files and makes the next diff unambiguous.
  6297. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6298. could not be read; a stored one carries the same mark on the archive.
  6299. ``run_id`` is the print that ended (archive redesign): the video is that
  6300. run's, the stored baseline is the run's own, and the poll ends once the
  6301. run has a video or is gone. Without it (no run was written), the run is
  6302. whichever the archive is on when the scan starts.
  6303. """
  6304. from backend.app.services.print_log import run_of
  6305. logger = logging.getLogger(__name__)
  6306. # Cleared when the baseline was taken off a card we could not read, so the
  6307. # attach step refuses to choose between several candidates (#2957, #3412).
  6308. baseline_trusted = True
  6309. # --- Phase 1: establish the baseline -------------------------------------
  6310. try:
  6311. async with async_session() as db:
  6312. from backend.app.models.printer import Printer
  6313. service = ArchiveService(db)
  6314. archive = await service.get_archive(archive_id)
  6315. if not archive:
  6316. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6317. return
  6318. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6319. if run_id is not None and run is None:
  6320. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6321. return
  6322. if run.timelapse_path if run is not None else archive.timelapse_path:
  6323. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6324. return
  6325. # The printer the print ran on: plates of one archive can print on
  6326. # two printers, and the archive's is the one that started last.
  6327. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6328. if not scan_printer_id:
  6329. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6330. return
  6331. # The run this scan is for. The archive row passes to a newer run
  6332. # when it prints again (the next plate, a reprint), and that run's
  6333. # video is its own.
  6334. run_started_at = run.started_at if run is not None else archive.started_at
  6335. # The baseline stored for it: the run's own, else the archive's
  6336. # while that is still this run's start's.
  6337. stored_baseline, stored_unread = None, False
  6338. if run is not None and run.timelapse_baseline is not None:
  6339. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6340. elif archive.started_at == run_started_at:
  6341. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6342. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6343. # The card was read at print start, and the in-memory copy is
  6344. # one Bambuddy took after a restart off a card it could not
  6345. # read: the stored one is this run's and is evidence.
  6346. baseline_names = set(stored_baseline)
  6347. logger.info(
  6348. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6349. len(baseline_names),
  6350. archive_id,
  6351. )
  6352. elif baseline_names is not None:
  6353. baseline_trusted = not baseline_unread
  6354. logger.info(
  6355. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6356. len(baseline_names),
  6357. archive_id,
  6358. )
  6359. elif stored_baseline is not None:
  6360. # Persisted at print start — survives a restart mid-print.
  6361. baseline_names = set(stored_baseline)
  6362. baseline_trusted = not stored_unread
  6363. logger.info(
  6364. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6365. len(baseline_names),
  6366. archive_id,
  6367. )
  6368. else:
  6369. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6370. printer = result.scalar_one_or_none()
  6371. if not printer:
  6372. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6373. return
  6374. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6375. if not baseline_trusted:
  6376. # The card is unreadable at the one moment a baseline has to
  6377. # be taken, so the empty listing means "we never looked",
  6378. # not "these are all new". Carry on with it anyway — the
  6379. # usual card holds exactly one video, which resolves
  6380. # correctly — but stop the poll from *choosing* between
  6381. # several, which is how a stale video got attached to this
  6382. # print and then deleted off the printer (#2957 follow-up).
  6383. logger.warning(
  6384. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6385. "read. A single new video still resolves; several will not be guessed between — "
  6386. "use Scan for Timelapse to pick one by hand",
  6387. archive_id,
  6388. scan_printer_id,
  6389. )
  6390. logger.info(
  6391. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6392. len(baseline_names),
  6393. archive_id,
  6394. )
  6395. except Exception as e:
  6396. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6397. return
  6398. # --- Phase 2: poll for a file that was not there when the print began -----
  6399. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6400. max_attempts = _timelapse_scan_max_attempts()
  6401. seen_names: set[str] = set()
  6402. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6403. attempt = 0
  6404. while True:
  6405. await asyncio.sleep(delay)
  6406. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6407. attempt += 1
  6408. try:
  6409. from backend.app.models.printer import Printer
  6410. # Read phase: fetch archive + printer in a short session and release
  6411. # the pooled connection BEFORE the FTP list/download below. Holding it
  6412. # across the FTP round-trips left one connection idle-in-transaction per
  6413. # in-flight scan (issue #2572).
  6414. async with async_session() as db:
  6415. from backend.app.services.print_log import claimed_timelapse_stems
  6416. service = ArchiveService(db)
  6417. archive = await service.get_archive(archive_id)
  6418. if not archive:
  6419. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6420. return
  6421. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6422. logger.info(
  6423. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6424. archive_id,
  6425. )
  6426. return
  6427. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6428. printer = result.scalar_one_or_none()
  6429. if not printer:
  6430. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6431. return
  6432. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6433. # I/O phase (no DB connection held): FTP list + download.
  6434. video_files, found_path = await _list_timelapse_videos(printer)
  6435. # The poll can run for dozens of rounds, so only narrate a round
  6436. # that saw something change. Repeating the whole listing every 30 s
  6437. # would bury the one interesting line in the support bundle.
  6438. names_now = {f.get("name", "") for f in video_files}
  6439. changed = attempt == 1 or names_now != seen_names
  6440. seen_names = names_now
  6441. speak = logger.info if changed else logger.debug
  6442. if video_files:
  6443. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6444. if changed:
  6445. for f in video_files[:5]:
  6446. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6447. attached = await _attach_first_unclaimed_timelapse(
  6448. archive_id,
  6449. printer,
  6450. video_files,
  6451. baseline_names,
  6452. claimed,
  6453. attempt,
  6454. logger,
  6455. quiet=not changed,
  6456. require_unambiguous=not baseline_trusted,
  6457. plate_id=plate_id,
  6458. run_started_at=run_started_at,
  6459. run_id=run_id,
  6460. )
  6461. if attached:
  6462. return
  6463. else:
  6464. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6465. except Exception as e:
  6466. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6467. if attempt >= max_attempts or time.monotonic() >= deadline:
  6468. break
  6469. # No name-match fallback: it compared the print name against the filename,
  6470. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6471. # bundles it fired 159 times and matched zero times, so all it added was a
  6472. # misleading log line before giving up.
  6473. logger.warning(
  6474. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6475. archive_id,
  6476. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6477. )
  6478. async def _attach_layer_timelapse(
  6479. archive_id: int,
  6480. timelapse_path: Path,
  6481. plate_id: int | None,
  6482. run_started_at: datetime | None,
  6483. run_id: int | None = None,
  6484. ) -> None:
  6485. """Attach the external camera's stitched timelapse to the archive.
  6486. The camera's video is the one the user set up in Bambuddy, so it wins
  6487. over the printer's own when both are on: it replaces the printer's video
  6488. (usually there first; stitching takes minutes) and that file is deleted,
  6489. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6490. the run the frames were taken for: when the archive is printing again by
  6491. the time the stitch is done, the video is not the new run's and is
  6492. dropped. The stitched file is a temporary either way.
  6493. ``run_id`` is the print that ended (archive redesign): the video is that
  6494. run's and replaces that run's printer video; the poll by start above is
  6495. for a print without a run.
  6496. """
  6497. from backend.app.services.print_log import run_of, superseded
  6498. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6499. logger = logging.getLogger(__name__)
  6500. try:
  6501. async with async_session() as db:
  6502. service = ArchiveService(db)
  6503. archive = await service.get_archive(archive_id)
  6504. if archive is None:
  6505. return
  6506. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6507. if run_id is not None and run is None:
  6508. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6509. return
  6510. if run is not None and await superseded(db, run):
  6511. logger.info(
  6512. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6513. run_id,
  6514. archive_id,
  6515. )
  6516. return
  6517. if run is None and archive.started_at != run_started_at:
  6518. logger.info(
  6519. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6520. )
  6521. return
  6522. holder = run if run is not None else archive
  6523. replaced = holder.timelapse_path
  6524. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6525. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6526. if not await service.attach_timelapse(
  6527. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6528. ):
  6529. return
  6530. attached = holder.timelapse_path
  6531. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6532. if replaced and replaced != attached:
  6533. try:
  6534. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6535. except PathTraversalError:
  6536. return
  6537. await asyncio.to_thread(old.unlink, missing_ok=True)
  6538. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6539. finally:
  6540. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6541. # ``run_started_at`` not given: attach whichever run the archive is on.
  6542. _ANY_RUN = object()
  6543. async def _attach_first_unclaimed_timelapse(
  6544. archive_id: int,
  6545. printer,
  6546. video_files: list[dict],
  6547. baseline_names: set[str],
  6548. claimed: set[str],
  6549. attempt: int,
  6550. logger: logging.Logger,
  6551. *,
  6552. quiet: bool = False,
  6553. require_unambiguous: bool = False,
  6554. plate_id: int | None = None,
  6555. run_started_at: datetime | None | object = _ANY_RUN,
  6556. run_id: int | None = None,
  6557. ) -> bool:
  6558. """Download and attach the one video that belongs to this print.
  6559. A candidate is any file absent from the print-start baseline. More than one
  6560. can qualify when a previous print's video landed late, after this print's
  6561. baseline was taken — those are filtered out by name, because they are
  6562. already attached to another archive. Sorting the candidates instead would
  6563. mean sorting on mtime or on the filename timestamp, both of which come from
  6564. the printer's unsynced clock.
  6565. Returns True once a video is attached. The printer's copy is deleted only
  6566. after the attach succeeds on bytes whose length matched the listing.
  6567. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6568. already seen this exact listing — the poll runs for many rounds and only the
  6569. rounds where something changed are worth an INFO line.
  6570. """
  6571. from backend.app.services.bambu_ftp import (
  6572. DownloadDeadlineExceeded,
  6573. delete_archived_timelapse,
  6574. download_file_bytes_async,
  6575. remote_file_settled,
  6576. )
  6577. speak = logger.debug if quiet else logger.info
  6578. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6579. if not new_files:
  6580. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6581. return False
  6582. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6583. if not candidates:
  6584. speak(
  6585. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6586. attempt,
  6587. len(new_files),
  6588. )
  6589. return False
  6590. if len(candidates) > 1:
  6591. if require_unambiguous:
  6592. # The baseline is not evidence -- it was taken off a card that could
  6593. # not be read -- so "new since the baseline" does not narrow these
  6594. # down at all. Taking the first would attach an arbitrary video to
  6595. # this print and then delete it from the printer.
  6596. logger.warning(
  6597. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6598. "leaving all of them on the printer for manual selection",
  6599. attempt,
  6600. len(candidates),
  6601. ", ".join(str(f.get("name")) for f in candidates),
  6602. )
  6603. return False
  6604. logger.warning(
  6605. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6606. "the rest stay on the printer for manual selection",
  6607. attempt,
  6608. len(candidates),
  6609. ", ".join(str(f.get("name")) for f in candidates),
  6610. )
  6611. target = candidates[0]
  6612. file_name = str(target.get("name") or "") # every listed entry has one
  6613. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6614. logger.info(
  6615. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6616. attempt,
  6617. file_name,
  6618. archive_id,
  6619. )
  6620. # The listing always carries a size (`list_files` skips entries it can't
  6621. # parse), but read it explicitly: the delete below is destructive and must
  6622. # depend on a size we actually had, not on one we hoped was there.
  6623. expected_size = target.get("size")
  6624. try:
  6625. timelapse_data = await download_file_bytes_async(
  6626. printer.ip_address,
  6627. printer.access_code,
  6628. remote_path,
  6629. printer_model=printer.model,
  6630. expected_size=expected_size,
  6631. )
  6632. except DownloadDeadlineExceeded:
  6633. # Too slow for its size this round; the printer keeps its copy.
  6634. timelapse_data = None
  6635. if not timelapse_data:
  6636. # Short or failed transfer. The printer keeps its copy, so the next
  6637. # round can try again — which is exactly why the delete below is
  6638. # gated on a verified download.
  6639. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6640. return False
  6641. # The length check above proves we got what the listing said, not that the
  6642. # printer had finished writing. A video still being written can be listed
  6643. # short, served short, and pass — so confirm it has stopped growing before
  6644. # committing to it and deleting the original (#2704).
  6645. if not await remote_file_settled(
  6646. printer.ip_address,
  6647. printer.access_code,
  6648. remote_path,
  6649. len(timelapse_data),
  6650. printer_model=printer.model,
  6651. ):
  6652. return False
  6653. # Write phase: attach in a fresh short-lived session. The download took a
  6654. # while: by now the archive may have its video, or be printing again for a
  6655. # newer run, whose video this is not. Then nothing is attached or deleted,
  6656. # and the poll ends (True).
  6657. async with async_session() as db:
  6658. service = ArchiveService(db)
  6659. if run_id is not None or run_started_at is not _ANY_RUN:
  6660. current = await service.get_archive(archive_id)
  6661. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6662. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6663. logger.info(
  6664. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6665. "%s stays on the printer",
  6666. archive_id,
  6667. file_name,
  6668. )
  6669. return True
  6670. success = await service.attach_timelapse(
  6671. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6672. )
  6673. if not success:
  6674. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6675. return False
  6676. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6677. await delete_archived_timelapse(
  6678. printer.ip_address,
  6679. printer.access_code,
  6680. remote_path,
  6681. verified=expected_size is not None,
  6682. printer_model=printer.model,
  6683. printer_name=printer.name,
  6684. )
  6685. return True
  6686. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6687. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6688. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6689. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6690. # How long the *background* upgrade keeps waiting after the notification has
  6691. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6692. # printer can't hold up the print-complete notification; this one exists so the
  6693. # archive still ends up with the better frame afterwards.
  6694. #
  6695. # Measured across 261 attaches in the support bundles, the video lands a median
  6696. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6697. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6698. # was 546s. Every other model was inside 26s. The long budget is therefore
  6699. # almost entirely for P1-series users; on everything else the short wait already
  6700. # wins and this task never runs.
  6701. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6702. async def _capture_finish_photo_from_timelapse(
  6703. archive_id: int,
  6704. archive_dir: Path,
  6705. timeout: float | None = None,
  6706. rotation: int = 0,
  6707. run_id: int | None = None,
  6708. ) -> tuple[str | None, bool]:
  6709. """Wait for the per-print timelapse to land on the archive and extract its
  6710. last frame as the finish photo (#1397).
  6711. Bambu firmware stops timelapse recording after the toolhead parks but
  6712. before the bed-drop end-gcode runs, so the last frame frames the finished
  6713. print correctly. A live camera grab at gcode_state=FINISH captures the
  6714. bed already lowered.
  6715. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6716. ``archive.timelapse_path`` when the file lands. This function polls for
  6717. that field.
  6718. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6719. the wait ran out with no video on the archive yet — i.e. the video may
  6720. still be coming and a later attempt could succeed. It is False when the
  6721. video landed (whether or not extraction worked), because in that case
  6722. waiting longer changes nothing. The caller uses that to decide between
  6723. falling back permanently and scheduling a background upgrade.
  6724. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6725. still (#2708) so this source agrees with every other finish-photo source.
  6726. The archived video itself is the printer's own file and is left alone —
  6727. rotating it would mean re-encoding it.
  6728. ``run_id`` is the print that ended: its own video is the one waited for,
  6729. not the archive's, which can be another plate's.
  6730. """
  6731. import uuid
  6732. from backend.app.models.archive import PrintArchive
  6733. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6734. from backend.app.services.print_log import run_of
  6735. logger = logging.getLogger(__name__)
  6736. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6737. deadline = asyncio.get_event_loop().time() + budget
  6738. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6739. while True:
  6740. async with async_session() as db:
  6741. if run_id is not None:
  6742. run = await run_of(db, archive_id, run_id)
  6743. timelapse_relpath = run.timelapse_path if run else None
  6744. else:
  6745. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6746. archive = result.scalar_one_or_none()
  6747. timelapse_relpath = archive.timelapse_path if archive else None
  6748. if timelapse_relpath:
  6749. video_path = app_settings.base_dir / timelapse_relpath
  6750. if video_path.exists() and video_path.stat().st_size > 0:
  6751. photos_dir = archive_dir / "photos"
  6752. photos_dir.mkdir(parents=True, exist_ok=True)
  6753. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6754. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6755. output_path = photos_dir / filename
  6756. if await extract_video_last_frame(video_path, output_path):
  6757. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6758. logger.info(
  6759. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6760. video_path.name,
  6761. archive_id,
  6762. )
  6763. return filename, False
  6764. logger.warning(
  6765. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6766. video_path.name,
  6767. archive_id,
  6768. )
  6769. return None, False
  6770. if asyncio.get_event_loop().time() >= deadline:
  6771. logger.info(
  6772. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6773. archive_id,
  6774. budget,
  6775. )
  6776. return None, True
  6777. await asyncio.sleep(poll_interval)
  6778. async def _upgrade_finish_photo_from_timelapse(
  6779. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6780. ) -> None:
  6781. """Add the timelapse's last frame to an archive after the fact (#2704).
  6782. The print-complete notification waits only ~60s for the video, because
  6783. holding a notification for minutes is worse than sending it with a live
  6784. camera grab. On a P1-series printer the video often lands well after that,
  6785. so the archive used to be stuck with the live grab — which is taken at
  6786. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6787. the worse photo of the two.
  6788. This keeps waiting in the background and, when the video arrives, extracts
  6789. the frame and puts it *first* in the archive's photo list, so opening the
  6790. gallery shows it. The live grab is deliberately kept: the notification that
  6791. already went out links to that exact file, and deleting it would leave a
  6792. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6793. whose list leads with it too.
  6794. """
  6795. from backend.app.services.print_log import add_run_photo, run_of
  6796. logger = logging.getLogger(__name__)
  6797. filename, _ = await _capture_finish_photo_from_timelapse(
  6798. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6799. )
  6800. if not filename:
  6801. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6802. return
  6803. try:
  6804. async with async_session() as db:
  6805. from backend.app.models.archive import PrintArchive
  6806. archive = await db.get(PrintArchive, archive_id)
  6807. if archive is None:
  6808. return
  6809. photos = list(archive.photos or [])
  6810. if filename in photos:
  6811. return
  6812. # Front of the list: PhotoGalleryModal opens at index 0.
  6813. archive.photos = [filename, *photos]
  6814. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6815. await db.commit()
  6816. except Exception as e:
  6817. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6818. return
  6819. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6820. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6821. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6822. """Put the filament-attribution context back after a restart mid-print.
  6823. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6824. both die with the process. The print keeps running, so at completion the
  6825. tracker would fall back to whatever the printer reports *now* — and AMS
  6826. filament backup makes "now" the substitute tray, charging the whole print
  6827. to the spool that only finished it.
  6828. The persisted row is only trusted when its print name still matches what
  6829. the printer says it is running: a row left behind by a completion we never
  6830. saw must not attach itself to the next print.
  6831. """
  6832. try:
  6833. from backend.app.api.routes.settings import get_setting
  6834. from backend.app.services.usage_tracker import (
  6835. clear_persisted_session,
  6836. get_persisted_ams_mapping,
  6837. get_persisted_print_name,
  6838. get_persisted_spool_change_log,
  6839. restore_session,
  6840. )
  6841. persisted_name = await get_persisted_print_name(db, printer_id)
  6842. current_name = (state.subtask_name or "").strip()
  6843. if persisted_name and current_name and persisted_name.strip() != current_name:
  6844. logger.info(
  6845. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6846. printer_id,
  6847. persisted_name,
  6848. current_name,
  6849. )
  6850. await clear_persisted_session(db, printer_id)
  6851. # Fall through to seeding: the print on the printer is real, it just
  6852. # isn't the one the row described.
  6853. persisted_log = None
  6854. else:
  6855. # Spoolman users get the tray-change log back but no in-memory
  6856. # session — see ``on_print_start`` on why that dict is load-bearing
  6857. # for the remain%-sync guard.
  6858. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6859. persisted_log = await restore_session(
  6860. db,
  6861. printer_id,
  6862. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6863. )
  6864. # The slot pills (#1762) read the mapping captured from the print
  6865. # command, which dies with the process as well. One this process
  6866. # has captured since is newer.
  6867. if state.print_ams_mapping is None:
  6868. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6869. # Spools swapped on a tray before the restart (#3325); anything this
  6870. # process has recorded since goes after them.
  6871. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6872. if persisted_swaps:
  6873. seen = getattr(state, "spool_change_log", None) or []
  6874. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6875. if persisted_log:
  6876. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6877. # Anything this process already observed goes after the persisted
  6878. # history — the log is ordered by layer, and a fresh process can
  6879. # only have seen changes from later in the print.
  6880. for entry in state.tray_change_log or []:
  6881. if tuple(entry) not in restored:
  6882. restored.append(tuple(entry))
  6883. state.tray_change_log = restored
  6884. tray_now = state.tray_now
  6885. if 0 <= tray_now <= 254:
  6886. if not state.tray_change_log:
  6887. # No persisted history — a print that started before this build,
  6888. # or before the row existed. Seed with the tray feeding right
  6889. # now so the remainder of the print is at least attributable to
  6890. # the right spool.
  6891. state.tray_change_log = [(tray_now, state.layer_num)]
  6892. logger.info(
  6893. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6894. printer_id,
  6895. tray_now,
  6896. state.layer_num,
  6897. )
  6898. # The tray handler updates ``last_loaded_tray`` on every push
  6899. # regardless of whether it logged a change, so re-align it to avoid
  6900. # a duplicate entry on the next push. Only ever with a real tray:
  6901. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6902. # 255" fallback, and writing 255 into it would defeat that.
  6903. state.last_loaded_tray = tray_now
  6904. except Exception:
  6905. # Never let attribution recovery cost the caller its timelapse
  6906. # baseline — that capture has to happen before the printer uploads
  6907. # the in-flight MP4 and there is no second chance at it.
  6908. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6909. async def on_print_running_observed(printer_id: int, data: dict):
  6910. """Restart-recovery for a print that started before Bambuddy came up.
  6911. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6912. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6913. creation). This hook restores the persisted archive into ``_active_prints``
  6914. and captures the timelapse baseline that normally hangs off print start.
  6915. Fires once per session, in lieu of on_print_start when restart-recovery
  6916. kicks in. The printer doesn't upload the timelapse until after PRINT
  6917. COMPLETE, so a baseline captured any time during the print is still
  6918. pre-upload.
  6919. """
  6920. logger = logging.getLogger(__name__)
  6921. async with async_session() as db:
  6922. from backend.app.models.printer import Printer
  6923. state = printer_manager.get_status(printer_id)
  6924. if state is not None:
  6925. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6926. if authorization is True:
  6927. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6928. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6929. await _restore_printable_objects(printer_id, state, db, logger)
  6930. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6931. printer = result.scalar_one_or_none()
  6932. if not printer:
  6933. logger.warning(
  6934. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6935. printer_id,
  6936. )
  6937. return
  6938. # Avoid double-capture: ownership reconciliation above must still run when
  6939. # a baseline already exists, but the camera work itself is one-shot.
  6940. if printer_id in _timelapse_baselines:
  6941. logger.debug(
  6942. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6943. printer_id,
  6944. )
  6945. return
  6946. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6947. class _RunOfArchive:
  6948. """An archive as one of its runs printed it: the run's job id, start and
  6949. plate, the rest the archive's. What the reconcile judges and closes."""
  6950. def __init__(self, archive, run):
  6951. self._archive = archive
  6952. self.subtask_id = run.subtask_id
  6953. self.started_at = run.started_at
  6954. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6955. def __getattr__(self, name):
  6956. return getattr(self._archive, name)
  6957. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6958. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6959. against the printer's current MQTT state.
  6960. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6961. COMPLETE events, typically a print finishing during an MQTT disconnect
  6962. window followed by a smart-plug power cycle):
  6963. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6964. provably not running anymore — only branch that should fire under
  6965. normal disconnect-then-reconnect timing.
  6966. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6967. firmware mints a fresh ``subtask_id`` for each print, including the
  6968. ghost replay it runs after a power cycle from a leftover SD file —
  6969. so a mismatch unambiguously means the in-DB archive is no longer
  6970. the print on the printer.
  6971. 3. Printer is running but ``subtask_name`` is empty. The printer
  6972. doesn't know what it's running; the archive's reference to it is
  6973. already broken.
  6974. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6975. with matching subtask_id+subtask_name is left alone. The cost of a false
  6976. positive is a print closed while it still runs: the reconcile takes its
  6977. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6978. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6979. cost of a false negative is the ghost-print loop in #1542. What the
  6980. archive is closed as is ``_reconciled_outcome``'s call.
  6981. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6982. MQTT has connected but the first ``push_status`` response hasn't been
  6983. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6984. The reconcile caller in ``on_printer_status_change`` is already gated
  6985. on a real ``state.state``, so in normal operation this branch is
  6986. unreachable; it's kept as belt-and-braces for future callers and for
  6987. the narrow window where a partial state update could arrive
  6988. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6989. ``not stale`` on degenerate input is strictly conservative: a real
  6990. stale archive will still be caught by the next push_status arriving
  6991. with terminal state.
  6992. """
  6993. current_state = (state.state or "").upper()
  6994. if current_state in ("", "UNKNOWN"):
  6995. # No real push_status yet — PrinterState defaults are not evidence.
  6996. return False, ""
  6997. if current_state in ("IDLE", "FINISH", "FAILED"):
  6998. return True, f"printer state {current_state}"
  6999. # Below here the printer is in a running / pre-running state (RUNNING /
  7000. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  7001. current_subtask_id = (state.subtask_id or "").strip()
  7002. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  7003. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  7004. current_subtask_name = (state.subtask_name or "").strip()
  7005. if not current_subtask_name:
  7006. return True, "printer subtask_name empty"
  7007. return False, ""
  7008. async def prime_kprofile_table(printer_id: int) -> int:
  7009. """Read the printer's calibration table once per connection.
  7010. The AMS slot card shows a K value per slot (#2854). On the printers whose
  7011. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  7012. report ``cali_idx`` and nothing else -- that number can only come from
  7013. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  7014. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  7015. backup, or the printer answering a query BambuStudio made on the report
  7016. topic we share. A Bambuddy that nobody visited showed a card with no K
  7017. values at all.
  7018. Only the diameters actually fitted are asked for, which is one request on a
  7019. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7020. what the backup does, and it is both wasteful and the thing that used to
  7021. blank the table.
  7022. Returns the number of nozzles whose table was read.
  7023. """
  7024. client = printer_manager.get_client(printer_id)
  7025. state = printer_manager.get_status(printer_id)
  7026. if client is None or state is None or not state.connected:
  7027. return 0
  7028. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7029. # ask once, and both entries are empty until the first push_status lands.
  7030. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7031. if not diameters:
  7032. logging.getLogger(__name__).debug(
  7033. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7034. printer_id,
  7035. )
  7036. return 0
  7037. primed = 0
  7038. for diameter in diameters:
  7039. try:
  7040. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7041. except Exception as exc: # noqa: BLE001
  7042. # A printer that won't answer costs the card its K values, nothing
  7043. # more — never the connection this runs on the back of.
  7044. logging.getLogger(__name__).warning(
  7045. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7046. )
  7047. continue
  7048. primed += 1
  7049. logging.getLogger(__name__).info(
  7050. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7051. )
  7052. return primed
  7053. def _sd_files_in_use(state) -> set[str]:
  7054. """Names of the SD-card files the printer may be printing right now (#3009).
  7055. The post-print cleanup works out what to delete from the finished archive,
  7056. not from the printer. When reconciliation closes an old archive because the
  7057. printer has moved on to a new job, and that job is the same file reprinted
  7058. from the printer's screen, the cleanup would delete the file mid-print.
  7059. Empty unless the printer is busy: on an ordinary completion the state is
  7060. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7061. name, a path or a URL depending on firmware, and some report only the
  7062. plate's G-code, so the job name is matched as well, in the same spellings
  7063. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7064. ignores case.
  7065. """
  7066. def _text(value) -> str:
  7067. return value.strip() if isinstance(value, str) else ""
  7068. if state is None:
  7069. return set()
  7070. current_state = _text(getattr(state, "state", None)).upper()
  7071. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7072. return set()
  7073. in_use: set[str] = set()
  7074. gcode_file = _text(getattr(state, "gcode_file", None))
  7075. if gcode_file:
  7076. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7077. # both legal in a file name, and raises on some inputs.
  7078. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7079. if name:
  7080. in_use.add(name.lower())
  7081. subtask_name = _text(getattr(state, "subtask_name", None))
  7082. if subtask_name:
  7083. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7084. for ext in (".3mf", ".gcode"):
  7085. in_use.add(f"{name}{ext}".lower())
  7086. return in_use
  7087. def _reconciled_outcome(archive, state) -> str:
  7088. """What a stale archive is closed as at reconnect (#3310).
  7089. A print that ends while Bambuddy restarts is never seen to end: the new
  7090. MQTT client's first status is already FINISH, which is not a transition.
  7091. The printer keeps reporting the finished job's ``subtask_id`` until the
  7092. next print, so a matching id proves the FINISH or FAILED is this
  7093. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7094. started outside the cloud) or none -- says only that the print is over,
  7095. not how, and stays ``aborted``.
  7096. """
  7097. current_state = (state.state or "").upper()
  7098. if current_state not in ("FINISH", "FAILED"):
  7099. return "aborted"
  7100. archive_id = (archive.subtask_id or "").strip()
  7101. current_id = str(state.subtask_id or "").strip()
  7102. if archive_id in ("", "0") or archive_id != current_id:
  7103. return "aborted"
  7104. return "completed" if current_state == "FINISH" else "failed"
  7105. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7106. """When a print reconciled as completed most likely ended, or None (#3310).
  7107. The printer does not say when it finished, and the reconnect can be hours
  7108. later. Its start plus the slicer's estimate for the plate it printed,
  7109. never later than now, is the best guess; None when either is missing,
  7110. and the run then keeps no duration, as an aborted one does.
  7111. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7112. of another plate reuses the archive without changing ``archive.plate_id``.
  7113. """
  7114. started = archive.started_at
  7115. if not started:
  7116. return None
  7117. if started.tzinfo is None:
  7118. started = started.replace(tzinfo=timezone.utc)
  7119. plate = plate_id if plate_id is not None else archive.plate_id
  7120. estimate = None
  7121. if archive.file_path:
  7122. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7123. full_path = (
  7124. app_settings.base_dir / archive.file_path
  7125. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7126. try:
  7127. estimate = extract_print_time_from_3mf(full_path, plate)
  7128. except Exception as exc: # noqa: BLE001
  7129. logging.getLogger(__name__).debug(
  7130. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7131. )
  7132. if plate is None and estimate != archive.print_time_seconds:
  7133. # Without a plate the first plate's estimate is read. The archive
  7134. # carries the sum over all plates (#1593), so a difference means
  7135. # several plates and no telling which one printed.
  7136. estimate = None
  7137. elif plate is None:
  7138. # Nothing to read the plate from; the archive's own estimate, as for
  7139. # a single-plate file.
  7140. estimate = archive.print_time_seconds
  7141. if not estimate or estimate <= 0:
  7142. return None
  7143. return min(started + timedelta(seconds=int(estimate)), now)
  7144. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7145. """Synthesise ``on_print_complete`` for archives whose print can't be
  7146. running on the printer anymore.
  7147. Called once per MQTT (re)connection (from on_printer_status_change when
  7148. the connected edge flips False → True) and at Bambuddy startup (from
  7149. the FastAPI lifespan). Without this, a print that completes during a
  7150. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7151. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7152. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7153. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7154. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7155. closes the loop by faking the missed PRINT COMPLETE — the existing
  7156. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7157. and notifications.
  7158. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7159. when the printer still reports the archive's own job as finished or
  7160. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7161. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7162. after a restart the printer's FINISH is not one (#3310).
  7163. Returns the number of archives reconciled.
  7164. """
  7165. state = printer_manager.get_status(printer_id)
  7166. if not state:
  7167. return 0
  7168. # Don't reconcile while disconnected — we'd be making a decision against
  7169. # stale cached state. The connected → reconcile edge handles this.
  7170. if not state.connected:
  7171. return 0
  7172. from backend.app.models.archive import PrintArchive
  7173. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7174. reconciled = 0
  7175. async with async_session() as db:
  7176. # The prints on this printer Bambuddy saw start: their runs open here.
  7177. # The archive row is shared by every plate of a file, its printer, job
  7178. # and start the latest start's, so each is judged as its run.
  7179. open_runs = (
  7180. await db.scalars(
  7181. select(PrintLogEntry)
  7182. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7183. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7184. )
  7185. ).all()
  7186. by_run = {
  7187. archive.id: archive
  7188. for archive in (
  7189. await db.scalars(
  7190. select(PrintArchive).where(
  7191. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7192. )
  7193. )
  7194. ).all()
  7195. }
  7196. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7197. # And as before runs were opened at the start: a printing archive of
  7198. # this printer with no run open anywhere (printing since before).
  7199. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7200. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7201. )
  7202. result = await db.execute(
  7203. select(PrintArchive)
  7204. .where(
  7205. PrintArchive.printer_id == printer_id,
  7206. PrintArchive.status == "printing",
  7207. PrintArchive.id.not_in(archives_with_open_runs),
  7208. )
  7209. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7210. )
  7211. active.extend(result.scalars().all())
  7212. if not active:
  7213. return 0
  7214. # The plate each run printed, from its queue job (#3310).
  7215. from backend.app.models.print_queue import PrintQueueItem
  7216. async with async_session() as db:
  7217. plate_rows = await db.execute(
  7218. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7219. PrintQueueItem.printer_id == printer_id,
  7220. PrintQueueItem.status == "printing",
  7221. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7222. )
  7223. )
  7224. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7225. logger = logging.getLogger(__name__)
  7226. for archive in active:
  7227. is_stale, reason = _is_active_archive_stale(archive, state)
  7228. if not is_stale:
  7229. continue
  7230. logger.info(
  7231. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7232. printer_id,
  7233. archive.id,
  7234. archive.filename,
  7235. reason,
  7236. )
  7237. # Synthesised payload: minimal fields the on_print_complete chain
  7238. # needs. `_reconciled` marker lets downstream code distinguish this
  7239. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7240. # metrics / debug logging). raw_data is the live printer state so
  7241. # the usage tracker can compare end-of-print remain% against the
  7242. # captured start values.
  7243. outcome = _reconciled_outcome(archive, state)
  7244. payload = {
  7245. "status": outcome,
  7246. "filename": archive.filename,
  7247. "subtask_name": archive.print_name or "",
  7248. "subtask_id": archive.subtask_id or "",
  7249. "raw_data": state.raw_data or {},
  7250. "_reconciled": True,
  7251. }
  7252. if isinstance(archive, _RunOfArchive):
  7253. # The archive it closes, which its names and printer may not find:
  7254. # another printer's plate of it can have started since.
  7255. payload["_reconciled_archive_id"] = archive.id
  7256. if outcome != "aborted":
  7257. # The printer's progress and layer are this job's, so a partial
  7258. # run is charged what it printed rather than nothing.
  7259. if state.progress:
  7260. payload["last_progress"] = state.progress
  7261. if state.layer_num:
  7262. payload["last_layer_num"] = state.layer_num
  7263. if outcome == "failed":
  7264. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7265. if outcome == "completed":
  7266. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7267. if ended:
  7268. payload["_reconciled_completed_at"] = ended
  7269. try:
  7270. await on_print_complete(printer_id, payload)
  7271. reconciled += 1
  7272. except Exception as e:
  7273. # Catch-all: a reconciliation failure must not block the
  7274. # printer's normal status flow. The archive stays in
  7275. # ``status="printing"`` and the next reconnect retries.
  7276. logger.warning(
  7277. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7278. archive.id,
  7279. e,
  7280. )
  7281. return reconciled
  7282. # #2547: clearance left between the nozzle and the top of the print when the
  7283. # plate is commanded back into camera framing. The nozzle is parked away from
  7284. # the part by then, so this is belt-and-braces against a max_z_height that
  7285. # under-reports (e.g. a slicer that excludes a final Z hop).
  7286. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7287. # How far below the restored position to drop the plate again afterwards, so
  7288. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7289. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7290. # on machines with less headroom.
  7291. _PLATE_PARK_DROP_MM = 100.0
  7292. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7293. # this axis, so it is a proven-safe speed for the full travel.
  7294. _PLATE_RESTORE_FEEDRATE = 600
  7295. # Time allowed for the plate to reach the restored position before the camera
  7296. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7297. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7298. # How long `_background_finish_photo` waits for this producer. Must cover the
  7299. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7300. # notification path's own photo wait so a slow producer degrades to a
  7301. # photo-less notification rather than a missed one. The chamber light's
  7302. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7303. # camera_light.MAX_DELAY_SECONDS stays below it.
  7304. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7305. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7306. """The ``_active_prints`` keys a finished print may be registered under.
  7307. Matching how they were registered in on_print_start. Shared by
  7308. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7309. to find the same binding.
  7310. """
  7311. possible_keys = []
  7312. # Try subtask_name variations first (most reliable for matching)
  7313. if subtask_name:
  7314. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7315. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7316. possible_keys.append((printer_id, subtask_name))
  7317. # Try filename variations
  7318. if filename:
  7319. # Extract just the filename if it's a path
  7320. fname = filename.split("/")[-1] if "/" in filename else filename
  7321. if fname.endswith(".3mf"):
  7322. possible_keys.append((printer_id, fname))
  7323. elif fname.endswith(".gcode"):
  7324. base_name = fname.rsplit(".", 1)[0]
  7325. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7326. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7327. possible_keys.append((printer_id, fname))
  7328. else:
  7329. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7330. possible_keys.append((printer_id, f"{fname}.3mf"))
  7331. possible_keys.append((printer_id, fname))
  7332. # Also try full path versions
  7333. if filename.endswith(".3mf"):
  7334. possible_keys.append((printer_id, filename))
  7335. elif filename.endswith(".gcode"):
  7336. base_name = filename.rsplit(".", 1)[0]
  7337. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7338. possible_keys.append((printer_id, filename))
  7339. else:
  7340. possible_keys.append((printer_id, f"{filename}.3mf"))
  7341. possible_keys.append((printer_id, filename))
  7342. return possible_keys
  7343. def _archive_name_forms(archive) -> set[str]:
  7344. """The names an archive could be echoed back as, in normalised form (#3240).
  7345. Its print name, and its filename with and without the 3MF extension.
  7346. """
  7347. forms = set()
  7348. if archive.print_name:
  7349. forms.add(_normalise_subtask_name(archive.print_name))
  7350. if archive.filename:
  7351. forms.add(_normalise_subtask_name(archive.filename))
  7352. for suffix in (".gcode.3mf", ".3mf"):
  7353. if archive.filename.lower().endswith(suffix):
  7354. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7355. forms.discard("")
  7356. return forms
  7357. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7358. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7359. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7360. from the plate recorded when the job was dispatched. Neither is touched:
  7361. ``on_print_complete`` pops both, which is why the finish-photo producer
  7362. calls this before its first await, while they are still there.
  7363. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7364. archive, or that it only knows by a name -- and on any error: the producer
  7365. calls this before the ``try`` that always releases the photo consumer, so
  7366. it must not raise.
  7367. """
  7368. try:
  7369. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7370. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7371. if archive_id is None:
  7372. return None, None
  7373. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7374. except Exception:
  7375. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7376. return None, None
  7377. async def _max_z_for_current_print(
  7378. printer_id: int,
  7379. data: dict,
  7380. logger,
  7381. archive_id: int | None,
  7382. plate_id: int | None = None,
  7383. ) -> float | None:
  7384. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7385. This number becomes the target of a real Z move, so every step here refuses
  7386. rather than guesses. A height belonging to some *other* print is the one
  7387. failure that could drive the nozzle into the model: 20 mm carried onto a
  7388. 200 mm print would command the plate up through the part.
  7389. Three independent things therefore have to agree before a height is
  7390. returned:
  7391. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7392. when it started (see ``_bound_print``), never one found by name. A name
  7393. is not an identity: every plate of a multi-plate file shares one, and a
  7394. reprint reuses its archive row, so the newest archive with the right
  7395. name can be another plate of the same file. Support bundles show the
  7396. old name lookup doing exactly that (archive 288 for a print bound to
  7397. 169, 313 layers against 125), stopped only by the layer check below.
  7398. No binding, no move.
  7399. 2. **Identity.** The bound archive's name still has to be the finished
  7400. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7401. because the printer echoes spaces as underscores (#3240). Exact: not a
  7402. substring, and not the completion check's tolerance for a truncated
  7403. echo.
  7404. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7405. match the layer count the printer itself reported over MQTT for the print
  7406. that just ended. These come from genuinely different sources, so a
  7407. mismatch means the row is not this print, whatever its name says.
  7408. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7409. plate of a multi-plate file reuses the archive row without updating its
  7410. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7411. ``on_print_complete`` may already have flipped the status by the time we
  7412. run.
  7413. """
  7414. subtask_name = (data.get("subtask_name") or "").strip()
  7415. if not subtask_name:
  7416. # Nothing to identify the print by — refuse rather than fall back to
  7417. # "whatever ran last on this printer".
  7418. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7419. return None
  7420. if archive_id is None:
  7421. logger.info(
  7422. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7423. printer_id,
  7424. subtask_name,
  7425. )
  7426. return None
  7427. try:
  7428. from backend.app.models.archive import PrintArchive
  7429. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7430. async with async_session() as db:
  7431. result = await db.execute(
  7432. select(PrintArchive).where(
  7433. PrintArchive.id == archive_id,
  7434. PrintArchive.printer_id == printer_id,
  7435. PrintArchive.status.in_(("printing", "completed")),
  7436. PrintArchive.deleted_at.is_(None),
  7437. )
  7438. )
  7439. archive = result.scalar_one_or_none()
  7440. if archive is None or not archive.file_path:
  7441. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7442. return None
  7443. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7444. logger.warning(
  7445. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7446. printer_id,
  7447. archive_id,
  7448. subtask_name,
  7449. )
  7450. return None
  7451. client = printer_manager.get_client(printer_id)
  7452. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7453. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7454. logger.warning(
  7455. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7456. "— refusing to move the plate on a height that may not be this print's",
  7457. printer_id,
  7458. archive.id,
  7459. archive.total_layers,
  7460. reported_layers,
  7461. )
  7462. return None
  7463. # Stored relative to the data directory, like every other archive path
  7464. # (#3240: this read a `data_dir` setting that does not exist).
  7465. path = app_settings.base_dir / archive.file_path
  7466. plate = plate_id or archive.plate_id or 1
  7467. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7468. except Exception as e:
  7469. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7470. return None
  7471. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7472. """Raise the plate back into camera framing before the finish photo (#2547).
  7473. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7474. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7475. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7476. This commands an absolute ``G1 Z`` back to just above the last printed
  7477. layer.
  7478. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7479. clearance`` is a height the toolhead was physically at seconds earlier, so
  7480. it is inside the travel limits by construction and leaves the nozzle above
  7481. the part. It is also unambiguous across model families: Z is the
  7482. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7483. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7484. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7485. (#2579).
  7486. Returns True if the move was sent and waited out, False if it was skipped.
  7487. """
  7488. client = printer_manager.get_client(printer_id)
  7489. if client is None:
  7490. return False
  7491. # Re-read state immediately before commanding motion. If the queue has
  7492. # already started the next print, the printer is no longer ours to move.
  7493. state = getattr(client, "state", None)
  7494. if state is None or state.state != "FINISH":
  7495. logger.info(
  7496. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7497. printer_id,
  7498. getattr(state, "state", "unknown"),
  7499. )
  7500. return False
  7501. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7502. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7503. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7504. return False
  7505. logger.info(
  7506. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7507. printer_id,
  7508. target_z,
  7509. max_z_height,
  7510. _PLATE_RESTORE_CLEARANCE_MM,
  7511. _PLATE_RESTORE_SETTLE_SECONDS,
  7512. )
  7513. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7514. return True
  7515. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7516. """Drop the plate again after the finish photo (#2547).
  7517. Without this the user walks up to a finished print sitting just under the
  7518. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7519. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7520. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7521. print homes anyway.
  7522. """
  7523. client = printer_manager.get_client(printer_id)
  7524. state = getattr(client, "state", None) if client else None
  7525. if client is None or state is None or state.state != "FINISH":
  7526. return
  7527. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7528. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7529. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7530. """True if a queue item is about to take this printer (#2547).
  7531. The scheduler dispatches the next job the moment a print completes, and a
  7532. plate move interleaved with a print start is not a race worth having. The
  7533. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7534. this window; this closes the head of it.
  7535. """
  7536. try:
  7537. from backend.app.models.print_queue import PrintQueueItem
  7538. async with async_session() as db:
  7539. result = await db.execute(
  7540. select(PrintQueueItem.id)
  7541. .where(
  7542. PrintQueueItem.printer_id == printer_id,
  7543. PrintQueueItem.status.in_(("pending", "printing")),
  7544. )
  7545. .limit(1)
  7546. )
  7547. return result.scalar_one_or_none() is not None
  7548. except Exception as e:
  7549. # Fail closed: if we can't tell, don't move the plate.
  7550. logging.getLogger(__name__).debug(
  7551. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7552. )
  7553. return True
  7554. async def on_finish_photo_moment(printer_id: int, data: dict):
  7555. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7556. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7557. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7558. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7559. HMS halt, firmware variants). Grabs one frame via the same
  7560. external-camera / RTSP path the post-completion fallback uses, stores
  7561. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7562. ``_background_finish_photo`` consume the cached bytes when it runs.
  7563. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7564. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7565. set to Smooth (#1721). No force-on now means the user's explicit
  7566. timelapse=off in the slicer send dialog is respected.
  7567. """
  7568. logger = logging.getLogger(__name__)
  7569. trigger = data.get("trigger", "unknown")
  7570. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7571. logger.info(
  7572. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7573. printer_id,
  7574. trigger,
  7575. timelapse_was_active,
  7576. )
  7577. # If a timelapse is actively recording, skip the pre-capture — the
  7578. # post-completion path will extract the last frame from the recorded
  7579. # video, which still provides the best framing (toolhead parked,
  7580. # before bed drop) without the per-layer parking side effects.
  7581. if timelapse_was_active:
  7582. logger.info(
  7583. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7584. printer_id,
  7585. )
  7586. return
  7587. # #1790: register the producer-done event BEFORE the first await so the
  7588. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7589. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7590. # The `finally` below guarantees `set()` runs on every exit, including
  7591. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7592. producer_done = asyncio.Event()
  7593. _stage22_finish_in_flight[printer_id] = producer_done
  7594. # #3240: also before the first await. On the FINISH-state path
  7595. # `on_print_complete` is dispatched right behind us and pops both the
  7596. # print's archive binding and its plate; read here, they are still there.
  7597. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7598. # #2547: set once the plate has actually been raised, and read by the
  7599. # `finally` below. Declared out here so a failure anywhere after the move —
  7600. # a camera timeout, a DB error — still lowers the plate again.
  7601. restore_max_z: float | None = None
  7602. try:
  7603. async with async_session() as db:
  7604. from backend.app.api.routes.settings import get_setting
  7605. from backend.app.models.printer import Printer
  7606. capture_setting = await get_setting(db, "capture_finish_photo")
  7607. if capture_setting is not None and capture_setting.lower() != "true":
  7608. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7609. return
  7610. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7611. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7612. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7613. printer = result.scalar_one_or_none()
  7614. if printer is None:
  7615. logger.warning(
  7616. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7617. printer_id,
  7618. )
  7619. return
  7620. frame_bytes: bytes | None = None
  7621. # #2708: the banked frame arrives already rotated — it comes from
  7622. # `_capture_snapshot_for_notification`, which rotates before returning.
  7623. # Every other source below is a raw grab. Tracking which lets us store
  7624. # exactly one rotation in `_stage22_finish_frames` either way.
  7625. frame_already_rotated = False
  7626. # On the FINISH-state path the End G-code has already run, and two very
  7627. # different situations arrive here needing opposite answers.
  7628. #
  7629. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7630. # snippet may have ejected the plate — the scene in front of the camera
  7631. # is no longer the finished print, and no amount of moving the plate
  7632. # brings it back. Use the banked in-print frame instead.
  7633. #
  7634. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7635. # than the camera frames well, and the toolhead is parked out of the
  7636. # way. That is the *best* moment available on firmware that never emits
  7637. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7638. # back. Preferring the bank here unconditionally, as this code used to,
  7639. # is what shipped a mid-print photo with the toolhead over the part.
  7640. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7641. banked = _inprint_frame_bank.get(printer_id)
  7642. if banked:
  7643. frame_bytes = banked
  7644. frame_already_rotated = True
  7645. logger.info(
  7646. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7647. "frame (%d bytes) instead of a post-swap live grab",
  7648. len(banked),
  7649. )
  7650. else:
  7651. logger.warning(
  7652. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7653. "in-print bank is empty — falling back to a live grab, which may show a "
  7654. "swapped or empty plate",
  7655. printer_id,
  7656. )
  7657. # `restore_max_z` is set only once the plate is actually up, because the
  7658. # `finally` reads it to decide whether it owes a move back down.
  7659. #
  7660. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7661. # came up empty above: that machine may have just ejected its plate, and
  7662. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7663. # taking for a photo of a bed we already know may be bare.
  7664. if (
  7665. frame_bytes is None
  7666. and trigger == "finish_state"
  7667. and restore_plate_enabled
  7668. and not print_dispatch_context.end_gcode_injected(printer_id)
  7669. ):
  7670. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7671. if wants_restore is None:
  7672. logger.info(
  7673. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7674. printer_id,
  7675. )
  7676. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7677. logger.info(
  7678. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7679. printer_id,
  7680. )
  7681. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7682. restore_max_z = wants_restore
  7683. # Chamber light for the live capture below (#1655). The banked frame
  7684. # above was taken without it, like every in-print bank.
  7685. async with camera_light(printer if frame_bytes is None else None):
  7686. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7687. from backend.app.api.routes.camera import live_frame_for_capture
  7688. from backend.app.services.external_camera import capture_frame
  7689. # #2707: this used to collide with the live view and fail, which is
  7690. # how finish-photo notifications went out with no image attached.
  7691. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7692. defer, buffered = live_frame_for_capture(printer_id)
  7693. if defer:
  7694. frame_bytes = buffered
  7695. else:
  7696. frame_bytes = await capture_frame(
  7697. printer.external_camera_url,
  7698. printer.external_camera_type or "mjpeg",
  7699. snapshot_url=printer.external_camera_snapshot_url,
  7700. )
  7701. if frame_bytes:
  7702. logger.info(
  7703. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7704. len(frame_bytes),
  7705. )
  7706. elif frame_bytes is None:
  7707. from backend.app.api.routes.camera import get_buffered_frame
  7708. buffered = get_buffered_frame(printer_id)
  7709. if buffered:
  7710. frame_bytes = buffered
  7711. logger.info(
  7712. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7713. len(frame_bytes),
  7714. )
  7715. else:
  7716. from backend.app.services.camera import capture_camera_frame_bytes
  7717. frame_bytes = await capture_camera_frame_bytes(
  7718. ip_address=printer.ip_address,
  7719. access_code=printer.access_code,
  7720. model=printer.model,
  7721. timeout=15,
  7722. )
  7723. if frame_bytes:
  7724. logger.info(
  7725. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7726. len(frame_bytes),
  7727. )
  7728. if frame_bytes:
  7729. if not frame_already_rotated:
  7730. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7731. _stage22_finish_frames[printer_id] = frame_bytes
  7732. else:
  7733. logger.warning(
  7734. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7735. printer_id,
  7736. )
  7737. except Exception as e:
  7738. logger.warning(
  7739. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7740. printer_id,
  7741. e,
  7742. )
  7743. finally:
  7744. # #2547: we raised the plate, so we own lowering it — including when the
  7745. # capture above failed or threw partway through.
  7746. if restore_max_z is not None:
  7747. try:
  7748. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7749. except Exception as e:
  7750. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7751. # #1790: always unblock the consumer's bounded wait — whether we stored
  7752. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7753. # dict entry by the consumer doesn't affect signalling.
  7754. producer_done.set()
  7755. def _subtask_name_from_filename(filename: str) -> str:
  7756. """Recover the subtask name a print command would have carried for *filename*.
  7757. The dispatcher derives the printer-facing subtask name from the archive's
  7758. file name, so stripping the extensions back off gives the value MQTT echoes
  7759. on completion. Only the two extensions Bambuddy actually stores are removed,
  7760. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7761. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7762. """
  7763. name = PurePosixPath(filename).name
  7764. for suffix in (".3mf", ".gcode"):
  7765. if name.lower().endswith(suffix):
  7766. name = name[: -len(suffix)]
  7767. return name
  7768. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7769. """Whether the subtask name is the printed 3MF's own file name.
  7770. A print started from the printer's screen reports the same full name, with
  7771. its extension, as both subtask and file (#3009). A dispatched print reports
  7772. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7773. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7774. """
  7775. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7776. return False
  7777. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7778. # How the printer marks a subtask name it had to cut short. Observed on real
  7779. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7780. # (a name with multibyte characters came back at 98), so match the marker
  7781. # rather than a length.
  7782. _SUBTASK_TRUNCATION_MARKER = "..."
  7783. def _normalise_subtask_name(name: str) -> str:
  7784. """Canonical form for comparing a dispatched name against MQTT's echo.
  7785. The printer does not echo the name back verbatim: it substitutes
  7786. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7787. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7788. The 3MF lookup in this module has always known that -- it builds
  7789. space-to-underscore variants of every candidate filename, and its
  7790. directory search normalises both sides before comparing. This exists so
  7791. the completion check reads the same rule from the same place instead of
  7792. growing its own, which is exactly how it came to disagree (#2829).
  7793. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7794. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7795. are dropped after the substitution so both sides agree (#3241).
  7796. """
  7797. return name.strip().replace(" ", "_").strip("_").casefold()
  7798. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7799. """The 3MF files of the printer's folder listings that are this print's.
  7800. A file of the print's own name wins, in whichever folder. Only without one
  7801. is a file that merely contains the name taken, and then only when it is
  7802. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7803. candidates none can be told apart. Paths keep the listings' order.
  7804. """
  7805. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7806. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7807. if exact:
  7808. return exact
  7809. term = _normalise_subtask_name(search_term)
  7810. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7811. if len(partial) > 1:
  7812. logging.getLogger(__name__).info(
  7813. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7814. )
  7815. return []
  7816. return partial
  7817. def _subtask_names_match(expected: str, observed: str) -> bool:
  7818. """Whether two subtask names describe the same print.
  7819. Beyond the space/underscore substitution, the printer truncates long names
  7820. and marks the cut with ``...``. A truncated echo has to count as a match or
  7821. every print with a long name strands its queue item the same way.
  7822. """
  7823. expected_n = _normalise_subtask_name(expected)
  7824. observed_n = _normalise_subtask_name(observed)
  7825. if expected_n == observed_n:
  7826. return True
  7827. # Either side can be the truncated one: the printer truncates what it
  7828. # echoes, and an archive whose own filename was recorded from a previous
  7829. # truncated echo carries the marker too.
  7830. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7831. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7832. continue
  7833. # The full side has lost its edge underscores; a cut that lands right
  7834. # after one keeps it, so drop it here too (#3241). Nothing left before
  7835. # the marker is no evidence of anything, and must not match every name.
  7836. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7837. if kept and full.startswith(kept):
  7838. return True
  7839. return False
  7840. async def _queue_item_dispatched_name(db, item) -> str:
  7841. """The subtask name *item* was dispatched under, or "" when unknowable.
  7842. A row with no archive, or an archive with no file name, is unverifiable
  7843. rather than wrong; every caller answers that with its permissive branch.
  7844. """
  7845. if item.archive_id is None:
  7846. return ""
  7847. from backend.app.models.archive import PrintArchive
  7848. archive = await db.get(PrintArchive, item.archive_id)
  7849. if archive is None or not archive.filename:
  7850. return ""
  7851. return _subtask_name_from_filename(archive.filename)
  7852. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7853. """Whether this completion event is plausibly about *item*'s print.
  7854. The caller finds its queue row by printer and ``status='printing'`` alone,
  7855. which is all a completion event gives it -- there is no run identifier in
  7856. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7857. completion delivered for this printer closes whichever row happens to be
  7858. printing, however unrelated. Comparing the subtask name against the archive
  7859. the row was dispatched with costs one primary-key load and rules that out.
  7860. Deliberately permissive: it answers False only on a positive disagreement
  7861. between two names we actually have. A row with no archive, an archive with
  7862. no file name, or an event with no subtask name is unverifiable rather than
  7863. wrong, and refusing those would strand the item in ``printing`` and wedge
  7864. the printer's queue -- a worse failure than the one being prevented.
  7865. """
  7866. observed = (data.get("subtask_name") or "").strip()
  7867. if not observed or item.archive_id is None:
  7868. return True
  7869. from backend.app.models.archive import PrintArchive
  7870. archive = await db.get(PrintArchive, item.archive_id)
  7871. if archive is None or not archive.filename:
  7872. return True
  7873. expected = _subtask_name_from_filename(archive.filename)
  7874. if not expected or _subtask_names_match(expected, observed):
  7875. return True
  7876. logging.getLogger(__name__).warning(
  7877. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7878. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7879. "printing rather than closing a run this event is not about.",
  7880. item.id,
  7881. expected,
  7882. archive.id,
  7883. archive.filename,
  7884. observed,
  7885. )
  7886. return False
  7887. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7888. """Spend the 3MF download cache on a still-empty fallback archive.
  7889. ``on_print_complete`` drops the cache as its first act, which deletes the
  7890. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7891. print ran and the archive never got one, this is the last moment those bytes
  7892. exist (#2957).
  7893. """
  7894. logger = logging.getLogger(__name__)
  7895. names = [
  7896. n
  7897. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7898. if n
  7899. ]
  7900. for name in names:
  7901. try:
  7902. cached = get_cached_3mf(printer_id, name)
  7903. # The print has ended: its completion prices the archive, so no
  7904. # print-start estimate is scheduled to race it.
  7905. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7906. return
  7907. except Exception as e:
  7908. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7909. # Longest the print's end waits for its file to be deleted from the SD card
  7910. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7911. async def _cleanup_sd_card_after_print(
  7912. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7913. ) -> None:
  7914. """Delete a finished print's file from the printer's SD card."""
  7915. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7916. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7917. # auto-start files found in root on power cycle, causing ghost prints.
  7918. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7919. try:
  7920. if subtask_name:
  7921. archive_filename: str | None = None
  7922. async with async_session() as db:
  7923. from backend.app.models.archive import PrintArchive
  7924. from backend.app.models.printer import Printer
  7925. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7926. printer = result.scalar_one_or_none()
  7927. if archive_id:
  7928. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7929. archive_filename = archive_row.scalar_one_or_none()
  7930. if printer:
  7931. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7932. from backend.app.utils.filename import derive_remote_filename
  7933. # Primary candidate: the exact path the dispatcher uploaded to
  7934. # (derived from archive.filename via the same rule as upload).
  7935. # Without it, a library row that ended up with a doubled
  7936. # .gcode.3mf (#1542) leaves the real file behind because the
  7937. # subtask_name + ext fallbacks below don't match what's on the
  7938. # SD card. Fallbacks remain for archive-less prints (subtask
  7939. # never resolved to an archive) and for older naming variants.
  7940. candidate_paths: list[str] = []
  7941. if archive_filename:
  7942. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7943. for ext in (".3mf", ".gcode"):
  7944. fallback = f"/{subtask_name}{ext}"
  7945. if fallback not in candidate_paths:
  7946. candidate_paths.append(fallback)
  7947. # Three outcomes track across all candidates so the final log
  7948. # line reflects what actually happened. The A1 in #1721 always
  7949. # ends here with ``any_not_found=True`` and the others False
  7950. # — its firmware auto-cleans the SD card before our cleanup
  7951. # runs, every candidate FTP-DELE returns 550, and the old
  7952. # code burned 3 retries × 2 s × 3 candidates per print
  7953. # logging a misleading "may linger" WARNING on a successful
  7954. # print.
  7955. any_deleted = False
  7956. any_real_failure = False
  7957. any_not_found = False
  7958. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7959. for remote_path in candidate_paths:
  7960. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7961. logger.info(
  7962. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7963. remote_path,
  7964. printer.name,
  7965. )
  7966. continue
  7967. # Retry only the FAILED case — 550 NOT_FOUND will never
  7968. # recover by waiting, so a "file isn't here" answer
  7969. # advances immediately to the next candidate without
  7970. # consuming the retry budget.
  7971. for attempt in range(1, 4):
  7972. try:
  7973. delete_result = await delete_file_async(
  7974. printer.ip_address,
  7975. printer.access_code,
  7976. remote_path,
  7977. printer_model=printer.model,
  7978. )
  7979. except Exception as e:
  7980. delete_result = DeleteResult.FAILED
  7981. logger.warning(
  7982. "SD card cleanup attempt %d/3 raised for %s: %s",
  7983. attempt,
  7984. remote_path,
  7985. e,
  7986. )
  7987. if delete_result == DeleteResult.DELETED:
  7988. any_deleted = True
  7989. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7990. break
  7991. if delete_result == DeleteResult.NOT_FOUND:
  7992. any_not_found = True
  7993. break # 550 will not recover; try next candidate
  7994. # FAILED: real error — retry with backoff, then give up
  7995. if attempt < 3:
  7996. await asyncio.sleep(2)
  7997. else:
  7998. any_real_failure = True
  7999. logger.warning(
  8000. "SD card cleanup failed after 3 attempts for %s "
  8001. "(network/auth/transient error — file may linger on SD card)",
  8002. remote_path,
  8003. )
  8004. if not any_deleted and not any_real_failure and any_not_found:
  8005. # Every candidate said "not here." Either the printer
  8006. # firmware swept the SD card itself (common on A1) or the
  8007. # dispatcher's upload path doesn't match our candidate
  8008. # rule. Either way: nothing to clean up, no warning.
  8009. logger.debug(
  8010. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  8011. "(printer likely self-cleaned)",
  8012. printer.name,
  8013. )
  8014. except Exception as e:
  8015. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8016. async def on_print_complete(printer_id: int, data: dict):
  8017. """Handle print completion - update the archive status.
  8018. The printer counts as printing until the print's usage is booked (or this
  8019. ends), so the AMS remain% weight sync can't charge it a second time while
  8020. the usage tracker works (WU-3). Marked before the first await.
  8021. """
  8022. from backend.app.services.usage_tracker import done_completing, mark_completing
  8023. mark_completing(printer_id)
  8024. try:
  8025. await _close_out_print(printer_id, data)
  8026. finally:
  8027. done_completing(printer_id)
  8028. async def _close_out_print(printer_id: int, data: dict):
  8029. import time
  8030. logger = logging.getLogger(__name__)
  8031. start_time = time.time()
  8032. def log_timing(section: str):
  8033. elapsed = time.time() - start_time
  8034. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8035. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8036. # A kill-switch stop sends its provider notification immediately. Keep the
  8037. # task so the later notification path can await it and avoid a duplicate;
  8038. # if that immediate attempt failed, the regular completion path retries.
  8039. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8040. # Last chance before the bytes go: if this print's archive is still an empty
  8041. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8042. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8043. # below deletes the file (#2957).
  8044. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8045. # A pending cool-off retry has nothing left to recover for — the cache is
  8046. # about to be dropped and the print is over.
  8047. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8048. if retry_task and not retry_task.done():
  8049. retry_task.cancel()
  8050. # Drop the 3MF download cache for this printer (#972). The print is over,
  8051. # nothing else legitimately needs the bytes; keeping them would only risk
  8052. # handing a stale file to the next print if it reuses the same name.
  8053. clear_3mf_cache(printer_id)
  8054. try:
  8055. ws_data = {
  8056. "status": data.get("status"),
  8057. "filename": data.get("filename"),
  8058. "subtask_name": data.get("subtask_name"),
  8059. "timelapse_was_active": data.get("timelapse_was_active"),
  8060. }
  8061. await ws_manager.send_print_complete(printer_id, ws_data)
  8062. log_timing("WebSocket send_print_complete")
  8063. except Exception as e:
  8064. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8065. # Capture user info before clearing (needed for print log entry)
  8066. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8067. # Clear current print user tracking (Issue #206)
  8068. printer_manager.clear_current_print_user(printer_id)
  8069. # If the user explicitly stopped this print from the queue UI the printer will
  8070. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8071. # correct "print stopped" notification/email is sent instead of a failure alert.
  8072. _raw_status = data.get("status", "completed")
  8073. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8074. logger.info(
  8075. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8076. _raw_status,
  8077. printer_id,
  8078. )
  8079. data = {**data, "status": "cancelled"}
  8080. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8081. logger.info(
  8082. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8083. _raw_status,
  8084. printer_id,
  8085. )
  8086. data = {**data, "status": "cancelled", "_kill_switch": True}
  8087. _user_stopped_printers.discard(printer_id)
  8088. _kill_switch_stopped.discard(printer_id)
  8089. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8090. # may have left material on the bed: a user can cancel ten hours into a
  8091. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8092. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8093. # `_user_stopped_printers` is only populated when the user stops via the
  8094. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8095. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8096. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8097. # Auto Off power cycles and Bambuddy restarts.
  8098. try:
  8099. notify_live_activities.print_finished(printer_id, data)
  8100. except Exception:
  8101. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8102. _final_status = data.get("status", "completed")
  8103. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8104. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8105. # MQTT relay - publish print complete
  8106. try:
  8107. printer_info = printer_manager.get_printer(printer_id)
  8108. if printer_info:
  8109. await mqtt_relay.on_print_complete(
  8110. printer_id,
  8111. printer_info.name,
  8112. printer_info.serial_number,
  8113. data.get("filename", ""),
  8114. data.get("subtask_name", ""),
  8115. data.get("status", "completed"),
  8116. )
  8117. except Exception:
  8118. pass # Don't fail print complete callback if MQTT fails
  8119. filename = data.get("filename", "")
  8120. subtask_name = data.get("subtask_name", "")
  8121. if not filename and not subtask_name:
  8122. # Which print ended can't be told: the printer reported no name since
  8123. # Bambuddy started (a print that failed while preparing, a calibration).
  8124. # Charge nothing, but close the print session, which otherwise kept the
  8125. # AMS weight sync off until the next print (AS-5). A print archived as
  8126. # running is closed and charged by the reconnect reconcile.
  8127. logger.warning("Print complete without filename or subtask_name")
  8128. try:
  8129. from backend.app.services.usage_tracker import discard_session
  8130. async with async_session() as db:
  8131. await discard_session(db, printer_id)
  8132. except Exception as e:
  8133. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8134. return
  8135. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8136. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8137. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8138. # Find the archive for this print
  8139. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8140. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8141. archive_id = None
  8142. for key in possible_keys:
  8143. archive_id = _active_prints.pop(key, None)
  8144. if archive_id:
  8145. _owned_print_archive_ids.discard(archive_id)
  8146. logger.info("Found archive %s with key %s", archive_id, key)
  8147. # Also clean up the printer's other keys pointing to this archive;
  8148. # another printer's are a plate of it still printing there.
  8149. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8150. for k in keys_to_remove:
  8151. _active_prints.pop(k, None)
  8152. break
  8153. # The archive bound when the print started, before the name search below.
  8154. # Only this one may give the finish-photo plate restore a height (#3240):
  8155. # the search matches names by substring.
  8156. bound_archive_id = archive_id
  8157. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8158. # The reconcile names the archive whose run on this printer it
  8159. # closes. Only while that run is open: the print's real end may have
  8160. # closed it meanwhile, or closed the print without managing to write
  8161. # it, and either way there is nothing left to end twice.
  8162. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8163. logger.info(
  8164. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8165. data["_reconciled_archive_id"],
  8166. printer_id,
  8167. )
  8168. return
  8169. archive_id = data["_reconciled_archive_id"]
  8170. ending_job = str(data.get("subtask_id") or "").strip()
  8171. if not archive_id and ending_job not in ("", "0"):
  8172. # Not bound (a restart since the start): this job's run, open on the
  8173. # printer. Only by its job id: a run open there can be of the print
  8174. # running now, while the end is of an earlier one closed late (the
  8175. # restart's reconcile of a missed end).
  8176. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8177. if archive_id:
  8178. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8179. if not archive_id:
  8180. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8181. async with async_session() as db:
  8182. from backend.app.models.archive import PrintArchive
  8183. # Try matching by subtask_name (stored as print_name) first. The
  8184. # same name rule as the queue's completion check: a name inside
  8185. # another ("Clip" in "Cable Clip") is a different print, and the
  8186. # printer's underscores for spaces and truncation still match.
  8187. if subtask_name:
  8188. printing = await db.scalars(
  8189. select(PrintArchive)
  8190. .where(PrintArchive.printer_id == printer_id)
  8191. .where(PrintArchive.status == "printing")
  8192. .order_by(PrintArchive.created_at.desc())
  8193. )
  8194. # A print started from the printer's screen reports its file
  8195. # name, extensions included, as the subtask (#3009).
  8196. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8197. archive = next(
  8198. (
  8199. candidate
  8200. for candidate in printing
  8201. if any(
  8202. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8203. or (
  8204. candidate.filename
  8205. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8206. )
  8207. for name in reported
  8208. )
  8209. ),
  8210. None,
  8211. )
  8212. if archive:
  8213. archive_id = archive.id
  8214. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8215. # Also try by filename
  8216. if not archive_id and filename:
  8217. result = await db.execute(
  8218. select(PrintArchive)
  8219. .where(PrintArchive.printer_id == printer_id)
  8220. .where(PrintArchive.filename == filename)
  8221. .where(PrintArchive.status == "printing")
  8222. .order_by(PrintArchive.created_at.desc())
  8223. .limit(1)
  8224. )
  8225. archive = result.scalar_one_or_none()
  8226. if archive:
  8227. archive_id = archive.id
  8228. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8229. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8230. # closed below. The stranded-job closer gives up after five and closed it
  8231. # first, so the job's auto-off and its billing never ran. Inline rather
  8232. # than in the background, so the next job of the same file isn't released
  8233. # (and uploaded under the name being deleted) while the cleanup still
  8234. # works on it. A delete already sent may still finish in its FTP thread
  8235. # after the cutoff, as one past delete_file_async's own timeout always did.
  8236. try:
  8237. await asyncio.wait_for(
  8238. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8239. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8240. )
  8241. except TimeoutError:
  8242. logger.warning(
  8243. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8244. printer_id,
  8245. _SD_CLEANUP_BUDGET_SECONDS,
  8246. )
  8247. log_timing("SD card cleanup")
  8248. # Update queue item status early — must run before the archive_id early-return
  8249. # so queue items don't get stuck in "printing" when archive lookup fails.
  8250. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8251. queue_item_id = None
  8252. billing_run_id: str | None = None
  8253. billing_user_id: int | None = None
  8254. billing_cost_center_id: int | None = None
  8255. billing_plate_id: int | None = None
  8256. queue_status = None
  8257. queue_auto_off = False
  8258. try:
  8259. from backend.app.core.database import run_with_retry
  8260. from backend.app.models.print_queue import PrintQueueItem
  8261. async def _update_queue_status(db):
  8262. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8263. nonlocal queue_item_id, queue_status, queue_auto_off
  8264. result = await db.execute(
  8265. select(PrintQueueItem)
  8266. .where(PrintQueueItem.printer_id == printer_id)
  8267. .where(PrintQueueItem.status == "printing")
  8268. )
  8269. printing_items = list(result.scalars().all())
  8270. if len(printing_items) > 1:
  8271. logger.warning(
  8272. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8273. printer_id,
  8274. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8275. )
  8276. item = printing_items[0] if printing_items else None
  8277. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8278. return
  8279. if item:
  8280. queue_status = data.get("status", "completed")
  8281. # MQTT sends "aborted" for cancelled prints; normalise to
  8282. # "cancelled" so it matches the queue schema Literal.
  8283. if queue_status == "aborted":
  8284. queue_status = "cancelled"
  8285. item.status = queue_status
  8286. item.completed_at = datetime.now(timezone.utc)
  8287. if queue_status == "failed" and not item.error_message:
  8288. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8289. # Bump usage counters on the source library file so admins can
  8290. # sort by "last printed" and (eventually) auto-purge stale
  8291. # files — #1008.
  8292. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8293. await db.commit()
  8294. queue_item_id = item.id
  8295. billing_run_id = item.billing_run_id
  8296. billing_user_id = item.created_by_id
  8297. billing_cost_center_id = item.cost_center_id
  8298. billing_plate_id = item.plate_id
  8299. queue_auto_off = item.auto_off_after
  8300. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8301. await run_with_retry(_update_queue_status, label="queue status update")
  8302. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8303. # their own sessions and have their own error handling — no retry needed.
  8304. if queue_item_id is not None:
  8305. # Batch orders (#342): this run may have been the last one an order
  8306. # owed. Re-evaluate here rather than lazily on read, so a finished
  8307. # order reports itself complete without someone opening the page.
  8308. try:
  8309. from backend.app.services.print_batch import refresh_batch_status_for_item
  8310. async with async_session() as db:
  8311. await refresh_batch_status_for_item(db, queue_item_id)
  8312. await db.commit()
  8313. except Exception as e:
  8314. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8315. # MQTT relay - publish queue job completed
  8316. try:
  8317. printer_info = printer_manager.get_printer(printer_id)
  8318. await mqtt_relay.on_queue_job_completed(
  8319. job_id=queue_item_id,
  8320. filename=filename or subtask_name,
  8321. printer_id=printer_id,
  8322. printer_name=printer_info.name if printer_info else "Unknown",
  8323. status=queue_status,
  8324. )
  8325. except Exception:
  8326. pass # Don't fail if MQTT fails
  8327. # Check if queue is now empty and send notification
  8328. try:
  8329. from sqlalchemy import func as sa_func
  8330. async with async_session() as db:
  8331. count_result = await db.execute(
  8332. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8333. )
  8334. pending_count = count_result.scalar() or 0
  8335. if pending_count == 0:
  8336. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8337. completed_result = await db.execute(
  8338. select(sa_func.count(PrintQueueItem.id)).where(
  8339. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8340. PrintQueueItem.completed_at >= today_start,
  8341. )
  8342. )
  8343. completed_count = completed_result.scalar() or 1
  8344. await notification_service.on_queue_completed(
  8345. completed_count=completed_count,
  8346. db=db,
  8347. )
  8348. except Exception:
  8349. pass # Don't fail if notification fails
  8350. # Handle auto_off_after - power off printer if the queue item opted
  8351. # in. Delegates to the smart-plug manager so the off honours each
  8352. # plug's configured strategy (time delay or temperature threshold),
  8353. # is cancelled if the printer starts printing again, and never cuts
  8354. # power on a loaded print (#1890). Previously an inline block here
  8355. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8356. # timeout regardless of print state — cutting a touchscreen reprint.
  8357. if queue_auto_off:
  8358. try:
  8359. async with async_session() as db:
  8360. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8361. except Exception as e:
  8362. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8363. except Exception as e:
  8364. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8365. log_timing("Queue item update")
  8366. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8367. # Must run before archive_id early-return so it fires for all prints (including
  8368. # prints started from BambuStudio/touchscreen that have no archive).
  8369. if data.get("status") == "completed":
  8370. try:
  8371. from backend.app.api.routes.settings import get_setting
  8372. async with async_session() as db:
  8373. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8374. threshold = float(threshold_str) if threshold_str else 35.0
  8375. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8376. async with async_session() as db:
  8377. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8378. if providers:
  8379. _bed_cool_waiters[printer_id] = {
  8380. "threshold": threshold,
  8381. "filename": filename or subtask_name or "",
  8382. "registered_at": time.time(),
  8383. }
  8384. logger.info(
  8385. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8386. printer_id,
  8387. threshold,
  8388. )
  8389. else:
  8390. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8391. except Exception as e:
  8392. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8393. # Capture the slicer estimate before usage tracking runs. The tracker may
  8394. # update archive.cost with this run's measured cost; billing partial runs
  8395. # against that already-partial value would discount the charge twice.
  8396. billing_planned_grams: float | None = None
  8397. billing_base_cost: float | None = None
  8398. if archive_id:
  8399. try:
  8400. async with async_session() as db:
  8401. from backend.app.models.archive import PrintArchive
  8402. billing_archive = await db.get(PrintArchive, archive_id)
  8403. if billing_archive:
  8404. billing_path = (
  8405. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8406. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8407. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8408. billing_archive,
  8409. billing_path,
  8410. billing_plate_id
  8411. if billing_plate_id is not None
  8412. else _get_start_plate_id(printer_id, archive_id),
  8413. )
  8414. except Exception as e:
  8415. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8416. # --- Track filament consumption (must run before archive_id early-return so usage
  8417. # is recorded even when auto-archive is disabled) ---
  8418. usage_results: list[dict] = []
  8419. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8420. stored_ams_mapping = data.get("ams_mapping")
  8421. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8422. # Drained either way, like the plate below: left over, it would be read by
  8423. # the archive's next run, dispatched without a mapping.
  8424. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8425. if not stored_ams_mapping:
  8426. stored_ams_mapping = registered_ams_mapping
  8427. # Always drain the plate_id register on completion — the session already
  8428. # consumed it at print-start injection; leaving it would leak into the next
  8429. # print on the same archive_id (rare but possible with reprints) (#1697).
  8430. # Capture the popped value so the completion notification can scope the
  8431. # archive-level (summed-across-plates per #1593) filament + time totals
  8432. # down to the single plate that was actually printed (#1785).
  8433. notify_plate_id: int | None = None
  8434. if archive_id:
  8435. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8436. # The start estimate must not outlive the real cost written below (COST-4).
  8437. if archive_id:
  8438. await _settle_archive_cost_estimate(archive_id)
  8439. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8440. try:
  8441. async with async_session() as db:
  8442. from backend.app.api.routes.settings import get_setting
  8443. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8444. if not _spoolman_on or _spoolman_on.lower() != "true":
  8445. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8446. async with async_session() as db:
  8447. usage_results = await usage_on_print_complete(
  8448. printer_id,
  8449. data,
  8450. printer_manager,
  8451. db,
  8452. archive_id=archive_id,
  8453. ams_mapping=stored_ams_mapping,
  8454. )
  8455. if usage_results:
  8456. await ws_manager.broadcast(
  8457. {
  8458. "type": "spool_usage_logged",
  8459. "printer_id": printer_id,
  8460. "usage": usage_results,
  8461. }
  8462. )
  8463. log_timing("Usage tracker")
  8464. except Exception as e:
  8465. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8466. # Drop the print-start context unconditionally — the Spoolman branch above
  8467. # skips the internal tracker entirely, so nothing else would clear what
  8468. # print start captured, and a row surviving its print would be restored
  8469. # onto the next one after a restart.
  8470. try:
  8471. from backend.app.services.usage_tracker import discard_session
  8472. async with async_session() as db:
  8473. await discard_session(db, printer_id)
  8474. except Exception as e:
  8475. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8476. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8477. # A partial run's cost from the Spoolman spools it was charged to; the
  8478. # built-in inventory's comes in usage_results.
  8479. spoolman_run_cost: float | None = None
  8480. if archive_id:
  8481. if data.get("status") == "completed":
  8482. try:
  8483. await _report_spoolman_usage(printer_id, archive_id)
  8484. log_timing("Spoolman usage report")
  8485. except Exception as e:
  8486. logger.warning("Spoolman usage reporting failed: %s", e)
  8487. else:
  8488. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8489. try:
  8490. async with async_session() as db:
  8491. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8492. printer_id,
  8493. archive_id,
  8494. db,
  8495. last_layer_num=data.get("last_layer_num"),
  8496. last_progress=data.get("last_progress"),
  8497. status=data.get("status") or "failed",
  8498. )
  8499. except Exception as e:
  8500. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8501. await _release_archived_spoolman_slots(printer_id)
  8502. log_timing("Filament usage tracking")
  8503. if not archive_id:
  8504. # The printer's own calibration run has no archive by design, so this
  8505. # arrives here every time one finishes. Returning before the no-archive
  8506. # notification keeps a calibration from being announced as a finished
  8507. # print. Everything above this point has already run — the plate-clear
  8508. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8509. # notification is skipped.
  8510. if is_internal_printer_job(filename, subtask_name):
  8511. logger.info(
  8512. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8513. filename,
  8514. subtask_name,
  8515. )
  8516. return
  8517. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8518. # Still send print-complete/failed/stopped notifications even without an archive.
  8519. # Try to enrich with queue/library-file data so user-specific emails work too.
  8520. async def _notify_no_archive():
  8521. try:
  8522. async with async_session() as db:
  8523. from backend.app.models.library import LibraryFile
  8524. from backend.app.models.print_queue import PrintQueueItem
  8525. from backend.app.models.printer import Printer
  8526. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8527. printer_obj = result.scalar_one_or_none()
  8528. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8529. # Only the queue item this completion itself closed (the
  8530. # reconciliation above, which checks the run belongs to it).
  8531. # A print started outside Bambuddy closed none, and must not
  8532. # borrow an earlier job's owner, email or times.
  8533. no_archive_data: dict | None = None
  8534. try:
  8535. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8536. if queue_item:
  8537. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8538. # How long it really ran, as the archive path reports it (#1198).
  8539. started = to_naive_utc(queue_item.started_at)
  8540. ended = to_naive_utc(queue_item.completed_at)
  8541. # Not for a completion reconciled at reconnect: it
  8542. # ended at an unknown time while the printer was
  8543. # offline, and "now" is the reconnect (DB-C9).
  8544. if (
  8545. not data.get("_reconciled")
  8546. and started
  8547. and ended
  8548. and (ended - started).total_seconds() > 0
  8549. ):
  8550. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8551. # Estimated time: the queue item caches it from its
  8552. # archive or library file; otherwise read the library
  8553. # file's metadata (LibraryFile has no column for it).
  8554. if queue_item.print_time_seconds:
  8555. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8556. elif queue_item.library_file_id:
  8557. lib_result = await db.execute(
  8558. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8559. )
  8560. lib_file = lib_result.scalar_one_or_none()
  8561. estimate = (
  8562. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8563. )
  8564. if estimate:
  8565. no_archive_data["print_time_seconds"] = estimate
  8566. except Exception as lookup_err:
  8567. logger.debug(
  8568. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8569. )
  8570. # Enrich with usage tracker results (captured in enclosing scope)
  8571. if usage_results:
  8572. if no_archive_data is None:
  8573. no_archive_data = {}
  8574. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8575. if total_from_usage > 0:
  8576. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8577. no_archive_data["usage_results"] = usage_results
  8578. # Try MQTT remaining_time for print duration when no queue/library data
  8579. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8580. mqtt_remaining = data.get("remaining_time")
  8581. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8582. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8583. ps = data.get("status", "completed")
  8584. logger.info(
  8585. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8586. )
  8587. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8588. await notification_service.on_print_complete(
  8589. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8590. )
  8591. else:
  8592. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8593. # Send user-specific email if we have a created_by_id
  8594. if no_archive_data and no_archive_data.get("created_by_id"):
  8595. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8596. await _dispatch_user_print_email(
  8597. ps,
  8598. no_archive_data["created_by_id"],
  8599. p_name,
  8600. raw_filename,
  8601. db,
  8602. )
  8603. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8604. except Exception as e:
  8605. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8606. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8607. return
  8608. log_timing("Archive lookup")
  8609. # Update archive status
  8610. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8611. try:
  8612. async with async_session() as db:
  8613. service = ArchiveService(db)
  8614. status = data.get("status", "completed")
  8615. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8616. if hms_errors:
  8617. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8618. failure_reason = derive_failure_reason(status, hms_errors)
  8619. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8620. # A reconciled completion closes out a stale archive at
  8621. # reconnect — it is not a user action, so don't mislabel it
  8622. # "userCancelled". It shares the stale-cleanup path's key
  8623. # (issue #2974) and records that the real end time is unknown,
  8624. # which is also why its logged duration is 0 (#2592). A failed
  8625. # one the printer's errors explain keeps their reason (#3310).
  8626. failure_reason = "noStatusUpdate"
  8627. elif data.get("_kill_switch"):
  8628. # Not the user's cancel: the kill switch stopped a print that did
  8629. # not come from Bambuddy.
  8630. failure_reason = "killSwitch"
  8631. if failure_reason:
  8632. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8633. elif status == "failed" and hms_errors:
  8634. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8635. await service.update_archive_status(
  8636. archive_id,
  8637. status=status,
  8638. completed_at=(
  8639. # A reconciled completed print ended at an estimated time,
  8640. # not at the reconnect (#3310).
  8641. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8642. if status in ("completed", "failed", "aborted", "cancelled")
  8643. else None
  8644. ),
  8645. failure_reason=failure_reason,
  8646. )
  8647. logger.info(
  8648. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8649. )
  8650. await ws_manager.send_archive_updated(
  8651. {
  8652. "id": archive_id,
  8653. "status": status,
  8654. }
  8655. )
  8656. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8657. # MQTT relay - publish archive updated
  8658. try:
  8659. await mqtt_relay.on_archive_updated(
  8660. archive_id=archive_id,
  8661. print_name=filename or subtask_name,
  8662. status=status,
  8663. )
  8664. except Exception:
  8665. pass # Don't fail if MQTT fails
  8666. except Exception as e:
  8667. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8668. # Continue with other operations even if archive update fails
  8669. log_timing("Archive status update")
  8670. # Apply finance wallet charge or release reservations once. For all partial
  8671. # terminal states (failed, aborted at the printer display, or cancelled via
  8672. # Bambuddy) use this run's measured spool delta, falling back to the last
  8673. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8674. # estimate and therefore cannot represent an interrupted run.
  8675. try:
  8676. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8677. async with async_session() as db:
  8678. from backend.app.models.archive import PrintArchive
  8679. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8680. from backend.app.services.print_log import run_being_ended
  8681. archive = await db.get(PrintArchive, archive_id)
  8682. # The run this end fills in below: charged as its own, not as
  8683. # the archive's latest dispatch (another plate of it, maybe).
  8684. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8685. if archive and billing_run_id is None and charged_run is None:
  8686. billing_run_id = getattr(archive, "billing_run_id", None)
  8687. if archive and archive.created_by_id is None and _print_user_info:
  8688. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8689. await db.flush()
  8690. run_status = data.get("status", "completed")
  8691. last_progress = data.get("last_progress")
  8692. if last_progress is None:
  8693. last_progress = data.get("progress")
  8694. actual_run_grams = _compute_run_filament_grams(
  8695. run_status,
  8696. billing_planned_grams,
  8697. last_progress,
  8698. usage_results,
  8699. )
  8700. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8701. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8702. charged = await apply_print_charge_for_archive(
  8703. db,
  8704. archive_id,
  8705. charged_user_id=billing_user_id,
  8706. cost_center_id=(
  8707. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8708. ),
  8709. print_queue_id=queue_item_id,
  8710. print_run_id=billing_run_id,
  8711. base_cost_override=billing_base_cost,
  8712. filament_usage=filament_usage,
  8713. run_entry_id=charged_run.id if charged_run is not None else None,
  8714. run_status=run_status,
  8715. )
  8716. await db.commit()
  8717. if charged:
  8718. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8719. except Exception as e:
  8720. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8721. printer_info = printer_manager.get_printer(printer_id)
  8722. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8723. billing_filename = filename or subtask_name or "Unknown"
  8724. billing_error = str(e)
  8725. try:
  8726. await ws_manager.broadcast(
  8727. {
  8728. "type": "billing_charge_failed",
  8729. "printer_id": printer_id,
  8730. "printer_name": billing_printer_name,
  8731. "filename": billing_filename,
  8732. "archive_id": archive_id,
  8733. }
  8734. )
  8735. except Exception as notification_error:
  8736. logger.error(
  8737. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8738. archive_id,
  8739. notification_error,
  8740. )
  8741. async def _notify_billing_charge_failed() -> None:
  8742. try:
  8743. async with async_session() as notification_db:
  8744. await notification_service.on_billing_charge_failed(
  8745. printer_id,
  8746. billing_printer_name,
  8747. billing_filename,
  8748. archive_id,
  8749. billing_error,
  8750. notification_db,
  8751. )
  8752. except Exception as provider_error:
  8753. logger.error(
  8754. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8755. archive_id,
  8756. provider_error,
  8757. exc_info=True,
  8758. )
  8759. spawn_background_task(
  8760. _notify_billing_charge_failed(),
  8761. name=f"billing-charge-failed-{archive_id}",
  8762. )
  8763. log_timing("Finance charge update")
  8764. # Write independent print log entry (separate table, never touches archives)
  8765. # The run's id, for the energy work below: the archive's newest run is
  8766. # the one started last, which with plates of it on two printers need not
  8767. # be the one that just ended.
  8768. completed_run_id: int | None = None
  8769. async def _write_run(db):
  8770. # Retried on a locked SQLite database: a run left open here would be
  8771. # closed again by the next reconnect's reconcile.
  8772. nonlocal completed_run_id
  8773. from backend.app.models.archive import PrintArchive
  8774. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8775. archive = await db.get(PrintArchive, archive_id)
  8776. if archive is None:
  8777. # Deleted while it printed: its run has nothing left to end on.
  8778. discarded = await discard_open_runs(db, printer_id)
  8779. await db.commit()
  8780. await _announce_discarded_runs(discarded, printer_id)
  8781. if archive:
  8782. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8783. # source archive row rather than creating a new one, so an
  8784. # archive that was auto-created from a printer-initiated
  8785. # print (created_by_id=NULL) would otherwise stay unattributed
  8786. # forever. When we have a print-session user AND the archive
  8787. # has no attribution yet, credit the current user. Never
  8788. # overwrite an existing attribution — the original uploader
  8789. # keeps ownership.
  8790. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8791. if archive.created_by_id is None and _print_user_id is not None:
  8792. archive.created_by_id = _print_user_id
  8793. p_info = printer_manager.get_printer(printer_id)
  8794. # Per-run actuals — written to PrintLogEntry so stats reflect
  8795. # what THIS print actually used, not the source archive's
  8796. # first-run values (#1378). Helper handles the partial-print
  8797. # math (failed / cancelled / stopped get scaled to progress
  8798. # or to tracked spool deltas).
  8799. _run_status = data.get("status", "completed")
  8800. # #2614: scope the per-run estimate to the printed plate. For a
  8801. # multi-plate 3MF dispatched one plate at a time, the archive's
  8802. # filament/cost are the whole-file totals; the PrintLogEntry must
  8803. # reflect only this plate. No effect on single-plate archives (the
  8804. # plate estimate equals the whole-file value) or on the tracker
  8805. # path (measured spool deltas win in _compute_run_filament_grams).
  8806. _est_full_path = (
  8807. app_settings.base_dir / archive.file_path if archive.file_path else None
  8808. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8809. # The plate that printed, as billing reads it: a reprint of
  8810. # another plate must not log the archive's first plate.
  8811. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8812. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8813. if _run_plate_id is None:
  8814. _run_plate_id = archive.plate_id
  8815. _run_grams = _compute_run_filament_grams(
  8816. _run_status,
  8817. _est_grams,
  8818. data.get("last_progress", data.get("progress")),
  8819. usage_results,
  8820. )
  8821. # Per-run cost — prefer usage_results sum. For partial prints
  8822. # we deliberately skip the topup-to-estimate logic in
  8823. # usage_tracker (which assumes the print completed); the raw
  8824. # tracked-spool sum is closer to what THIS run actually cost.
  8825. _run_cost: float | None = None
  8826. if usage_results:
  8827. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8828. if _run_cost is None and _run_status != "completed":
  8829. _run_cost = spoolman_run_cost
  8830. if _run_cost is None and _run_status == "completed":
  8831. _run_cost = _est_cost
  8832. from backend.app.models.printer import Printer as _Printer
  8833. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8834. run_entry = await write_log_entry(
  8835. db,
  8836. archive_id=archive.id,
  8837. # Captured by _update_queue_status above; None for
  8838. # printer-initiated prints with no queue row. Batch
  8839. # cost/energy roll-up joins on it (#342).
  8840. queue_item_id=queue_item_id,
  8841. status=_run_status,
  8842. print_name=archive.print_name,
  8843. # The plate this run printed, as the estimate above takes
  8844. # it; the archive's own is the latest run's.
  8845. plate_id=_run_plate_id,
  8846. printer_name=p_info.name if p_info else None,
  8847. printer_id=printer_id,
  8848. started_at=archive.started_at,
  8849. completed_at=archive.completed_at,
  8850. filament_type=archive.filament_type,
  8851. filament_color=archive.filament_color,
  8852. filament_used_grams=_run_grams,
  8853. cost=_run_cost,
  8854. wear_cost_per_hour=_wear_rate,
  8855. failure_reason=archive.failure_reason,
  8856. thumbnail_path=archive.thumbnail_path,
  8857. created_by_id=archive.created_by_id,
  8858. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8859. # Reconciled completions have an unknown real end time —
  8860. # log 0 duration instead of the whole disconnect gap (#2592),
  8861. # unless it was estimated (#3310).
  8862. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8863. # Its time is the estimate or nothing, never measured (#3310).
  8864. duration_unmeasured=bool(data.get("_reconciled")),
  8865. # The real end of a print stopped while its printer was offline.
  8866. replaces_offline_stop=True,
  8867. )
  8868. await record_archive_wear(db, archive, run_entry)
  8869. await db.commit()
  8870. completed_run_id = run_entry.id
  8871. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8872. try:
  8873. from backend.app.core.database import run_with_retry
  8874. await run_with_retry(_write_run, label="print log entry")
  8875. except Exception as e:
  8876. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8877. await _publish_run_completed(completed_run_id, printer_id)
  8878. log_timing("Print log entry")
  8879. # Run slow operations as background tasks to avoid blocking the event loop
  8880. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8881. async def _background_energy_calculation():
  8882. """Calculate and save energy usage in background.
  8883. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8884. backend restart no longer loses per-print energy data).
  8885. """
  8886. try:
  8887. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8888. async with async_session() as db:
  8889. from backend.app.models.archive import PrintArchive
  8890. from backend.app.models.print_log import PrintLogEntry
  8891. from backend.app.services.print_log import energy_start_of
  8892. archive = await db.get(PrintArchive, archive_id)
  8893. if archive is None:
  8894. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8895. return
  8896. # The ended run's own start reading: the archive's is its
  8897. # latest start's, maybe another plate's on another printer.
  8898. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8899. start = energy_start_of(run_row, archive)
  8900. if start is None:
  8901. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8902. return
  8903. starting_kwh = start.kwh
  8904. candidates = await energy_plug_candidates(db, printer_id)
  8905. if not candidates:
  8906. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8907. return
  8908. # Same ordering as the start reading, so the delta below is
  8909. # against the counter that produced `starting_kwh` (#2859).
  8910. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8911. if selected is None:
  8912. logger.warning(
  8913. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8914. printer_id,
  8915. ", ".join(plug.name for plug in candidates),
  8916. )
  8917. return
  8918. plug, energy = selected
  8919. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8920. energy_used = round(energy["total"] - starting_kwh, 4)
  8921. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8922. if energy_used < 0:
  8923. logger.warning(
  8924. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8925. archive_id,
  8926. starting_kwh,
  8927. energy["total"],
  8928. )
  8929. return
  8930. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8931. # Each hour of the print at the price of that hour (#1251). If
  8932. # that fails, the last price known, as before, rather than no
  8933. # energy at all. Read first: the session may be unusable after.
  8934. last_price = await stored_price(db)
  8935. try:
  8936. energy_cost_value = round(
  8937. await print_energy_cost(
  8938. db,
  8939. plug_id=start.plug_id,
  8940. start_at=start.at,
  8941. start_kwh=starting_kwh,
  8942. start_price=start.price,
  8943. end_kwh=energy["total"],
  8944. end_plug_id=plug.id,
  8945. price_now=await current_price(db),
  8946. ),
  8947. 3,
  8948. )
  8949. except Exception as e:
  8950. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8951. energy_cost_value = round(energy_used * last_price, 3)
  8952. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8953. # reprint doesn't visually clobber the source archive's energy data
  8954. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8955. from sqlalchemy import func
  8956. existing_runs = await db.scalar(
  8957. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8958. )
  8959. if (existing_runs or 0) <= 1:
  8960. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8961. # we just wrote for THIS print. Either way it's the first run.
  8962. archive.energy_kwh = energy_used
  8963. archive.energy_cost = energy_cost_value
  8964. # The ended run's energy (write_log_entry above ran before this
  8965. # background task, so its energy fields are still NULL). With
  8966. # no run written, none: the archive's newest is another print's.
  8967. if run_row is not None:
  8968. run_row.energy_kwh = energy_used
  8969. run_row.energy_cost = energy_cost_value
  8970. await db.commit()
  8971. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8972. except Exception as e:
  8973. logger.warning("[ENERGY-BG] Failed: %s", e)
  8974. async def _background_finish_photo() -> str | None:
  8975. """Capture finish photo in background. Returns photo filename if captured."""
  8976. # #2547: set once this function has raised the plate itself (the
  8977. # timelapse path, where the moment producer returned without doing it).
  8978. # Declared out here so the `finally` can lower it again no matter where
  8979. # the capture below fails.
  8980. plate_restored_z: float | None = None
  8981. try:
  8982. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8983. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8984. # Read phase: settings + printer + archive in a short session, released
  8985. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8986. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8987. # tens of seconds; holding this session across it pinned one pooled
  8988. # connection idle-in-transaction per finishing print (issue #2572).
  8989. async with async_session() as db:
  8990. from backend.app.api.routes.settings import get_setting
  8991. from backend.app.models.archive import PrintArchive
  8992. from backend.app.models.printer import Printer
  8993. capture_enabled = await get_setting(db, "capture_finish_photo")
  8994. if capture_enabled is not None and capture_enabled.lower() != "true":
  8995. return None
  8996. if not archive_id:
  8997. return None
  8998. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8999. archive = (
  9000. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9001. ).scalar_one_or_none()
  9002. if not printer or not archive:
  9003. return None
  9004. import uuid
  9005. from datetime import datetime
  9006. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  9007. if not archive.file_path:
  9008. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  9009. archive_dir = resolve_archive_dir(archive)
  9010. photo_filename = None
  9011. # Prefer the timelapse last-frame source when a timelapse was
  9012. # recording — it captures the moment after the toolhead parks
  9013. # but before the bed drops, which the live-camera grab below
  9014. # would miss (#1397). Skipped for external cameras (those have
  9015. # their own framing and don't see a Bambu timelapse). Only
  9016. # runs when the USER explicitly enabled timelapse for this
  9017. # print — #1721 removed Bambuddy's force-on at dispatch
  9018. # because it caused per-layer nozzle parking on Smooth-mode
  9019. # slicer profiles.
  9020. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9021. printer.external_camera_enabled and printer.external_camera_url
  9022. )
  9023. timelapse_still_pending = False
  9024. if prefer_timelapse_source:
  9025. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9026. archive_id=archive_id,
  9027. archive_dir=archive_dir,
  9028. rotation=getattr(printer, "camera_rotation", 0),
  9029. run_id=completed_run_id,
  9030. )
  9031. # #1721: replacement framing path — on_finish_photo_moment
  9032. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9033. # parked, bed not yet dropped) and cached the JPEG bytes in
  9034. # _stage22_finish_frames. Consume them now so the saved photo
  9035. # has the better framing instead of the post-bed-drop angle
  9036. # the live-camera fallback below would give.
  9037. if not photo_filename:
  9038. # #1790: on the FINISH-state fallback path the producer
  9039. # task is dispatched back-to-back with this consumer, so
  9040. # a bare pop would race past with an empty result and
  9041. # the RTSP fallback below would collide with the
  9042. # producer's still-in-flight grab (single-client RTSP
  9043. # on Bambu printers). Wait for the producer to finish
  9044. # or give up before touching the cache.
  9045. #
  9046. # #2547: 20s was enough when the producer only ever grabbed a
  9047. # frame. It now also raises the plate first, which costs the
  9048. # settle window before the grab even starts — so the budget has
  9049. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9050. # under the notification's own photo wait below.
  9051. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9052. if in_flight is not None:
  9053. try:
  9054. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9055. except TimeoutError:
  9056. logger.warning(
  9057. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9058. printer_id,
  9059. )
  9060. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9061. if cached_frame:
  9062. # Already rotated by the producer (#2708) — rotating again
  9063. # here would undo the fix on the banked-frame path, whose
  9064. # bytes reach the cache having been rotated once already.
  9065. photos_dir = archive_dir / "photos"
  9066. photos_dir.mkdir(parents=True, exist_ok=True)
  9067. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9068. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9069. photo_path = photos_dir / photo_filename
  9070. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9071. logger.info(
  9072. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9073. photo_filename,
  9074. len(cached_frame),
  9075. )
  9076. # #2547: the timelapse path reaches the live grab below whenever the
  9077. # video hasn't landed in time — the documented usual outcome on
  9078. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9079. # returned early for those prints without raising the plate, so
  9080. # without this the photo that actually ships in the notification is
  9081. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9082. # asked us to fix. The archive still gets the better video frame
  9083. # later; this is about the image the user is sent.
  9084. #
  9085. # Gated on `timelapse_was_active` precisely because that is the
  9086. # condition under which the producer skipped. On every other path it
  9087. # has already raised and lowered the plate, and repeating that here
  9088. # would be a second pointless round trip.
  9089. if (
  9090. not photo_filename
  9091. and data.get("timelapse_was_active")
  9092. and not print_dispatch_context.end_gcode_injected(printer_id)
  9093. ):
  9094. try:
  9095. async with async_session() as db:
  9096. from backend.app.api.routes.settings import get_setting
  9097. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9098. if restore_setting is None or restore_setting.lower() == "true":
  9099. max_z = await _max_z_for_current_print(
  9100. printer_id, data, logger, bound_archive_id, notify_plate_id
  9101. )
  9102. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9103. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9104. plate_restored_z = max_z
  9105. except Exception as e:
  9106. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9107. # Fallback chain: external camera → buffered live frame →
  9108. # fresh RTSP capture. Only runs if the timelapse path above
  9109. # didn't already produce a photo.
  9110. # Chamber light for the live capture below (#1655).
  9111. async with camera_light(printer if not photo_filename else None):
  9112. if not photo_filename:
  9113. if printer.external_camera_enabled and printer.external_camera_url:
  9114. logger.info("[PHOTO-BG] Using external camera")
  9115. from backend.app.api.routes.camera import live_frame_for_capture
  9116. from backend.app.services.external_camera import capture_frame
  9117. # #2707: the second half of the finish-photo failure — the
  9118. # pre-capture and this fallback both collided with the live
  9119. # view. None here continues down the fallback chain.
  9120. defer, buffered = live_frame_for_capture(printer_id)
  9121. if defer:
  9122. frame_data = buffered
  9123. else:
  9124. frame_data = await capture_frame(
  9125. printer.external_camera_url,
  9126. printer.external_camera_type or "mjpeg",
  9127. snapshot_url=printer.external_camera_snapshot_url,
  9128. )
  9129. if frame_data:
  9130. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9131. photos_dir = archive_dir / "photos"
  9132. photos_dir.mkdir(parents=True, exist_ok=True)
  9133. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9134. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9135. photo_path = photos_dir / photo_filename
  9136. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9137. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9138. else:
  9139. # Check if camera stream is active - use buffered frame to avoid freeze
  9140. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9141. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9142. active_chamber_for_printer = [
  9143. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9144. ]
  9145. buffered_frame = get_buffered_frame(printer_id)
  9146. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9147. # Use frame from active stream
  9148. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9149. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9150. photos_dir = archive_dir / "photos"
  9151. photos_dir.mkdir(parents=True, exist_ok=True)
  9152. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9153. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9154. photo_path = photos_dir / photo_filename
  9155. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9156. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9157. else:
  9158. # No active stream - capture new frame
  9159. from backend.app.services.camera import capture_finish_photo
  9160. photo_filename = await capture_finish_photo(
  9161. printer_id=printer_id,
  9162. ip_address=printer.ip_address,
  9163. access_code=printer.access_code,
  9164. model=printer.model,
  9165. archive_dir=archive_dir,
  9166. rotation=getattr(printer, "camera_rotation", 0),
  9167. )
  9168. # Write phase: attach the photo in a fresh short-lived session.
  9169. if photo_filename:
  9170. async with async_session() as db:
  9171. from backend.app.models.archive import PrintArchive
  9172. from backend.app.services.print_log import add_run_photo, run_of
  9173. arch = await db.get(PrintArchive, archive_id)
  9174. # The ended print's own list takes it too: the archive's
  9175. # holds every print's.
  9176. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9177. if arch is not None:
  9178. photos = arch.photos or []
  9179. photos.append(photo_filename)
  9180. arch.photos = photos
  9181. add_run_photo(run, photo_filename)
  9182. await db.commit()
  9183. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9184. # The short wait above is bounded so a slow printer can't hold up
  9185. # the print-complete notification, which is what the caller is
  9186. # blocking on. When it ran out with the video still on its way,
  9187. # keep waiting off to the side and add the better frame to the
  9188. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9189. # users, whose videos routinely take minutes to transfer, never get
  9190. # the pre-bed-drop framing this path exists to provide.
  9191. #
  9192. # Spawned here rather than at the point the wait gave up: both this
  9193. # function and the upgrade do a read-modify-write on `photos`, and
  9194. # the live-camera fallback above can take tens of seconds. Starting
  9195. # the upgrade before that write means the two can interleave and one
  9196. # silently drops the other's entry, leaving a JPEG on disk that the
  9197. # gallery never lists.
  9198. if timelapse_still_pending:
  9199. from backend.app.services import archive_work
  9200. spawn_background_task(
  9201. archive_work.held_while(
  9202. archive_id,
  9203. _upgrade_finish_photo_from_timelapse(
  9204. archive_id,
  9205. archive_dir,
  9206. rotation=getattr(printer, "camera_rotation", 0),
  9207. run_id=completed_run_id,
  9208. ),
  9209. ),
  9210. name=f"finish-photo-upgrade-{archive_id}",
  9211. )
  9212. return photo_filename
  9213. except Exception as e:
  9214. logger.warning("[PHOTO-BG] Failed: %s", e)
  9215. return None
  9216. finally:
  9217. # #2547: we raised the plate, so we owe the move back down — even if
  9218. # the capture in between threw. Otherwise the user finds the print
  9219. # pinned under the nozzle.
  9220. if plate_restored_z is not None:
  9221. try:
  9222. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9223. except Exception as e:
  9224. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9225. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9226. # Photo capture task - result will be used by notifications
  9227. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9228. log_timing("Background tasks scheduled (energy, photo)")
  9229. # Also run smart plug, notifications, and maintenance as background tasks
  9230. print_status = data.get("status", "completed")
  9231. async def _background_smart_plug():
  9232. """Handle smart plug automation in background."""
  9233. try:
  9234. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9235. async with async_session() as db:
  9236. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9237. logger.info("[AUTO-OFF-BG] Completed")
  9238. except Exception as e:
  9239. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9240. async def _background_notifications(finish_photo_filename: str | None = None):
  9241. """Send print complete notifications in background."""
  9242. try:
  9243. logger.info(
  9244. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9245. )
  9246. async with async_session() as db:
  9247. from backend.app.models.archive import PrintArchive
  9248. from backend.app.models.printer import Printer
  9249. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9250. printer = result.scalar_one_or_none()
  9251. printer_name = printer.name if printer else f"Printer {printer_id}"
  9252. archive_data = None
  9253. if archive_id:
  9254. from backend.app.models.print_log import PrintLogEntry
  9255. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9256. archive = archive_result.scalar_one_or_none()
  9257. # The run that ended: the archive shows its latest, which
  9258. # with another plate of it printing elsewhere is not this.
  9259. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9260. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9261. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9262. if archive:
  9263. # Actual elapsed time from started_at/completed_at when both are
  9264. # populated (every terminal status sets completed_at after #1198).
  9265. # Falls back to None so the notification path can decide whether to
  9266. # render the slicer estimate as a last resort.
  9267. actual_time_seconds = None
  9268. # Unknown for a completion reconciled at reconnect: the
  9269. # print ended while the printer was offline and
  9270. # completed_at is the reconnect, so the gap would read
  9271. # as the duration -- 14 h for a night offline (DB-C9).
  9272. # An estimated end (#3310) gives the estimate.
  9273. if (
  9274. run_started
  9275. and run_completed
  9276. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9277. ):
  9278. elapsed = (run_completed - run_started).total_seconds()
  9279. if elapsed > 0:
  9280. actual_time_seconds = int(elapsed)
  9281. archive_data = {
  9282. "print_time_seconds": archive.print_time_seconds,
  9283. "actual_time_seconds": actual_time_seconds,
  9284. "actual_filament_grams": archive.filament_used_grams,
  9285. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9286. "created_by_id": archive.created_by_id,
  9287. }
  9288. # Scale filament usage for partial prints
  9289. if print_status != "completed" and archive.filament_used_grams:
  9290. progress = data.get("progress") or 0
  9291. scale = _partial_progress_scale(progress)
  9292. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9293. archive_data["progress"] = progress
  9294. # Pass per-slot data from archive.extra_data
  9295. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9296. slots = archive.extra_data["filament_slots"]
  9297. if print_status != "completed":
  9298. scale = _partial_progress_scale(data.get("progress"))
  9299. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9300. archive_data["filament_slots"] = slots
  9301. # Scope project-summed totals down to the plate that was
  9302. # actually printed — see _scope_notification_archive_data_to_plate
  9303. # for the why (#1785).
  9304. archive_data = _scope_notification_archive_data_to_plate(
  9305. archive_data,
  9306. archive.file_path,
  9307. notify_plate_id,
  9308. print_status,
  9309. data.get("progress"),
  9310. app_settings.base_dir,
  9311. )
  9312. # Enrich filament_grams from usage_results when archive has no 3MF data
  9313. if not archive_data.get("actual_filament_grams") and usage_results:
  9314. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9315. if total_from_usage > 0:
  9316. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9317. # Pass usage tracker results for AMS slot info in notifications
  9318. if usage_results:
  9319. archive_data["usage_results"] = usage_results
  9320. # Which archive and print it was (archive redesign).
  9321. archive_data["archive_id"] = archive_id
  9322. archive_data["run_id"] = completed_run_id
  9323. # Add finish photo URL and image bytes if available
  9324. if finish_photo_filename:
  9325. photo_url, photo_bytes = await _finish_photo_for_notification(
  9326. db, archive, archive_id, finish_photo_filename
  9327. )
  9328. if photo_url:
  9329. archive_data["finish_photo_url"] = photo_url
  9330. if photo_bytes:
  9331. archive_data["image_data"] = photo_bytes
  9332. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9333. await notification_service.on_print_complete(
  9334. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9335. )
  9336. else:
  9337. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9338. # Post-print outcome confirmation (#1898). Runs in this
  9339. # background task so the finish photo fetched above rides
  9340. # along with the prompt.
  9341. if print_status == "completed" and archive_id:
  9342. await _dispatch_outcome_confirmation_safely(
  9343. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9344. )
  9345. # Send user-specific email notification
  9346. if archive_data:
  9347. created_by_id = archive_data.get("created_by_id")
  9348. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9349. await _dispatch_user_print_email(
  9350. print_status,
  9351. created_by_id,
  9352. printer_name,
  9353. raw_filename,
  9354. db,
  9355. image_data=archive_data.get("image_data"),
  9356. finish_photo_url=archive_data.get("finish_photo_url"),
  9357. )
  9358. logger.info("[NOTIFY-BG] Completed")
  9359. except Exception as e:
  9360. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9361. async def _background_maintenance_check():
  9362. """Check for maintenance due in background."""
  9363. if print_status != "completed":
  9364. return
  9365. try:
  9366. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9367. async with async_session() as db:
  9368. from backend.app.models.printer import Printer
  9369. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9370. printer = result.scalar_one_or_none()
  9371. printer_name = printer.name if printer else f"Printer {printer_id}"
  9372. await ensure_default_types(db)
  9373. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9374. attention = [
  9375. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9376. ]
  9377. items_needing_attention = [
  9378. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9379. for item in attention
  9380. ]
  9381. if items_needing_attention:
  9382. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9383. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9384. # MQTT relay - publish maintenance alerts
  9385. for item in attention:
  9386. current_value, threshold, unit = maintenance_alert_values(item)
  9387. try:
  9388. await mqtt_relay.on_maintenance_alert(
  9389. printer_id=printer_id,
  9390. printer_name=printer_name,
  9391. maintenance_type=item.maintenance_type_name,
  9392. current_value=current_value,
  9393. threshold=threshold,
  9394. unit=unit,
  9395. )
  9396. except Exception:
  9397. pass # Don't fail if MQTT fails
  9398. else:
  9399. logger.info("[MAINT-BG] Completed (no items need attention)")
  9400. except Exception as e:
  9401. logger.warning("[MAINT-BG] Failed: %s", e)
  9402. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9403. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9404. # Notification task waits for photo capture to complete first (with timeout).
  9405. # When a timelapse was recording, photo sourcing polls the per-print
  9406. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9407. # carries the correct bed-up photo instead of falling through to the
  9408. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9409. #
  9410. # #2547: both budgets now have to cover a plate restore as well.
  9411. #
  9412. # Without timelapse, the wait is on the moment producer, which raises the
  9413. # plate before its grab — so this has to outlast that producer's own budget.
  9414. #
  9415. # With timelapse, the capture polls up to
  9416. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9417. # falls back to a live grab, which is the case that raises the plate. At the
  9418. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9419. # restore would have moved the plate for a photo nobody waited for.
  9420. photo_wait_timeout = (
  9421. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9422. if data.get("timelapse_was_active")
  9423. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9424. )
  9425. async def _photo_then_notify():
  9426. """Wait for photo capture, then send notification with photo URL."""
  9427. finish_photo = None
  9428. try:
  9429. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9430. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9431. except TimeoutError:
  9432. logger.warning(
  9433. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9434. photo_wait_timeout,
  9435. )
  9436. except Exception as e:
  9437. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9438. try:
  9439. await _background_notifications(finish_photo)
  9440. except Exception as e:
  9441. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9442. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9443. # Stitch external camera layer timelapse if session was active
  9444. print_status = data.get("status", "completed")
  9445. async def _background_layer_timelapse():
  9446. """Stitch layer timelapse and attach to archive."""
  9447. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9448. try:
  9449. if print_status == "completed":
  9450. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9451. # The run the frames belong to, read before the stitch: it can
  9452. # take long enough for the archive to start printing again.
  9453. run_started_at = None
  9454. if archive_id:
  9455. async with async_session() as db:
  9456. run_archive = await ArchiveService(db).get_archive(archive_id)
  9457. run_started_at = run_archive.started_at if run_archive else None
  9458. timelapse_path = await tl_complete(printer_id)
  9459. if timelapse_path and archive_id:
  9460. await _attach_layer_timelapse(
  9461. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9462. )
  9463. elif timelapse_path:
  9464. # Timelapse created but no archive - just clean up
  9465. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9466. else:
  9467. # Print failed or cancelled - cancel timelapse session
  9468. cancel_session(printer_id)
  9469. logger.info(
  9470. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9471. )
  9472. except Exception as e:
  9473. logger.warning("[LAYER-TL] Failed: %s", e)
  9474. # A completed print's session left _active_sessions when its stitch
  9475. # began: the one there now belongs to the next print, which may have
  9476. # started during the stitch, and must not lose its frames.
  9477. if print_status != "completed":
  9478. try:
  9479. cancel_session(printer_id)
  9480. except Exception:
  9481. pass # Best-effort timelapse session cancellation on error
  9482. from backend.app.services import archive_work
  9483. # Held through the stitch, which can take longer than a merge waits after
  9484. # a print (archive redesign P2).
  9485. layer_timelapse = _background_layer_timelapse()
  9486. if archive_id:
  9487. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9488. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9489. log_timing("All background tasks scheduled")
  9490. # Auto-scan for timelapse if recording was active during the print
  9491. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9492. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9493. # Schedule timelapse scan as background task with retries
  9494. # The printer needs time to encode the video after print completion
  9495. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9496. log_timing("Timelapse scan scheduled")
  9497. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9498. # AMS sensor history recording
  9499. _ams_history_task: asyncio.Task | None = None
  9500. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9501. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9502. def _retention_days(stored: str | None, default: int) -> int:
  9503. """A history retention setting as days to keep: at least 1, the default
  9504. when unset or unreadable. A stored 0 or less (the API took one before it
  9505. had a minimum) would put the cutoff at now and delete all history."""
  9506. try:
  9507. return max(1, int(stored)) if stored is not None else default
  9508. except (TypeError, ValueError):
  9509. return default
  9510. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9511. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9512. _ams_alarm_cooldown: dict[str, datetime] = {}
  9513. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9514. # (printer_id, ams_id) already reported as sending the drop index and no
  9515. # percentage. Logged once each so a supported printer that turns out to do this
  9516. # shows up in a support bundle rather than as a user wondering where the
  9517. # humidity reading went -- see the note at the read site below (#3140).
  9518. _ams_index_only_logged: set[tuple[int, int]] = set()
  9519. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9520. """Temperature at which the AMS alarm fires, falling back to the display band.
  9521. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9522. when a notification was sent as well, which is why a room above it made the
  9523. alarm fire once an hour for as long as the weather lasted -- and the only way
  9524. to stop that was to raise the display band and lose the colour that says the
  9525. unit is warm (#2905).
  9526. Unset resolves to the fair threshold, so an install that never sets one is
  9527. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9528. so that arrives here as a string and is handled by the same branch as any
  9529. other unparseable value -- there is no separate sentinel to keep in sync.
  9530. A non-positive value is refused rather than honoured: zero would alarm
  9531. permanently, and it is far more likely to be a cleared field than a
  9532. deliberate choice.
  9533. """
  9534. if raw_alarm_value is None:
  9535. return fair_threshold
  9536. try:
  9537. value = float(raw_alarm_value)
  9538. except (TypeError, ValueError):
  9539. return fair_threshold
  9540. if not math.isfinite(value) or value <= 0:
  9541. return fair_threshold
  9542. return value
  9543. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9544. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9545. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9546. # partway through a cool-down would otherwise resume alarming about heat the
  9547. # user asked for — the same internal-timestamp-row pattern as
  9548. # support.py's debug_logging_enabled_at.
  9549. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9550. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9551. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9552. # matters when it never does.
  9553. AMS_DRYING_GRACE_MINUTES = 120
  9554. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9555. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9556. Anything older than the grace cap would expire on its next visit anyway, so
  9557. discarding it here costs nothing and stops rows for deleted printers from
  9558. accumulating.
  9559. Stamps ahead of now get two defences, because a box whose clock jumps
  9560. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9561. ones are discarded outright, and the rest are clamped to now. Without the
  9562. clamp the cap would measure from a moment that has not happened yet and hold
  9563. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9564. after a clock jump is a far better failure than an alarm silently disabled
  9565. for hours.
  9566. """
  9567. from backend.app.models.settings import Settings
  9568. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9569. setting = result.scalar_one_or_none()
  9570. if not setting or not setting.value:
  9571. return {}
  9572. try:
  9573. raw = json.loads(setting.value)
  9574. except (ValueError, TypeError):
  9575. return {} # Corrupted row → no latch, alarms behave as they did before
  9576. if not isinstance(raw, dict):
  9577. return {}
  9578. now = datetime.now(timezone.utc)
  9579. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9580. latch: dict[str, datetime] = {}
  9581. for key, value in raw.items():
  9582. try:
  9583. stamp = datetime.fromisoformat(str(value))
  9584. except (ValueError, TypeError):
  9585. continue
  9586. if stamp.tzinfo is None:
  9587. stamp = stamp.replace(tzinfo=timezone.utc)
  9588. if not (now - window <= stamp <= now + window):
  9589. continue
  9590. # Nothing may sit in the future: suppression is measured as now minus
  9591. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9592. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9593. latch[str(key)] = min(stamp, now)
  9594. return latch
  9595. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9596. """Persist the latch, writing only when it actually changed.
  9597. Adds the session change but does not commit — the caller's own commit
  9598. carries it, so the latch lands in the same transaction as the sensor rows
  9599. that produced it.
  9600. """
  9601. from backend.app.models.settings import Settings
  9602. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9603. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9604. setting = result.scalar_one_or_none()
  9605. if setting is None:
  9606. # Don't create the row on installs that never dry anything.
  9607. if payload != "{}":
  9608. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9609. elif setting.value != payload:
  9610. setting.value = payload
  9611. def _ams_has_filament(ams_data: dict) -> bool:
  9612. """True if this AMS unit has at least one tray slot holding filament.
  9613. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9614. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9615. still report sensor readings, but those readings are ambient and not
  9616. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9617. humidity/temperature alarms on this check so empty units don't generate
  9618. hourly noise. Sensor history still records regardless so the UI charts
  9619. stay continuous.
  9620. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9621. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9622. """
  9623. bits = ams_data.get("tray_exist_bits")
  9624. if isinstance(bits, str) and bits.strip():
  9625. try:
  9626. return int(bits, 16) > 0
  9627. except ValueError:
  9628. pass
  9629. trays = ams_data.get("tray")
  9630. if isinstance(trays, list):
  9631. return any(
  9632. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9633. )
  9634. return False
  9635. async def record_ams_history():
  9636. """Background task to record AMS humidity and temperature data."""
  9637. logger = logging.getLogger(__name__)
  9638. # Wait a short time for MQTT connections to establish on startup
  9639. await asyncio.sleep(10)
  9640. while True:
  9641. try:
  9642. from backend.app.models.ams_history import AMSSensorHistory
  9643. from backend.app.models.printer import Printer
  9644. from backend.app.models.settings import Settings
  9645. async with async_session() as db:
  9646. # Get all active printers
  9647. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9648. printers = result.scalars().all()
  9649. # Get alarm thresholds from settings
  9650. humidity_threshold = 60.0 # Default: fair threshold
  9651. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9652. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9653. setting = result.scalar_one_or_none()
  9654. if setting:
  9655. try:
  9656. humidity_threshold = float(setting.value)
  9657. except (ValueError, TypeError):
  9658. pass # Keep default threshold if stored value is invalid
  9659. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9660. setting = result.scalar_one_or_none()
  9661. if setting:
  9662. try:
  9663. temp_fair_threshold = float(setting.value)
  9664. except (ValueError, TypeError):
  9665. pass # Keep default threshold if stored value is invalid
  9666. # The alarm gets its own threshold, seeded from the resolved fair
  9667. # value so an install that has never set one behaves exactly as
  9668. # it did before (#2905). ams_temp_fair decides when the card turns
  9669. # amber; 35 C is a reasonable place to change a colour and not a
  9670. # reasonable place to page someone. A room above it makes the
  9671. # alarm fire once an hour for as long as the weather lasts, and
  9672. # the only way to stop it was to raise the display band and lose
  9673. # the colour that says the unit is warm.
  9674. #
  9675. # An unset value is stored as the literal "None", which the except
  9676. # below swallows the same way it swallows garbage -- so the
  9677. # fallback costs nothing and needs no sentinel of its own.
  9678. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9679. setting = result.scalar_one_or_none()
  9680. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9681. temp_fair_threshold, setting.value if setting else None
  9682. )
  9683. # Per-filament humidity threshold overrides (#1605) — resolved
  9684. # per-AMS below from the loaded tray types. Reuses the same
  9685. # resolver as the auto-drying scheduler so behavior stays in
  9686. # lockstep across both consumers.
  9687. from backend.app.services.print_scheduler import PrintScheduler
  9688. per_type_humidity_thresholds: dict[str, int] = {}
  9689. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9690. setting = result.scalar_one_or_none()
  9691. if setting and setting.value:
  9692. try:
  9693. raw = json.loads(setting.value)
  9694. if isinstance(raw, dict):
  9695. for k, v in raw.items():
  9696. try:
  9697. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9698. v
  9699. )
  9700. except (TypeError, ValueError):
  9701. continue
  9702. except (ValueError, TypeError):
  9703. pass # Invalid JSON → no overrides, fall through to global threshold
  9704. # Per-AMS drying latch (#1802), loaded once per pass and written
  9705. # back below only if a unit changed it.
  9706. drying_latch = await _load_ams_drying_latch(db)
  9707. drying_latch_before = dict(drying_latch)
  9708. recorded_count = 0
  9709. for printer in printers:
  9710. # Get current state from printer manager
  9711. state = printer_manager.get_status(printer.id)
  9712. if not state or not state.connected or not state.raw_data:
  9713. continue # Skip disconnected printers - don't use stale data
  9714. raw_data = state.raw_data
  9715. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9716. continue
  9717. # Record data for each AMS unit
  9718. for ams_data in raw_data["ams"]:
  9719. ams_id = int(ams_data.get("id", 0))
  9720. # Percentage only. The 1-5 index is inverted, so
  9721. # charting it as a percentage drew the wettest units as
  9722. # the driest (#3140); a unit that reports no percentage
  9723. # leaves a gap in the chart instead. See
  9724. # utils/ams_humidity.
  9725. humidity = ams_humidity_percent(ams_data)
  9726. # No supported printer is known to send the index
  9727. # alone -- the report came from unsupported firmware,
  9728. # and no install has been seen using the old fallback.
  9729. # "Known" is doing work there, so say so once per unit:
  9730. # the alternative is a silent blank card.
  9731. if humidity is None and ams_data.get("humidity") is not None:
  9732. unit_key = (printer.id, ams_id)
  9733. if unit_key not in _ams_index_only_logged:
  9734. _ams_index_only_logged.add(unit_key)
  9735. logger.info(
  9736. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9737. "percentage. The index is inverted and is not shown as a percentage "
  9738. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9739. "Please report this with the printer and AMS firmware versions.",
  9740. printer.name,
  9741. ams_id,
  9742. )
  9743. # Get temperature
  9744. temperature = None
  9745. temp_str = ams_data.get("temp")
  9746. if temp_str is not None:
  9747. try:
  9748. temperature = float(temp_str)
  9749. except (ValueError, TypeError):
  9750. pass # Skip unparseable temperature value
  9751. # Skip if no data
  9752. if humidity is None and temperature is None:
  9753. continue
  9754. # Record the data point
  9755. history = AMSSensorHistory(
  9756. printer_id=printer.id,
  9757. ams_id=ams_id,
  9758. humidity=humidity,
  9759. # Both columns hold the same reading now that the
  9760. # index can no longer reach ``humidity``. Writing it
  9761. # through the same value also stops a genuine 0%
  9762. # from being stored as NULL, which the old truthiness
  9763. # test did.
  9764. humidity_raw=humidity,
  9765. temperature=temperature,
  9766. )
  9767. db.add(history)
  9768. recorded_count += 1
  9769. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9770. is_ams_ht = ams_id >= 128
  9771. if is_ams_ht:
  9772. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9773. else:
  9774. ams_label = f"AMS-{chr(65 + ams_id)}"
  9775. # Skip alarm dispatch for empty AMS units — humidity /
  9776. # temperature readings are ambient with no filament to
  9777. # protect, and the hourly notification just becomes
  9778. # noise. Sensor history was already recorded above so
  9779. # the UI charts stay continuous (#1619). Per-AMS check
  9780. # so a multi-AMS setup with one loaded + one empty
  9781. # still alarms on the loaded unit.
  9782. if not _ams_has_filament(ams_data):
  9783. continue
  9784. # Resolve per-filament humidity threshold for this AMS
  9785. # unit (#1605). Falls back to the global ams_humidity_fair
  9786. # when no per-type overrides are configured.
  9787. trays = ams_data.get("tray", []) or []
  9788. effective_humidity_threshold = float(
  9789. PrintScheduler.resolve_humidity_threshold(
  9790. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9791. )
  9792. )
  9793. # Check humidity alarm (only if above threshold)
  9794. if humidity is not None and humidity > effective_humidity_threshold:
  9795. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9796. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9797. now = datetime.now(timezone.utc)
  9798. if (
  9799. last_alarm is None
  9800. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9801. ):
  9802. _ams_alarm_cooldown[cooldown_key] = now
  9803. logger.info(
  9804. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9805. )
  9806. try:
  9807. # Call different notification method based on AMS type
  9808. if is_ams_ht:
  9809. await notification_service.on_ams_ht_humidity_high(
  9810. printer.id,
  9811. printer.name,
  9812. ams_label,
  9813. humidity,
  9814. effective_humidity_threshold,
  9815. db,
  9816. )
  9817. else:
  9818. await notification_service.on_ams_humidity_high(
  9819. printer.id,
  9820. printer.name,
  9821. ams_label,
  9822. humidity,
  9823. effective_humidity_threshold,
  9824. db,
  9825. )
  9826. except Exception as e:
  9827. logger.warning("Failed to send humidity alarm: %s", e)
  9828. # A drying cycle heats the unit far past ams_temp_fair on
  9829. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9830. # AMS-HT, against a 35 C default — so the alarm fired
  9831. # once an hour for the whole cycle and kept firing while
  9832. # the unit cooled back down (#1802). Latch on the
  9833. # firmware's own drying state and hold until the reading
  9834. # returns to normal. Humidity is deliberately left alone:
  9835. # it falls during drying, which is the whole point.
  9836. latch_key = f"{printer.id}:{ams_id}"
  9837. # The latch releases at `threshold`, so it takes the alarm
  9838. # number too. Handing it the display band would strand the
  9839. # latch on any unit that settles back above it -- a room
  9840. # where the AMS rests at 37.7 C never returns under a 35 C
  9841. # band, so the latch could only expire on the grace cap
  9842. # rather than releasing when the unit had actually cooled.
  9843. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9844. drying_active=is_drying_active(ams_data),
  9845. temperature=temperature,
  9846. threshold=temp_alarm_threshold,
  9847. latched_at=drying_latch.get(latch_key),
  9848. now=datetime.now(timezone.utc),
  9849. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9850. )
  9851. if new_latch is None:
  9852. drying_latch.pop(latch_key, None)
  9853. else:
  9854. drying_latch[latch_key] = new_latch
  9855. # Check temperature alarm (only if above threshold)
  9856. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9857. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9858. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9859. now = datetime.now(timezone.utc)
  9860. if (
  9861. last_alarm is None
  9862. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9863. ):
  9864. _ams_alarm_cooldown[cooldown_key] = now
  9865. logger.info(
  9866. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9867. f"{temperature}°C > {temp_alarm_threshold}°C"
  9868. )
  9869. try:
  9870. # Call different notification method based on AMS type
  9871. if is_ams_ht:
  9872. # The reported threshold has to be the one
  9873. # that fired, or the message says "> 35 °C"
  9874. # while firing at 45.
  9875. await notification_service.on_ams_ht_temperature_high(
  9876. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9877. )
  9878. else:
  9879. await notification_service.on_ams_temperature_high(
  9880. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9881. )
  9882. except Exception as e:
  9883. logger.warning("Failed to send temperature alarm: %s", e)
  9884. if drying_latch != drying_latch_before:
  9885. await _save_ams_drying_latch(db, drying_latch)
  9886. await db.commit()
  9887. if recorded_count > 0:
  9888. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9889. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9890. global _ams_cleanup_counter
  9891. _ams_cleanup_counter += 1
  9892. if _ams_cleanup_counter >= 288:
  9893. _ams_cleanup_counter = 0
  9894. # Get retention days from settings
  9895. from backend.app.models.settings import Settings
  9896. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9897. setting = result.scalar_one_or_none()
  9898. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9899. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9900. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9901. await db.commit()
  9902. if result.rowcount > 0:
  9903. logger.info(
  9904. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9905. )
  9906. # Wait until next recording interval
  9907. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9908. except asyncio.CancelledError:
  9909. break
  9910. except Exception as e:
  9911. logger.warning("AMS history recording failed: %s", e)
  9912. await asyncio.sleep(60) # Wait a bit before retrying
  9913. def start_ams_history_recording():
  9914. """Start the AMS history recording background task."""
  9915. global _ams_history_task
  9916. if _ams_history_task is None:
  9917. _ams_history_task = asyncio.create_task(record_ams_history())
  9918. logging.getLogger(__name__).info("AMS history recording started")
  9919. def stop_ams_history_recording():
  9920. """Stop the AMS history recording background task."""
  9921. global _ams_history_task
  9922. if _ams_history_task:
  9923. _ams_history_task.cancel()
  9924. _ams_history_task = None
  9925. logging.getLogger(__name__).info("AMS history recording stopped")
  9926. # Printer sensor history recording (nozzle / bed / chamber)
  9927. _printer_sensor_history_task: asyncio.Task | None = None
  9928. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9929. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9930. _printer_sensor_cleanup_counter = 0
  9931. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9932. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9933. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9934. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9935. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9936. _SENSOR_TARGET_KEYS = {
  9937. "nozzle": "nozzle_target",
  9938. "nozzle_2": "nozzle_2_target",
  9939. "bed": "bed_target",
  9940. "chamber": "chamber_target",
  9941. }
  9942. async def record_printer_sensor_history():
  9943. """Background task to record nozzle / bed / chamber readings.
  9944. Pulls from `state.temperatures` (already normalised across all printer
  9945. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9946. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9947. """
  9948. logger = logging.getLogger(__name__)
  9949. await asyncio.sleep(10)
  9950. while True:
  9951. try:
  9952. from backend.app.models.printer import Printer
  9953. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9954. from backend.app.models.settings import Settings
  9955. async with async_session() as db:
  9956. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9957. printers = result.scalars().all()
  9958. recorded_count = 0
  9959. for printer in printers:
  9960. state = printer_manager.get_status(printer.id)
  9961. if not state or not state.connected:
  9962. continue
  9963. temps = getattr(state, "temperatures", None) or {}
  9964. if not isinstance(temps, dict):
  9965. continue
  9966. for kind in _SENSOR_KINDS:
  9967. if kind not in temps:
  9968. continue
  9969. try:
  9970. value = float(temps[kind])
  9971. except (ValueError, TypeError):
  9972. continue
  9973. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9974. target_val: float | None = None
  9975. if target_raw is not None:
  9976. try:
  9977. target_val = float(target_raw)
  9978. except (ValueError, TypeError):
  9979. target_val = None
  9980. db.add(
  9981. PrinterSensorHistory(
  9982. printer_id=printer.id,
  9983. sensor_kind=kind,
  9984. value=value,
  9985. target=target_val,
  9986. )
  9987. )
  9988. recorded_count += 1
  9989. await db.commit()
  9990. if recorded_count > 0:
  9991. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9992. # Periodic cleanup — once every ~24h at this interval.
  9993. global _printer_sensor_cleanup_counter
  9994. _printer_sensor_cleanup_counter += 1
  9995. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9996. if _printer_sensor_cleanup_counter >= cleanup_every:
  9997. _printer_sensor_cleanup_counter = 0
  9998. result = await db.execute(
  9999. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  10000. )
  10001. setting = result.scalar_one_or_none()
  10002. retention_days = _retention_days(
  10003. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  10004. )
  10005. cutoff = utcnow_naive() - timedelta(days=retention_days)
  10006. cleanup = await db.execute(
  10007. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  10008. )
  10009. await db.commit()
  10010. if cleanup.rowcount > 0:
  10011. logger.info(
  10012. "Cleaned up %s old printer sensor history entries (older than %s days)",
  10013. cleanup.rowcount,
  10014. retention_days,
  10015. )
  10016. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10017. except asyncio.CancelledError:
  10018. break
  10019. except Exception as e:
  10020. logger.warning("Printer sensor history recording failed: %s", e)
  10021. await asyncio.sleep(60)
  10022. def start_printer_sensor_history_recording():
  10023. global _printer_sensor_history_task
  10024. if _printer_sensor_history_task is None:
  10025. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10026. logging.getLogger(__name__).info("Printer sensor history recording started")
  10027. def stop_printer_sensor_history_recording():
  10028. global _printer_sensor_history_task
  10029. if _printer_sensor_history_task:
  10030. _printer_sensor_history_task.cancel()
  10031. _printer_sensor_history_task = None
  10032. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10033. # Printer runtime tracking
  10034. _runtime_tracking_task: asyncio.Task | None = None
  10035. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10036. # Printers the runtime tracker has seen connected since startup. One of them
  10037. # going offline clears its timestamp, so the time it was away is not counted
  10038. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10039. # connecting after a restart -- keeps it for a grace period: a print that ran
  10040. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10041. _runtime_seen_connected: set[int] = set()
  10042. # A printer never seen connected this long after the tracker started is
  10043. # offline, not still connecting: its stored timestamp predates a gap too.
  10044. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10045. async def track_printer_runtime():
  10046. """Background task to track printer active runtime (RUNNING state only).
  10047. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10048. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10049. which track mechanical wear. Pause time has no motion and no wear, so
  10050. counting it inflates maintenance warnings (#1521).
  10051. """
  10052. logger = logging.getLogger(__name__)
  10053. # Wait for MQTT connections to establish on startup
  10054. await asyncio.sleep(15)
  10055. started = time.monotonic()
  10056. while True:
  10057. try:
  10058. from backend.app.models.printer import Printer
  10059. # Fetch printer IDs in a short-lived read-only session
  10060. async with async_session() as db:
  10061. result = await db.execute(
  10062. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10063. Printer.is_active.is_(True)
  10064. )
  10065. )
  10066. printer_rows = result.all()
  10067. now = datetime.now(timezone.utc)
  10068. updated_count = 0
  10069. # Update each printer in its own short session to minimise write-lock
  10070. # hold time and avoid blocking critical commits like queue status
  10071. # updates (#897).
  10072. for pid, pname, runtime_secs, last_update in printer_rows:
  10073. state = printer_manager.get_status(pid)
  10074. if not state:
  10075. logger.debug("[%s] Runtime tracking: no state available", pname)
  10076. continue
  10077. if not state.connected:
  10078. logger.debug("[%s] Runtime tracking: not connected", pname)
  10079. offline = pid in _runtime_seen_connected or (
  10080. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10081. )
  10082. if offline and last_update is not None:
  10083. try:
  10084. async with async_session() as db:
  10085. printer = await db.get(Printer, pid)
  10086. if printer:
  10087. printer.last_runtime_update = None
  10088. await db.commit()
  10089. except Exception as e:
  10090. # Still marked: the next offline tick tries again.
  10091. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10092. continue
  10093. _runtime_seen_connected.discard(pid)
  10094. continue
  10095. _runtime_seen_connected.add(pid)
  10096. needs_commit = False
  10097. new_runtime = runtime_secs
  10098. new_last_update = last_update
  10099. if state.state == "RUNNING":
  10100. if last_update:
  10101. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10102. elapsed = (now - lu).total_seconds()
  10103. if elapsed > 0:
  10104. new_runtime = runtime_secs + int(elapsed)
  10105. updated_count += 1
  10106. needs_commit = True
  10107. logger.debug(
  10108. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10109. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10110. )
  10111. else:
  10112. needs_commit = True
  10113. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10114. new_last_update = now
  10115. else:
  10116. if last_update is not None:
  10117. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10118. new_last_update = None
  10119. needs_commit = True
  10120. if needs_commit:
  10121. try:
  10122. async with async_session() as db:
  10123. result = await db.execute(select(Printer).where(Printer.id == pid))
  10124. printer = result.scalar_one_or_none()
  10125. if printer:
  10126. printer.runtime_seconds = new_runtime
  10127. printer.last_runtime_update = new_last_update
  10128. await db.commit()
  10129. except Exception as e:
  10130. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10131. if updated_count > 0:
  10132. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10133. except asyncio.CancelledError:
  10134. logger.info("Runtime tracking cancelled")
  10135. break
  10136. except Exception as e:
  10137. logger.warning("Runtime tracking failed: %s", e)
  10138. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10139. def start_runtime_tracking():
  10140. """Start the printer runtime tracking background task."""
  10141. global _runtime_tracking_task
  10142. if _runtime_tracking_task is None:
  10143. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10144. logging.getLogger(__name__).info("Printer runtime tracking started")
  10145. def stop_runtime_tracking():
  10146. """Stop the printer runtime tracking background task."""
  10147. global _runtime_tracking_task
  10148. if _runtime_tracking_task:
  10149. _runtime_tracking_task.cancel()
  10150. _runtime_tracking_task = None
  10151. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10152. # SpoolBuddy device watchdog
  10153. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10154. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10155. async def _spoolbuddy_watchdog_loop():
  10156. """Periodic check for SpoolBuddy devices that have gone offline."""
  10157. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10158. while True:
  10159. try:
  10160. await spoolbuddy_watchdog()
  10161. except asyncio.CancelledError:
  10162. break
  10163. except Exception as e:
  10164. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10165. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10166. def start_spoolbuddy_watchdog():
  10167. global _spoolbuddy_watchdog_task
  10168. if _spoolbuddy_watchdog_task is None:
  10169. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10170. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10171. def stop_spoolbuddy_watchdog():
  10172. global _spoolbuddy_watchdog_task
  10173. if _spoolbuddy_watchdog_task:
  10174. _spoolbuddy_watchdog_task.cancel()
  10175. _spoolbuddy_watchdog_task = None
  10176. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10177. # Dead-MQTT-session recovery
  10178. #
  10179. # check_staleness() covers the "connected but silent" half-broken session. It
  10180. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10181. # is the only thing left watching at that point. When paho stops making
  10182. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10183. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10184. # offline with the UI open the whole time, recovered only when something
  10185. # happened to nudge it.
  10186. #
  10187. # This loop is that backstop. It only touches printers that had a working
  10188. # session and lost it, and only when the MQTT port still answers — a printer
  10189. # that is simply switched off is left to paho, since rebuilding a client
  10190. # against an unreachable host achieves nothing and would fill the log every
  10191. # night.
  10192. _connection_watchdog_task: asyncio.Task | None = None
  10193. CONNECTION_WATCHDOG_INTERVAL = 60
  10194. # How long a printer must have been silent before we stop trusting paho.
  10195. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10196. # so a session that is recovering on its own is never interrupted.
  10197. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10198. # Per-printer floor between rebuild attempts.
  10199. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10200. _connection_watchdog_last_attempt: dict[int, float] = {}
  10201. async def _recover_dead_printer_sessions() -> int:
  10202. """Rebuild MQTT clients that have been offline too long to still be trying.
  10203. Returns the number of printers a rebuild was attempted for (for tests and
  10204. for the caller's logging). Never raises: one unreachable printer must not
  10205. stop the sweep for the rest of the farm.
  10206. """
  10207. logger = logging.getLogger(__name__)
  10208. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10209. now = time.monotonic()
  10210. recovered = 0
  10211. for printer_id, client in list(printer_manager._clients.items()):
  10212. try:
  10213. if client.state.connected:
  10214. _connection_watchdog_last_attempt.pop(printer_id, None)
  10215. continue
  10216. # Time since the last inbound message is the age of the last known
  10217. # good session — no extra bookkeeping needed, and it is the same
  10218. # clock is_stale() reads. 0 means this client has never had one:
  10219. # that is the initial-connect path, where paho retrying is the
  10220. # correct and only behaviour, so leave it be.
  10221. last_msg = client._last_message_time
  10222. if not last_msg:
  10223. continue
  10224. offline_for = time.time() - last_msg
  10225. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10226. continue
  10227. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10228. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10229. continue
  10230. if not await check_port(client.ip_address, PORT_MQTT):
  10231. # Switched off, unplugged, or off the network. Paho's retry is
  10232. # the right handler; say so at debug level and move on.
  10233. logger.debug(
  10234. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10235. "— leaving the reconnect to paho",
  10236. printer_id,
  10237. offline_for,
  10238. )
  10239. _connection_watchdog_last_attempt[printer_id] = now
  10240. continue
  10241. _connection_watchdog_last_attempt[printer_id] = now
  10242. recovered += 1
  10243. logger.warning(
  10244. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10245. "rebuilding the client with a fresh session (last connect error: %s)",
  10246. printer_id,
  10247. offline_for,
  10248. PORT_MQTT,
  10249. client.last_connect_error or "none recorded",
  10250. )
  10251. # Async context, so this takes the hard-reset path: fresh client_id,
  10252. # paho's QoS 1 queue dropped. That matters — a project_file left
  10253. # unacked on the dead session would otherwise replay into the new
  10254. # one and trip 0500_4003 on the printer (#1136).
  10255. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10256. except Exception as e:
  10257. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10258. return recovered
  10259. async def _connection_watchdog_loop():
  10260. logger = logging.getLogger(__name__)
  10261. # Let the initial connects settle before judging anyone offline.
  10262. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10263. while True:
  10264. try:
  10265. await _recover_dead_printer_sessions()
  10266. except asyncio.CancelledError:
  10267. break
  10268. except Exception as e:
  10269. logger.warning("Connection watchdog sweep failed: %s", e)
  10270. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10271. def start_connection_watchdog():
  10272. global _connection_watchdog_task
  10273. if _connection_watchdog_task is None:
  10274. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10275. logging.getLogger(__name__).info("Printer connection watchdog started")
  10276. def stop_connection_watchdog():
  10277. global _connection_watchdog_task
  10278. if _connection_watchdog_task:
  10279. _connection_watchdog_task.cancel()
  10280. _connection_watchdog_task = None
  10281. _connection_watchdog_last_attempt.clear()
  10282. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10283. # Camera stream orphan cleanup
  10284. _camera_cleanup_task: asyncio.Task | None = None
  10285. CAMERA_CLEANUP_INTERVAL = 60
  10286. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10287. # kept frames of a failed stitch go after a day, not at the next restart.
  10288. TIMELAPSE_CLEANUP_EVERY = 60
  10289. async def _camera_cleanup_loop():
  10290. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10291. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10292. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10293. rounds = 0
  10294. while True:
  10295. try:
  10296. rounds += 1
  10297. await cleanup_orphaned_streams()
  10298. except asyncio.CancelledError:
  10299. break
  10300. except Exception as e:
  10301. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10302. try:
  10303. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10304. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10305. except asyncio.CancelledError:
  10306. break
  10307. except Exception as e:
  10308. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10309. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10310. def start_camera_cleanup():
  10311. global _camera_cleanup_task
  10312. if _camera_cleanup_task is None:
  10313. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10314. logging.getLogger(__name__).info("Camera stream cleanup started")
  10315. def stop_camera_cleanup():
  10316. global _camera_cleanup_task
  10317. if _camera_cleanup_task:
  10318. _camera_cleanup_task.cancel()
  10319. _camera_cleanup_task = None
  10320. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10321. # ---------------------------------------------------------------------------
  10322. # Expected-print TTL eviction
  10323. # ---------------------------------------------------------------------------
  10324. def _evict_stale_expected_prints() -> None:
  10325. """Remove entries from _expected_prints / _expected_print_creators that are
  10326. older than _EXPECTED_PRINT_TTL_SECONDS.
  10327. This prevents unbounded growth when a print is registered (via
  10328. register_expected_print) but on_print_start never fires — e.g. because the
  10329. printer disconnects, the app restarts, or the print is started directly from
  10330. the printer panel without going through the queue.
  10331. """
  10332. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10333. # (e.g. NTP sync, DST changes).
  10334. # A print that ended without its archive being found at completion leaves
  10335. # its id here; only running prints are owned.
  10336. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10337. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10338. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10339. if not stale_keys:
  10340. return
  10341. evicted: set[tuple[int, int]] = set()
  10342. for key in stale_keys:
  10343. archive_id = _expected_prints.pop(key, None)
  10344. if archive_id is not None:
  10345. evicted.add((key[0], archive_id))
  10346. _expected_print_creators.pop(key, None)
  10347. _expected_print_registered_at.pop(key, None)
  10348. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10349. # that have no remaining live keys in _expected_prints (all variants
  10350. # were just evicted) and are not printing right now. Print start pops
  10351. # only the names the printer reported, so the "<base>.gcode" variant
  10352. # outlives it; without the printing check its eviction two hours after
  10353. # dispatch threw away a running print's plate, AMS mapping and cost
  10354. # centre, which completion still reads (#3275).
  10355. for printer_id, archive_id in evicted:
  10356. if not _expected_or_printing_here(printer_id, archive_id):
  10357. _drop_dispatch(printer_id, archive_id)
  10358. logging.getLogger(__name__).info(
  10359. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10360. )
  10361. async def _expected_prints_cleanup_loop() -> None:
  10362. """Background task: periodically evict stale expected-print entries."""
  10363. while True:
  10364. try:
  10365. _evict_stale_expected_prints()
  10366. except asyncio.CancelledError:
  10367. raise
  10368. except Exception as e:
  10369. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10370. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10371. def start_expected_prints_cleanup() -> None:
  10372. global _expected_prints_cleanup_task
  10373. if _expected_prints_cleanup_task is None:
  10374. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10375. logging.getLogger(__name__).info("Expected prints cleanup started")
  10376. def stop_expected_prints_cleanup() -> None:
  10377. global _expected_prints_cleanup_task
  10378. if _expected_prints_cleanup_task:
  10379. _expected_prints_cleanup_task.cancel()
  10380. _expected_prints_cleanup_task = None
  10381. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10382. # ---------------------------------------------------------------------------
  10383. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10384. # ---------------------------------------------------------------------------
  10385. _auth_cleanup_task: asyncio.Task | None = None
  10386. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10387. async def _run_auth_cleanup() -> None:
  10388. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10389. from backend.app.core.database import async_session
  10390. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10391. from backend.app.models.user_totp import UserTOTP
  10392. now = datetime.now(timezone.utc)
  10393. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10394. try:
  10395. async with async_session() as db:
  10396. stale_cutoff = now - timedelta(hours=1)
  10397. result = await db.execute(
  10398. select(UserTOTP).where(
  10399. UserTOTP.is_enabled.is_(False),
  10400. UserTOTP.created_at < stale_cutoff,
  10401. )
  10402. )
  10403. stale_records = result.scalars().all()
  10404. if stale_records:
  10405. for rec in stale_records:
  10406. await db.delete(rec)
  10407. await db.commit()
  10408. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10409. except Exception as e:
  10410. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10411. # Remove expired revoked-JTI entries (they are no longer needed once the
  10412. # original token's exp has passed — the token would be rejected by JWT
  10413. # signature verification regardless).
  10414. try:
  10415. async with async_session() as db:
  10416. await db.execute(
  10417. delete(AuthEphemeralToken).where(
  10418. AuthEphemeralToken.token_type == "revoked_jti",
  10419. AuthEphemeralToken.expires_at < now,
  10420. )
  10421. )
  10422. await db.commit()
  10423. except Exception as e:
  10424. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10425. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10426. # Events outside this window can never affect rate-limit decisions — they only
  10427. # consume DB space. Use the same window constant as the rate limiter so the
  10428. # two are always in sync.
  10429. try:
  10430. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10431. async with async_session() as db:
  10432. await db.execute(
  10433. delete(AuthRateLimitEvent).where(
  10434. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10435. )
  10436. )
  10437. await db.commit()
  10438. except Exception as e:
  10439. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10440. async def _auth_cleanup_loop() -> None:
  10441. """Periodic background task: run auth cleanup every hour."""
  10442. while True:
  10443. try:
  10444. await _run_auth_cleanup()
  10445. except asyncio.CancelledError:
  10446. break
  10447. except Exception as e:
  10448. logging.warning("Auth cleanup loop error: %s", e)
  10449. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10450. def start_auth_cleanup() -> None:
  10451. global _auth_cleanup_task
  10452. if _auth_cleanup_task is None:
  10453. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10454. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10455. def stop_auth_cleanup() -> None:
  10456. global _auth_cleanup_task
  10457. if _auth_cleanup_task:
  10458. _auth_cleanup_task.cancel()
  10459. _auth_cleanup_task = None
  10460. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10461. @asynccontextmanager
  10462. async def lifespan(app: FastAPI):
  10463. # Startup
  10464. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10465. # anything else can spawn tasks that might trip it.
  10466. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10467. install_proactor_reset_filter()
  10468. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10469. # what turned descriptor exhaustion into a corrupted database (#2883).
  10470. from backend.app.core.fd_limit import raise_open_file_limit
  10471. raise_open_file_limit()
  10472. # Before init_db, so the warning is near the top of the log rather than
  10473. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10474. warn_if_running_on_uvloop()
  10475. await init_db()
  10476. # Browser download tokens expire after five minutes. Remove abandoned
  10477. # prepared ZIPs at startup as well as before each new preparation so a
  10478. # quiet appliance cannot retain an unusable bundle indefinitely.
  10479. try:
  10480. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10481. await prune_stale_printer_file_bundles()
  10482. except Exception as exc:
  10483. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10484. # After migrations, so the is_env_managed column exists. Never raises --
  10485. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10486. # startup (see apply_env_oidc_provider).
  10487. from backend.app.core.oidc_env import apply_env_oidc_provider
  10488. async with async_session() as oidc_db:
  10489. await apply_env_oidc_provider(oidc_db)
  10490. # Close out batches that finished before `completed` was a reachable status
  10491. # (#342). Without this the Batches tab opens on every batch created since
  10492. # the feature shipped, all still marked active. Never blocks startup.
  10493. try:
  10494. from backend.app.services.print_batch import backfill_batch_statuses
  10495. async with async_session() as batch_db:
  10496. await backfill_batch_statuses(batch_db)
  10497. except Exception as exc:
  10498. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10499. # Each plate's estimate of archives made before they were kept (#3375),
  10500. # read from their 3MFs in the background: the readers use the whole
  10501. # file's figures until then.
  10502. global _plate_estimates_task
  10503. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10504. # Register an app-scoped httpx client for Bambu Cloud services so
  10505. # per-request BambuCloudService instances reuse the same connection pool
  10506. # (important for routes like /cloud/filament-info that chain many
  10507. # get_setting_detail calls). The shared client stores no region/token
  10508. # state, so the per-request ownership pattern that fixed the region-bleed
  10509. # bug is preserved.
  10510. import httpx as _httpx
  10511. from backend.app.services.bambu_cloud import set_shared_http_client
  10512. from backend.app.services.model_providers.makerworld.service import (
  10513. set_shared_http_client as set_shared_makerworld_http_client,
  10514. )
  10515. from backend.app.services.orca_cloud import (
  10516. set_shared_http_client as set_shared_orca_http_client,
  10517. )
  10518. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10519. set_shared_http_client(_shared_cloud_http_client)
  10520. # Reuse the same connection pool for MakerWorld — different host, same
  10521. # keep-alive pool saves a TLS handshake per request.
  10522. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10523. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10524. # each spun up (and never closed) its own client, leaking sockets.
  10525. set_shared_orca_http_client(_shared_cloud_http_client)
  10526. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10527. # This can happen when a print was cancelled mid-print on versions before this fix.
  10528. try:
  10529. async with async_session() as db:
  10530. from backend.app.models.print_queue import PrintQueueItem
  10531. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10532. aborted_items = result.scalars().all()
  10533. if aborted_items:
  10534. for item in aborted_items:
  10535. item.status = "cancelled"
  10536. await db.commit()
  10537. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10538. except Exception as e:
  10539. logging.warning("Failed to fix aborted queue items: %s", e)
  10540. # Restore debug logging state from previous session
  10541. await init_debug_logging()
  10542. # Set up printer manager callbacks
  10543. loop = asyncio.get_event_loop()
  10544. printer_manager.set_event_loop(loop)
  10545. printer_manager.set_status_change_callback(on_printer_status_change)
  10546. printer_manager.set_print_start_callback(on_print_start)
  10547. printer_manager.set_print_complete_callback(on_print_complete)
  10548. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10549. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10550. printer_manager.set_ams_change_callback(on_ams_change)
  10551. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10552. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10553. await printer_manager.load_awaiting_plate_clear_from_db()
  10554. # Layer change callback for external camera timelapse
  10555. async def on_layer_change(printer_id: int, layer_num: int):
  10556. """Capture timelapse frame on layer change + first layer notification."""
  10557. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10558. await tl_layer_change(printer_id, layer_num)
  10559. # #1867: bank a recent in-print frame so the finish-photo path has a
  10560. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10561. # #2547 added `on_print_progress` as a second driver — this one alone
  10562. # stops firing once the final layer begins.
  10563. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10564. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10565. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10566. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10567. # nozzle clean), so a bare layer_num check can fire minutes before the
  10568. # first real extrusion. We require gcode_state == RUNNING and
  10569. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10570. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10571. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10572. # edge fires later; _first_layer_notified stays clear until we actually send
  10573. # so a deferred re-evaluation can win. See issue #1837.
  10574. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10575. client = printer_manager.get_client(printer_id)
  10576. state = client.state if client else None
  10577. if not state or state.state != "RUNNING":
  10578. return
  10579. if state.mc_print_sub_stage not in (None, 0):
  10580. return
  10581. _first_layer_notified[printer_id] = True
  10582. try:
  10583. async with async_session() as db:
  10584. from backend.app.models.printer import Printer
  10585. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10586. printer = result.scalar_one_or_none()
  10587. if not printer:
  10588. return
  10589. printer_name = printer.name
  10590. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10591. total_layers = state.total_layers if state else 0
  10592. image_data = await _capture_snapshot_for_notification(
  10593. printer_id, printer, logging.getLogger(__name__)
  10594. )
  10595. await notification_service.on_first_layer_complete(
  10596. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10597. )
  10598. except Exception as e:
  10599. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10600. printer_manager.set_layer_change_callback(on_layer_change)
  10601. async def on_print_progress(printer_id: int, percent: int):
  10602. """#2547: keep the in-print frame bank fresh through the final layer.
  10603. `on_layer_change` stops the moment the last layer starts, which on the
  10604. H2C capture that closed #2547 left the bank stale for the three minutes
  10605. that layer took. Progress is the only field that keeps advancing there,
  10606. and it freezes before the End G-code runs — so banking on it stays
  10607. inside the print and never sees a swapped plate.
  10608. """
  10609. client = printer_manager.get_client(printer_id)
  10610. state = client.state if client else None
  10611. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10612. printer_manager.set_print_progress_callback(on_print_progress)
  10613. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10614. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10615. waiter = _bed_cool_waiters.get(printer_id)
  10616. if not waiter:
  10617. return
  10618. threshold = waiter["threshold"]
  10619. if bed_temp > threshold:
  10620. return
  10621. # Bed is at or below threshold — fire notification and remove waiter
  10622. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10623. if not waiter_info:
  10624. return # Another callback already handled it
  10625. bed_cool_logger = logging.getLogger(__name__)
  10626. bed_cool_logger.info(
  10627. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10628. bed_temp,
  10629. printer_id,
  10630. threshold,
  10631. )
  10632. try:
  10633. printer_info = printer_manager.get_printer(printer_id)
  10634. p_name = printer_info.name if printer_info else "Unknown"
  10635. async with async_session() as db:
  10636. await notification_service.on_bed_cooled(
  10637. printer_id=printer_id,
  10638. printer_name=p_name,
  10639. bed_temp=bed_temp,
  10640. threshold=threshold,
  10641. filename=waiter_info["filename"],
  10642. db=db,
  10643. )
  10644. except Exception as e:
  10645. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10646. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10647. async def on_drying_complete(printer_id: int, ams_id: int):
  10648. """Smart-plug auto-off-after-drying trigger (#1349).
  10649. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10650. manager walks all plugs linked to this printer and turns off only
  10651. the ones with ``auto_off_after_drying`` enabled, after their
  10652. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10653. dual-AMS dry that ends within the same MQTT push) call this once
  10654. per unit — the manager's ``_cancel_pending_off`` collapses
  10655. repeated scheduling on the same plug to one timer, so duplicate
  10656. fires are safe.
  10657. """
  10658. try:
  10659. async with async_session() as db:
  10660. await smart_plug_manager.on_drying_complete(printer_id, db)
  10661. except Exception as e:
  10662. logging.getLogger(__name__).warning(
  10663. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10664. printer_id,
  10665. ams_id,
  10666. e,
  10667. )
  10668. printer_manager.set_drying_complete_callback(on_drying_complete)
  10669. async def on_drying_cycle_end(printer_id: int, cycle):
  10670. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10671. from backend.app.services.spool_drying import record_drying_cycle
  10672. try:
  10673. async with async_session() as db:
  10674. await record_drying_cycle(db, printer_id, cycle)
  10675. except Exception as e:
  10676. logging.getLogger(__name__).warning(
  10677. "Failed to record drying for printer %d (AMS %d): %s",
  10678. printer_id,
  10679. cycle.ams_id,
  10680. e,
  10681. )
  10682. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10683. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10684. """Surface the read-back result of a spool assignment to the UI (#2582).
  10685. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10686. echoed back the filament id we pushed. We relay that as a websocket
  10687. event so the frontend can toast "loaded" / "assignment didn't take"
  10688. instead of the historic silent fire-and-forget, which made the
  10689. AMS→Studio hand-off feel random to users.
  10690. """
  10691. try:
  10692. from backend.app.services.spool_assignment_notifications import (
  10693. _slot_label_from_global_tray,
  10694. )
  10695. if ams_id == 255:
  10696. global_id = 254 + tray_id
  10697. elif ams_id >= 128:
  10698. global_id = ams_id
  10699. else:
  10700. global_id = ams_id * 4 + tray_id
  10701. slot_label = _slot_label_from_global_tray(global_id)
  10702. printer_info = printer_manager.get_printer(printer_id)
  10703. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10704. await ws_manager.broadcast(
  10705. {
  10706. "type": "spool_assignment_verified",
  10707. "printer_id": printer_id,
  10708. "printer_name": printer_name,
  10709. "ams_id": ams_id,
  10710. "tray_id": tray_id,
  10711. "slot": slot_label,
  10712. "verified": verified,
  10713. # Present on success: False means the filament setting landed
  10714. # but the K-profile (cali_idx) did not — the reporter's exact
  10715. # "loaded but no flow profile" symptom.
  10716. "kprofile_applied": detail.get("kprofile_applied", True),
  10717. }
  10718. )
  10719. except Exception as e:
  10720. logging.getLogger(__name__).warning(
  10721. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10722. printer_id,
  10723. ams_id,
  10724. tray_id,
  10725. e,
  10726. )
  10727. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10728. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10729. """Persist a mid-print tray change for completion-time attribution.
  10730. AMS filament backup switches trays without telling the slicer, so the
  10731. tray-change log is the only record of which spool fed which layers.
  10732. Keeping it only in memory meant a restart mid-print charged everything
  10733. to the tray that finished the job.
  10734. """
  10735. try:
  10736. from backend.app.services.usage_tracker import record_tray_change
  10737. async with async_session() as db:
  10738. await record_tray_change(db, printer_id, tray_global, layer_num)
  10739. except Exception as e:
  10740. logging.getLogger(__name__).warning(
  10741. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10742. printer_id,
  10743. tray_global,
  10744. layer_num,
  10745. e,
  10746. )
  10747. printer_manager.set_tray_change_callback(on_tray_change)
  10748. # Initialize MQTT relay from settings
  10749. async with async_session() as db:
  10750. from backend.app.api.routes.settings import get_setting
  10751. mqtt_settings = {
  10752. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10753. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10754. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10755. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10756. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10757. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10758. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10759. }
  10760. await mqtt_relay.configure(mqtt_settings)
  10761. # Restore MQTT smart plug subscriptions
  10762. if mqtt_settings.get("mqtt_enabled"):
  10763. from backend.app.models.smart_plug import SmartPlug
  10764. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10765. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10766. mqtt_plugs = result.scalars().all()
  10767. restored = 0
  10768. for plug in mqtt_plugs:
  10769. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10770. restored += 1
  10771. if restored:
  10772. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10773. # Connect to all active printers
  10774. async with async_session() as db:
  10775. await init_printer_connections(db)
  10776. # Auto-connect to Spoolman if enabled
  10777. async with async_session() as db:
  10778. from backend.app.api.routes.settings import get_setting
  10779. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10780. spoolman_url = await get_setting(db, "spoolman_url")
  10781. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10782. try:
  10783. client = await init_spoolman_client(spoolman_url)
  10784. if await client.health_check():
  10785. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10786. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10787. field_ok = await client.ensure_tag_extra_field()
  10788. if not field_ok:
  10789. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10790. # Register the BambuStudio slicer-preset fields used by the
  10791. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10792. # unknown extra keys, so these must exist before any update
  10793. # that touches them.
  10794. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10795. if not await client.ensure_extra_field(field_name):
  10796. logging.warning(
  10797. "Spoolman extra field %r registration failed — "
  10798. "spool slicer-preset edits will return 502",
  10799. field_name,
  10800. )
  10801. else:
  10802. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10803. except Exception as e:
  10804. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10805. # Start the print scheduler
  10806. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10807. # Start the smart plug scheduler for time-based on/off
  10808. smart_plug_manager.start_scheduler()
  10809. # Start the Home Assistant sensor poller (#1148)
  10810. ha_sensor_manager.start()
  10811. location_ha_sensor_manager.start()
  10812. # Resume any pending auto-offs that were interrupted by restart
  10813. await smart_plug_manager.resume_pending_auto_offs()
  10814. # Start the notification digest scheduler
  10815. notification_service.start_digest_scheduler()
  10816. notify_live_activities.start()
  10817. notify_widgets.start()
  10818. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10819. # provider in reactions/both mode; the notification routes resync them.
  10820. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10821. # until the next provider save, not the whole startup.
  10822. try:
  10823. await telegram_reaction_poller.start()
  10824. except Exception as e:
  10825. logging.warning("Telegram reaction poller did not start: %s", e)
  10826. # Start the GitHub backup scheduler
  10827. await github_backup_service.start_scheduler()
  10828. # Start the local backup scheduler
  10829. await local_backup_service.start_scheduler()
  10830. await obico_detection_service.start()
  10831. # Start the library trash sweeper (#1008)
  10832. await library_trash_service.start_scheduler()
  10833. # Start the archive auto-purge sweeper (#1008 follow-up)
  10834. await archive_purge_service.start_scheduler()
  10835. # Start AMS history recording
  10836. start_ams_history_recording()
  10837. # Start printer sensor (nozzle / bed / chamber) history recording
  10838. start_printer_sensor_history_recording()
  10839. # Start printer runtime tracking
  10840. start_runtime_tracking()
  10841. # Start SpoolBuddy device watchdog
  10842. start_spoolbuddy_watchdog()
  10843. # Start camera stream orphan cleanup
  10844. start_camera_cleanup()
  10845. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10846. start_connection_watchdog()
  10847. # One-shot sweep for timelapse session directories orphaned by a crash
  10848. # or restart that happened mid-print (in-memory session tracking can't
  10849. # survive that, and nothing else reaps the leftover frames/output file)
  10850. try:
  10851. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10852. removed = cleanup_orphaned_timelapse_sessions()
  10853. if removed:
  10854. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10855. except Exception as e:
  10856. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10857. # Start expected-print TTL eviction (prevents memory leak when prints are
  10858. # registered but on_print_start never fires)
  10859. start_expected_prints_cleanup()
  10860. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10861. start_auth_cleanup()
  10862. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10863. from backend.app.services import announcements as announcements_service
  10864. announcements_service.start()
  10865. from backend.app.services.printer_media import start_printer_download_cleanup
  10866. start_printer_download_cleanup()
  10867. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10868. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10869. from backend.app.services.loop_watchdog import start_loop_watchdog
  10870. start_loop_watchdog()
  10871. # Initialize virtual printer manager and sync from DB
  10872. from backend.app.services.virtual_printer import virtual_printer_manager
  10873. virtual_printer_manager.set_session_factory(async_session)
  10874. virtual_printer_manager.set_printer_manager(printer_manager)
  10875. try:
  10876. await virtual_printer_manager.sync_from_db()
  10877. logging.info("Virtual printer manager synced from database")
  10878. except Exception as e:
  10879. logging.warning("Failed to sync virtual printers: %s", e)
  10880. yield
  10881. # Shutdown
  10882. print_scheduler.stop()
  10883. smart_plug_manager.stop_scheduler()
  10884. ha_sensor_manager.stop()
  10885. location_ha_sensor_manager.stop()
  10886. notification_service.stop_digest_scheduler()
  10887. await notify_live_activities.close()
  10888. await notify_widgets.close()
  10889. await telegram_reaction_poller.aclose()
  10890. github_backup_service.stop_scheduler()
  10891. local_backup_service.stop_scheduler()
  10892. library_trash_service.stop_scheduler()
  10893. archive_purge_service.stop_scheduler()
  10894. obico_detection_service.stop()
  10895. stop_ams_history_recording()
  10896. stop_printer_sensor_history_recording()
  10897. stop_runtime_tracking()
  10898. stop_spoolbuddy_watchdog()
  10899. stop_camera_cleanup()
  10900. stop_connection_watchdog()
  10901. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10902. stop_loop_watchdog()
  10903. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10904. # cleanly rather than waiting on a queue that nothing will ever fill.
  10905. try:
  10906. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10907. await shutdown_all_broadcasters()
  10908. except Exception as e:
  10909. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10910. stop_expected_prints_cleanup()
  10911. stop_auth_cleanup()
  10912. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  10913. _plate_estimates_task.cancel()
  10914. from backend.app.services import announcements as announcements_service
  10915. announcements_service.stop()
  10916. from backend.app.services.printer_media import stop_printer_download_cleanup
  10917. await stop_printer_download_cleanup()
  10918. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10919. from backend.app.services import timelapse_jobs
  10920. await timelapse_jobs.cancel_all()
  10921. printer_manager.disconnect_all()
  10922. slot_unlink_grace.reset()
  10923. await close_spoolman_client()
  10924. # Stop all virtual printer services
  10925. await virtual_printer_manager.stop_all()
  10926. await mqtt_smart_plug_service.disconnect(timeout=2)
  10927. await mqtt_relay.disconnect(timeout=2)
  10928. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10929. set_shared_http_client(None)
  10930. set_shared_makerworld_http_client(None)
  10931. set_shared_orca_http_client(None)
  10932. await _shared_cloud_http_client.aclose()
  10933. # Checkpoint WAL (SQLite only) and close all database connections
  10934. from backend.app.core.db_dialect import is_sqlite
  10935. if is_sqlite():
  10936. try:
  10937. async with engine.begin() as conn:
  10938. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10939. logging.info("WAL checkpoint completed")
  10940. except Exception as e:
  10941. logging.warning("WAL checkpoint failed: %s", e)
  10942. await engine.dispose()
  10943. app = FastAPI(
  10944. title=app_settings.app_name,
  10945. description="Archive and manage Bambu Lab 3MF files",
  10946. version=APP_VERSION,
  10947. lifespan=lifespan,
  10948. )
  10949. # Added first so it sits innermost, next to the routes: a refused header's value
  10950. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10951. app.add_middleware(RefusedHeaderResponseMask)
  10952. def _json_safe(value):
  10953. """The validation errors with every non-finite number written as text."""
  10954. if isinstance(value, float) and not math.isfinite(value):
  10955. return str(value)
  10956. if isinstance(value, dict):
  10957. return {key: _json_safe(item) for key, item in value.items()}
  10958. if isinstance(value, list | tuple):
  10959. return [_json_safe(item) for item in value]
  10960. return value
  10961. @app.exception_handler(RequestValidationError)
  10962. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10963. """FastAPI's own 422, except that it survives a non-finite number.
  10964. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10965. them), and the default handler echoes the input back in its errors,
  10966. which JSON cannot hold: the request ended in an error instead of a 422.
  10967. """
  10968. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10969. # =============================================================================
  10970. # Authentication Middleware - Secures ALL API routes by default
  10971. # =============================================================================
  10972. # Public routes that don't require authentication even when auth is enabled
  10973. PUBLIC_API_ROUTES = {
  10974. # Auth routes needed before/during login
  10975. "/api/v1/auth/status",
  10976. "/api/v1/auth/login",
  10977. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10978. # Advanced auth status needed for login page
  10979. "/api/v1/auth/advanced-auth/status",
  10980. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10981. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10982. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10983. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10984. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10985. # OIDC routes that must be reachable without a JWT
  10986. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10987. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10988. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10989. # Connected apps: the app's server swaps a code for the user's identity,
  10990. # authenticated by its client secret rather than a login token.
  10991. "/api/v1/connect/token",
  10992. # Version check for updates (no sensitive data)
  10993. "/api/v1/updates/version",
  10994. # Metrics endpoint handles its own prometheus_token authentication
  10995. "/api/v1/metrics",
  10996. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10997. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10998. # hostname / timezone / locale and the chrony NTP-gate state. The
  10999. # response contains user-set defaults and a public sync flag — no
  11000. # secrets. Without this entry the global auth middleware returns 401
  11001. # before the route handler runs, regardless of the route's own
  11002. # "no auth required" intent.
  11003. "/api/v1/system/appliance",
  11004. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  11005. # authenticates with a long-lived ``camwall``-scoped token in the query
  11006. # string — exactly like the camera streams two lists below, and for the same
  11007. # reason (no header to put a JWT in). "Public" here only means the middleware
  11008. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  11009. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  11010. # plain ``camera_stream`` token does NOT open this door.
  11011. "/api/v1/camwall/printers",
  11012. # Overlay branding: the route enforces overlay-scoped token authentication.
  11013. "/api/v1/overlay-branding/logo",
  11014. }
  11015. # Route prefixes that are public (for routes with dynamic segments)
  11016. PUBLIC_API_PREFIXES = [
  11017. # WebSocket connections handle their own auth
  11018. "/api/v1/ws",
  11019. # OIDC authorize redirects — include provider_id in path
  11020. "/api/v1/auth/oidc/authorize/",
  11021. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11022. # a phone with no session, so no header can carry a JWT — the single-use
  11023. # capability token in the path IS the credential (same reasoning as the
  11024. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11025. # good/reject on the one archive the token was minted for.
  11026. "/api/v1/archives/confirm/",
  11027. ]
  11028. # Route patterns that are public (read-only display data)
  11029. # These are checked with "in path" - needed because browsers load images/videos
  11030. # via <img src> and <video src> which don't include Authorization headers
  11031. PUBLIC_API_PATTERNS = [
  11032. # Thumbnails
  11033. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11034. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11035. # Images and media
  11036. "/photos/", # /archives/{id}/photos/{filename}
  11037. "/project-image/", # /archives/{id}/project-image/{path}
  11038. "/qrcode", # /archives/{id}/qrcode
  11039. "/timelapse", # /archives/{id}/timelapse (video)
  11040. "/cover", # /printers/{id}/cover
  11041. "/icon", # /external-links/{id}/icon
  11042. # Camera (streams loaded via <img> tag)
  11043. "/camera/stream", # /printers/{id}/camera/stream
  11044. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11045. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11046. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11047. # string (same reasoning as the camera streams above — no header to carry a
  11048. # JWT). "Public" only means the middleware steps aside; the route still runs
  11049. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11050. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11051. "/overlay-status", # /printers/{id}/overlay-status
  11052. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11053. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11054. # download token in the URL path instead.
  11055. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11056. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11057. # and these patterns match by substring. Without its own entry the middleware
  11058. # 401s the slicer's header-less request before the route's token check runs,
  11059. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11060. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11061. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11062. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11063. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11064. ]
  11065. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11066. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11067. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11068. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11069. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11070. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11071. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11072. Invalid entries are dropped with a warning rather than failing startup, so
  11073. a typo in one origin doesn't take the whole deployment down.
  11074. """
  11075. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11076. if not raw:
  11077. return ()
  11078. valid: list[str] = []
  11079. for item in raw.split(","):
  11080. candidate = item.strip()
  11081. if not candidate:
  11082. continue
  11083. try:
  11084. parsed = urlparse(candidate)
  11085. except ValueError as e:
  11086. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11087. continue
  11088. if parsed.scheme not in ("http", "https"):
  11089. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11090. continue
  11091. if not parsed.netloc:
  11092. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11093. continue
  11094. if parsed.path and parsed.path != "/":
  11095. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11096. continue
  11097. if parsed.query or parsed.fragment:
  11098. _security_headers_logger.warning(
  11099. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11100. )
  11101. continue
  11102. if "*" in parsed.netloc:
  11103. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11104. continue
  11105. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11106. if valid:
  11107. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11108. return tuple(valid)
  11109. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11110. def _frame_ancestors(default_value: str) -> str:
  11111. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11112. ``default_value`` is the strict directive used when the operator has not
  11113. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11114. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11115. Settings URL builder's preview). When trusted origins
  11116. are configured, ``'self'`` is always included so same-origin embedding never
  11117. breaks even if an operator forgets to add their own origin to the list.
  11118. """
  11119. if _TRUSTED_FRAME_ORIGINS:
  11120. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11121. return f"frame-ancestors {default_value};"
  11122. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11123. # patterns are anchored on the exact emitted name so the relaxed policies
  11124. # below can never apply to any other asset.
  11125. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11126. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11127. # -> /assets/pdf.worker.min-<hash>.js
  11128. # Vite also emits a one-line chunk under the second name that only exports the
  11129. # worker's URL. The page imports it as a module, and a module script is run
  11130. # under the importing document's policy, never its own response's, so it
  11131. # matching as well changes nothing.
  11132. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11133. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11134. @app.middleware("http")
  11135. async def security_headers_middleware(request, call_next):
  11136. """Add standard HTTP security headers to every response."""
  11137. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11138. # changes nothing for Bambuddy's own pages — index.html has no inline
  11139. # scripts since the SW registration moved to /sw-register.js. The reason
  11140. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11141. # script injected into the HTML on the edge, with a fresh hash on every
  11142. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11143. # it clones the same nonce onto its injected <script>, and the inline
  11144. # script passes the policy without us needing 'unsafe-inline'. See
  11145. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11146. csp_nonce = secrets.token_urlsafe(16)
  11147. # Routes that render their own HTML need it too, or their inline script is
  11148. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11149. # one that does: it submits its own form so a verdict still costs one tap.
  11150. request.state.csp_nonce = csp_nonce
  11151. response = await call_next(request)
  11152. response.headers["X-Content-Type-Options"] = "nosniff"
  11153. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11154. # browsers honour CSP frame-ancestors instead, and the legacy
  11155. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11156. # When operators have explicitly allowlisted trusted frame origins (#1191
  11157. # — typically Home Assistant on a different port), drop X-Frame-Options
  11158. # and let the CSP-side frame-ancestors directive govern embedding.
  11159. if not _TRUSTED_FRAME_ORIGINS:
  11160. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11161. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11162. # Content-Security-Policy for the React SPA.
  11163. # Notes:
  11164. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11165. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11166. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11167. # - media-src blob:: timelapse video player uses Blob URLs.
  11168. # - font-src data:: some icon fonts are embedded as data URIs.
  11169. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11170. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11171. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11172. # default CSP would render a blank page.
  11173. response.headers["Content-Security-Policy"] = (
  11174. "default-src 'self'; "
  11175. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11176. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11177. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11178. "connect-src 'self'; "
  11179. "font-src 'self' data: https://fonts.gstatic.com; "
  11180. "worker-src 'self' blob:; "
  11181. "object-src 'none'; "
  11182. "base-uri 'self'; " + _frame_ancestors("'none'")
  11183. )
  11184. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11185. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11186. # its emscripten/embind glue generates invoker functions with `new
  11187. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11188. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11189. # own response — not the document's — so relaxing it here confines
  11190. # eval to that DOM-less worker context. The document policy below
  11191. # stays nonce-strict, and this response header has no effect when the
  11192. # file is merely fetched (a fetch's CSP is enforced against the
  11193. # requesting document, not the resource's own headers).
  11194. response.headers["Content-Security-Policy"] = (
  11195. "default-src 'self'; "
  11196. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11197. "connect-src 'self'; "
  11198. "object-src 'none'; "
  11199. "base-uri 'self'; " + _frame_ancestors("'none'")
  11200. )
  11201. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11202. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11203. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11204. # rule as the STEP worker above: the policy that governs a dedicated
  11205. # worker is the one delivered with its own script, so the wasm compile
  11206. # has to be permitted here rather than on the document. Unlike the STEP
  11207. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11208. response.headers["Content-Security-Policy"] = (
  11209. "default-src 'self'; "
  11210. "script-src 'self' 'wasm-unsafe-eval'; "
  11211. "connect-src 'self'; "
  11212. "object-src 'none'; "
  11213. "base-uri 'self'; " + _frame_ancestors("'none'")
  11214. )
  11215. else:
  11216. # The streaming overlay is embedded same-origin by the URL builder's
  11217. # preview in Settings (#1422), so this branch allows 'self'.
  11218. # Embedding from anywhere else is still refused: 'self'
  11219. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11220. # a clickjacking page on another host is blocked exactly as before.
  11221. # (The overlay draws status over a camera feed and its only interactive
  11222. # element is the logo link, so there is nothing to bait a click into
  11223. # even from a same-origin framer.) Cross-origin embedding of the
  11224. # overlay — Home Assistant on another port — remains what
  11225. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11226. # allowlist in.
  11227. #
  11228. # The connected-app consent page (/connect/authorize) gets the same
  11229. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11230. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11231. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11232. # requires every ancestor to be this origin, so a foreign page -- a
  11233. # sidebar link's site included -- still cannot frame the consent
  11234. # screen to bait a click.
  11235. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11236. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11237. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11238. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11239. # the policy served with their own script, so each gets it in its own
  11240. # branch above and the document policy stays as strict as it was.
  11241. response.headers["Content-Security-Policy"] = (
  11242. "default-src 'self'; "
  11243. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11244. "style-src 'self' 'unsafe-inline'; "
  11245. "img-src 'self' data: blob:; "
  11246. "media-src 'self' blob:; "
  11247. "connect-src 'self' ws: wss:; "
  11248. "font-src 'self' data:; "
  11249. "object-src 'none'; "
  11250. "base-uri 'self'; "
  11251. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11252. )
  11253. if request.url.scheme == "https":
  11254. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11255. return response
  11256. @app.middleware("http")
  11257. async def auth_middleware(request, call_next):
  11258. """Enforce authentication on all API routes when auth is enabled.
  11259. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11260. regardless of whether individual routes have auth dependencies.
  11261. """
  11262. from starlette.responses import JSONResponse
  11263. path = request.url.path
  11264. # Only apply to API routes
  11265. if not path.startswith("/api/"):
  11266. return await call_next(request)
  11267. # Allow public routes
  11268. if path in PUBLIC_API_ROUTES:
  11269. return await call_next(request)
  11270. # Allow public prefixes
  11271. for prefix in PUBLIC_API_PREFIXES:
  11272. if path.startswith(prefix):
  11273. return await call_next(request)
  11274. # Allow public patterns (read-only display data like thumbnails)
  11275. for pattern in PUBLIC_API_PATTERNS:
  11276. if pattern in path:
  11277. return await call_next(request)
  11278. # Check if auth is enabled. Fail CLOSED on any exception during the
  11279. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11280. # an attacker who could force a DB exception (e.g. file-descriptor
  11281. # exhaustion via login flood) bypass auth on every protected endpoint.
  11282. # Only the probe is guarded: the request itself runs outside the try, so an
  11283. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11284. try:
  11285. async with async_session() as db:
  11286. from backend.app.core.auth import is_auth_enabled
  11287. auth_enabled = await is_auth_enabled(db)
  11288. except Exception:
  11289. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11290. return JSONResponse(
  11291. status_code=503,
  11292. content={"detail": "Authentication service temporarily unavailable"},
  11293. )
  11294. if not auth_enabled:
  11295. # Auth disabled, allow all requests
  11296. return await call_next(request)
  11297. # Auth is enabled - require valid token
  11298. auth_header = request.headers.get("Authorization")
  11299. x_api_key = request.headers.get("X-API-Key")
  11300. # Check for API key auth first
  11301. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11302. # API key authentication - let the request through to be validated by route handler
  11303. # API keys are validated per-route since they have different permission levels
  11304. return await call_next(request)
  11305. # Check for JWT auth
  11306. if not auth_header or not auth_header.startswith("Bearer "):
  11307. return JSONResponse(
  11308. status_code=401,
  11309. content={"detail": "Authentication required"},
  11310. headers={"WWW-Authenticate": "Bearer"},
  11311. )
  11312. # Validate JWT token
  11313. import jwt
  11314. try:
  11315. from backend.app.core.auth import (
  11316. ALGORITHM,
  11317. SECRET_KEY,
  11318. _is_token_fresh,
  11319. get_user_by_username,
  11320. is_jti_revoked,
  11321. )
  11322. token = auth_header.replace("Bearer ", "")
  11323. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11324. username = payload.get("sub")
  11325. if not username:
  11326. raise ValueError("No username in token")
  11327. jti = payload.get("jti")
  11328. if not jti:
  11329. raise ValueError("No jti in token")
  11330. iat = payload.get("iat")
  11331. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11332. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11333. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11334. async with async_session() as db:
  11335. if await is_jti_revoked(jti, db):
  11336. return JSONResponse(
  11337. status_code=401,
  11338. content={"detail": "Token has been revoked"},
  11339. headers={"WWW-Authenticate": "Bearer"},
  11340. )
  11341. user = await get_user_by_username(db, username)
  11342. if not user or not user.is_active:
  11343. return JSONResponse(
  11344. status_code=401,
  11345. content={"detail": "User not found or inactive"},
  11346. headers={"WWW-Authenticate": "Bearer"},
  11347. )
  11348. if not _is_token_fresh(iat, user):
  11349. return JSONResponse(
  11350. status_code=401,
  11351. content={"detail": "Token no longer valid"},
  11352. headers={"WWW-Authenticate": "Bearer"},
  11353. )
  11354. except jwt.ExpiredSignatureError:
  11355. return JSONResponse(
  11356. status_code=401,
  11357. content={"detail": "Token has expired"},
  11358. headers={"WWW-Authenticate": "Bearer"},
  11359. )
  11360. except (jwt.InvalidTokenError, ValueError):
  11361. return JSONResponse(
  11362. status_code=401,
  11363. content={"detail": "Invalid token"},
  11364. headers={"WWW-Authenticate": "Bearer"},
  11365. )
  11366. except Exception:
  11367. # Not a bad token but a failure checking it (database, pool): refuse,
  11368. # as for the probe above, rather than answer 401 -- the frontend reads
  11369. # a 401 from /auth/me as final and signs the user out.
  11370. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11371. return JSONResponse(
  11372. status_code=503,
  11373. content={"detail": "Authentication service temporarily unavailable"},
  11374. )
  11375. return await call_next(request)
  11376. @app.middleware("http")
  11377. async def trace_id_middleware(request, call_next):
  11378. """Stamp every HTTP request with a trace ID and echo it back.
  11379. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11380. @app.middleware decorators LIFO, so the last-decorated runs first
  11381. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11382. which means auth-middleware log lines (and every line emitted on the
  11383. way down to and back from the route handler) all carry the same
  11384. trace ID. If we put it before auth, auth's logs would be stamped
  11385. with the *previous* request's ID — useless for correlation.
  11386. Honours an inbound ``X-Trace-Id`` header so callers running their
  11387. own tracing can correlate their span IDs with our log lines, but
  11388. only if the value passes the whitelist gate in
  11389. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11390. rejected (too long, contains control chars, etc.) silently triggers
  11391. a freshly minted server-side ID rather than failing the request.
  11392. The minted (or echoed) ID is set on a ContextVar so that every log
  11393. record emitted during the request — application logs *and* uvicorn's
  11394. access log — carries it via TraceIDFilter, and is also written to
  11395. the ``X-Trace-Id`` response header so clients can pin a server-side
  11396. log search to the exact request they made.
  11397. """
  11398. from backend.app.core.trace import (
  11399. generate_trace_id,
  11400. normalise_inbound_trace_id,
  11401. trace_id_var,
  11402. )
  11403. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11404. trace_id = inbound if inbound is not None else generate_trace_id()
  11405. token = trace_id_var.set(trace_id)
  11406. try:
  11407. response = await call_next(request)
  11408. finally:
  11409. # Reset the ContextVar so a record emitted in a totally
  11410. # unrelated background task that just happens to inherit this
  11411. # context doesn't keep referencing this request's ID forever.
  11412. # In practice ContextVar.reset is best-effort under asyncio
  11413. # task-spawn semantics, but the cost is one attribute write so
  11414. # we may as well do it.
  11415. trace_id_var.reset(token)
  11416. response.headers["X-Trace-Id"] = trace_id
  11417. return response
  11418. # API routes
  11419. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11420. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11421. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11422. app.include_router(users.router, prefix=app_settings.api_prefix)
  11423. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11424. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11425. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11426. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11427. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11428. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11429. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11430. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11431. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11432. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11433. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11434. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11435. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11436. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11437. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11438. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11439. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11440. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11441. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11442. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11443. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11444. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11445. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11446. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11447. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11448. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11449. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11450. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11451. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11452. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11453. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11454. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11455. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11456. app.include_router(library.router, prefix=app_settings.api_prefix)
  11457. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11458. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11459. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11460. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11461. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11462. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11463. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11464. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11465. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11466. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11467. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11468. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11469. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11470. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11471. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11472. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11473. app.include_router(system.router, prefix=app_settings.api_prefix)
  11474. app.include_router(support.router, prefix=app_settings.api_prefix)
  11475. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11476. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11477. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11478. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11479. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11480. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11481. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11482. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11483. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11484. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11485. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11486. # Serve static files (React build)
  11487. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11488. # Compressed, and cached for good where Vite hashed the name (#3175).
  11489. app.mount(
  11490. "/assets",
  11491. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11492. name="assets",
  11493. )
  11494. if (app_settings.static_dir / "img").exists():
  11495. app.mount(
  11496. "/img",
  11497. StaticFiles(directory=app_settings.static_dir / "img"),
  11498. name="img",
  11499. )
  11500. if (app_settings.static_dir / "icons").exists():
  11501. app.mount(
  11502. "/icons",
  11503. StaticFiles(directory=app_settings.static_dir / "icons"),
  11504. name="icons",
  11505. )
  11506. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11507. # falls through to the SPA catch-all and returns index.html, which the
  11508. # browser's font sanitizer rejects ("downloadable font: rejected by
  11509. # sanitizer").
  11510. if (app_settings.static_dir / "fonts").exists():
  11511. app.mount(
  11512. "/fonts",
  11513. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11514. name="fonts",
  11515. )
  11516. @app.get("/")
  11517. async def serve_frontend():
  11518. """Serve the React frontend."""
  11519. index_file = app_settings.static_dir / "index.html"
  11520. if index_file.exists():
  11521. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11522. return {
  11523. "message": "Bambuddy API",
  11524. "docs": "/docs",
  11525. "frontend": "Build and place React app in /static directory",
  11526. }
  11527. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11528. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11529. # forever, but the HTML wrapping it is the only file that knows which hash
  11530. # is current. Without explicit cache-control headers Chromium decides
  11531. # heuristically (typically 10% of the time since Last-Modified) and on
  11532. # long-running kiosks happily serves stale HTML across browser restarts.
  11533. # That stale HTML references an old bundle hash, the old bundle is also
  11534. # in the disk cache, and the user ends up running pre-update JS forever
  11535. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11536. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11537. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11538. @app.get("/health")
  11539. async def health_check():
  11540. """Health check endpoint."""
  11541. return {"status": "healthy"}
  11542. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11543. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11544. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11545. # in deployment debugging. One decorator per method, not api_route(methods=
  11546. # [...]): api_route gives both methods the same OpenAPI operation id.
  11547. @app.get("/manifest.json")
  11548. @app.head("/manifest.json")
  11549. async def serve_manifest():
  11550. """Serve PWA manifest."""
  11551. manifest_file = app_settings.static_dir / "manifest.json"
  11552. if manifest_file.exists():
  11553. return FileResponse(manifest_file, media_type="application/manifest+json")
  11554. return {"error": "Manifest not found"}
  11555. @app.get("/sw.js")
  11556. @app.head("/sw.js")
  11557. async def serve_service_worker():
  11558. """Serve service worker."""
  11559. sw_file = app_settings.static_dir / "sw.js"
  11560. if sw_file.exists():
  11561. return FileResponse(
  11562. sw_file,
  11563. media_type="application/javascript",
  11564. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11565. )
  11566. return {"error": "Service worker not found"}
  11567. @app.get("/sw-register.js")
  11568. @app.head("/sw-register.js")
  11569. async def serve_sw_register():
  11570. """Serve the service-worker registration bootstrap script.
  11571. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11572. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11573. """
  11574. reg_file = app_settings.static_dir / "sw-register.js"
  11575. if reg_file.exists():
  11576. return FileResponse(reg_file, media_type="application/javascript")
  11577. return {"error": "sw-register.js not found"}
  11578. # ── GCode viewer static files ────────────────────────────────────────────────
  11579. # Catch-all route for React Router (must be last)
  11580. @app.get("/{full_path:path}")
  11581. async def serve_spa(full_path: str):
  11582. """Serve React app for client-side routing."""
  11583. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11584. if full_path.startswith("api/"):
  11585. from fastapi import HTTPException
  11586. raise HTTPException(status_code=404, detail="Not found")
  11587. index_file = app_settings.static_dir / "index.html"
  11588. if index_file.exists():
  11589. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11590. return {"error": "Frontend not built"}