main.py 543 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, or_, select, text
  19. from backend.app.api.routes import (
  20. ams_history,
  21. announcements,
  22. api_keys,
  23. archive_purge,
  24. archives,
  25. auth,
  26. bug_report,
  27. camera,
  28. camwall,
  29. cloud,
  30. connected_apps,
  31. discovery,
  32. external_links,
  33. filaments,
  34. finance,
  35. firmware,
  36. github_backup,
  37. groups,
  38. ha_sensors,
  39. inventory,
  40. kprofiles,
  41. labels,
  42. library,
  43. library_tags,
  44. library_trash,
  45. library_variants,
  46. local_backup,
  47. local_presets,
  48. location_ha_sensors,
  49. maintenance,
  50. makerworld,
  51. manyfold,
  52. metrics,
  53. mfa,
  54. notification_templates,
  55. notifications,
  56. obico,
  57. orca_cloud,
  58. overlay_branding,
  59. pending_uploads,
  60. pipeline_runs,
  61. print_log,
  62. print_queue,
  63. printer_locations,
  64. printer_sensor_history,
  65. printers,
  66. projects,
  67. scheduled_dryings,
  68. settings as settings_routes,
  69. slice_jobs,
  70. slicer_pipelines,
  71. slicer_presets,
  72. smart_plugs,
  73. sponsor_prompt,
  74. spoolbuddy,
  75. spoolman,
  76. spoolman_inventory,
  77. support,
  78. system,
  79. updates,
  80. user_notifications,
  81. users,
  82. virtual_printers,
  83. webhook,
  84. websocket,
  85. )
  86. from backend.app.api.routes.maintenance import (
  87. _get_printer_maintenance_internal,
  88. ensure_default_types,
  89. maintenance_alert_values,
  90. )
  91. from backend.app.api.routes.support import init_debug_logging
  92. from backend.app.core.config import APP_VERSION, settings as app_settings
  93. from backend.app.core.database import async_session, engine, init_db
  94. from backend.app.core.static_assets import AssetStaticFiles
  95. from backend.app.core.tasks import spawn_background_task
  96. from backend.app.core.websocket import ws_manager
  97. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  98. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  99. from backend.app.services.archive_cost_estimate import (
  100. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  101. )
  102. from backend.app.services.archive_purge import archive_purge_service
  103. from backend.app.services.bambu_ftp import (
  104. FileNotOnPrinterError,
  105. cache_3mf_download,
  106. clear_3mf_cache,
  107. download_file_async,
  108. download_file_try_paths_async,
  109. ftps_handshake_blocked,
  110. get_cached_3mf,
  111. get_ftp_retry_settings,
  112. normalize_3mf_name,
  113. with_ftp_retry,
  114. )
  115. from backend.app.services.bambu_mqtt import PrinterState
  116. from backend.app.services.camera_light import camera_light
  117. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  118. from backend.app.services.github_backup import github_backup_service
  119. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  120. from backend.app.services.library_trash import library_trash_service
  121. from backend.app.services.local_backup import local_backup_service
  122. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  123. from backend.app.services.mqtt_relay import mqtt_relay
  124. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  125. from backend.app.services.notification_service import notification_service
  126. from backend.app.services.notify_live_activities import notify_live_activities
  127. from backend.app.services.notify_widgets import notify_widgets
  128. from backend.app.services.obico_detection import obico_detection_service
  129. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  130. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  131. from backend.app.services.print_scheduler import scheduler as print_scheduler
  132. from backend.app.services.print_storage import (
  133. REASON_FTP_TRANSFER_FAILED,
  134. REASON_FTPS_COOLOFF,
  135. external_storage_present,
  136. ftp_probe_paths,
  137. print_file_reachable_over_ftp,
  138. )
  139. from backend.app.services.printer_manager import (
  140. init_printer_connections,
  141. parse_plate_id,
  142. printer_manager,
  143. printer_state_to_dict,
  144. resolve_plate_id,
  145. )
  146. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  147. from backend.app.services.slot_nozzle import (
  148. nozzle_diameter_for_extruder,
  149. nozzle_flow_for_extruder,
  150. resolve_slot_nozzle,
  151. )
  152. from backend.app.services.smart_plug_manager import smart_plug_manager
  153. from backend.app.services.spool_assignment_notifications import (
  154. notify_missing_spool_assignments_on_print_start,
  155. )
  156. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  157. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  158. from backend.app.services.spoolman_tracking import (
  159. cleanup_tracking as _cleanup_spoolman_tracking,
  160. report_usage as _report_spoolman_usage,
  161. store_print_data as _store_spoolman_print_data,
  162. )
  163. from backend.app.services.telegram_reactions import telegram_reaction_poller
  164. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  165. from backend.app.utils.ams_humidity import ams_humidity_percent
  166. from backend.app.utils.filament_types import printer_filament_type
  167. from backend.app.utils.fts_routing import extruder_for_inlet
  168. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  169. from backend.app.utils.print_jobs import is_internal_printer_job
  170. # =============================================================================
  171. # Dependency Check - runs before other imports to give helpful error messages
  172. # =============================================================================
  173. def _start_error_server(missing_packages: list):
  174. """Start a minimal HTTP server to display dependency errors in browser."""
  175. import os
  176. import signal
  177. from http.server import BaseHTTPRequestHandler, HTTPServer
  178. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  179. html = f"""<!DOCTYPE html>
  180. <html>
  181. <head>
  182. <title>Bambuddy - Setup Required</title>
  183. <style>
  184. body {{
  185. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  186. background: #0f172a; color: #e2e8f0;
  187. display: flex; justify-content: center; align-items: center;
  188. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  189. }}
  190. .container {{
  191. background: #1e293b; border-radius: 12px; padding: 40px;
  192. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  193. }}
  194. h1 {{ color: #f87171; margin-bottom: 10px; }}
  195. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  196. .packages {{
  197. background: #0f172a; border-radius: 8px; padding: 20px;
  198. margin: 20px 0; text-align: left;
  199. }}
  200. .packages ul {{ margin: 0; padding-left: 20px; }}
  201. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  202. .command {{
  203. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  204. margin: 15px 0; font-family: monospace; color: #4ade80;
  205. text-align: left; overflow-x: auto;
  206. }}
  207. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  208. </style>
  209. </head>
  210. <body>
  211. <div class="container">
  212. <h1>Setup Required</h1>
  213. <h2>Missing Python packages</h2>
  214. <div class="packages"><ul>{packages_html}</ul></div>
  215. <p>To fix, run this command on your server:</p>
  216. <div class="command">pip install -r requirements.lock</div>
  217. <p>Or if using a virtual environment:</p>
  218. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  219. <p class="note">After installing, restart Bambuddy:<br>
  220. <code>sudo systemctl restart bambuddy</code></p>
  221. </div>
  222. </body>
  223. </html>"""
  224. class ErrorHandler(BaseHTTPRequestHandler):
  225. def do_GET(self):
  226. self.send_response(503)
  227. self.send_header("Content-type", "text/html")
  228. self.end_headers()
  229. self.wfile.write(html.encode())
  230. def log_message(self, format, *args):
  231. print(f"[Error Server] {args[0]}")
  232. port = int(os.environ.get("PORT", 8000))
  233. print(f"\nStarting error server on http://0.0.0.0:{port}")
  234. print("Visit this URL in your browser to see the error details.\n")
  235. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  236. def shutdown(signum, frame):
  237. print("\nShutting down error server...")
  238. raise SystemExit(0)
  239. signal.signal(signal.SIGTERM, shutdown)
  240. signal.signal(signal.SIGINT, shutdown)
  241. server.serve_forever()
  242. def check_dependencies():
  243. """Check that all required packages are installed."""
  244. missing = []
  245. # Map of import name -> package name (for pip install)
  246. required = {
  247. "jwt": "PyJWT",
  248. "fastapi": "fastapi",
  249. "uvicorn": "uvicorn",
  250. "sqlalchemy": "sqlalchemy",
  251. "aiosqlite": "aiosqlite",
  252. "pydantic": "pydantic",
  253. "paho.mqtt": "paho-mqtt",
  254. }
  255. for module, package in required.items():
  256. try:
  257. __import__(module)
  258. except ImportError:
  259. missing.append(package)
  260. if missing:
  261. print("\n" + "=" * 60)
  262. print("ERROR: Missing required Python packages!")
  263. print("=" * 60)
  264. print(f"\nMissing packages: {', '.join(missing)}")
  265. print("\nTo fix, run:")
  266. print(" pip install -r requirements.lock")
  267. print("\nOr if using a virtual environment:")
  268. print(" ./venv/bin/pip install -r requirements.lock")
  269. print("=" * 60 + "\n")
  270. _start_error_server(missing)
  271. check_dependencies()
  272. # =============================================================================
  273. # Import settings first for logging configuration
  274. # Configure logging based on settings
  275. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  276. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  277. log_level = getattr(logging, log_level_str, logging.INFO)
  278. # Trace ID column ([-] when no request scope is active — startup, MQTT
  279. # callbacks, scheduled tasks not chained from a request — so the column
  280. # stays visually aligned and missing values are obvious in grep). See
  281. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  282. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  283. # Create root logger
  284. root_logger = logging.getLogger()
  285. root_logger.setLevel(log_level)
  286. # Trace-ID injection: this filter populates record.trace_id from the
  287. # per-request ContextVar so the format string above can reference it.
  288. # Attached to each HANDLER (not the root logger) because Python's
  289. # logging semantics only invoke a logger's filters on records that
  290. # *originated* at that logger — records propagated up from child
  291. # loggers (every named logger in the app) never trigger root's filter.
  292. # Putting it on the handlers means every record any handler emits gets
  293. # trace_id injected just before the formatter runs, regardless of which
  294. # logger created the record. Without this, the formatter raises
  295. # KeyError on every child-logger record and the record is silently
  296. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  297. # partially" bug we hit. See backend/app/core/trace.py for the
  298. # ContextVar the filter reads.
  299. from backend.app.core.trace import TraceIDFilter
  300. _trace_id_filter = TraceIDFilter()
  301. # Console handler - always enabled
  302. console_handler = logging.StreamHandler()
  303. console_handler.setLevel(log_level)
  304. console_handler.setFormatter(logging.Formatter(log_format))
  305. console_handler.addFilter(_trace_id_filter)
  306. root_logger.addHandler(console_handler)
  307. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  308. """Send uvicorn's own loggers to bambuddy.log as well.
  309. Both ship with propagate=False, so the root handler never sees them.
  310. uvicorn.access is the record of which endpoint changed server state;
  311. uvicorn.error is where an unhandled route error is logged with its
  312. traceback ("Exception in ASGI application").
  313. """
  314. for name in ("uvicorn.access", "uvicorn.error"):
  315. logging.getLogger(name).addHandler(handler)
  316. # File handler - only in production or if explicitly enabled
  317. if app_settings.log_to_file:
  318. log_file = app_settings.log_dir / "bambuddy.log"
  319. file_handler = RotatingFileHandler(
  320. log_file,
  321. maxBytes=app_settings.log_max_bytes,
  322. backupCount=app_settings.log_backup_count,
  323. encoding="utf-8",
  324. )
  325. file_handler.setLevel(log_level)
  326. file_handler.setFormatter(logging.Formatter(log_format))
  327. file_handler.addFilter(_trace_id_filter)
  328. root_logger.addHandler(file_handler)
  329. logging.info("Logging to file: %s", log_file)
  330. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  331. # access logger with propagate=False by default, so without this attach
  332. # there is no on-disk record of which endpoint triggered a server-state
  333. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  334. # for exactly this reason. Filtered to write methods only
  335. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  336. # frontend don't churn the rotation window faster than it's useful.
  337. from backend.app.core.logging_filters import (
  338. CancelledPoolNoiseFilter,
  339. WriteRequestsOnlyFilter,
  340. )
  341. _attach_file_handler_to_uvicorn(file_handler)
  342. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  343. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  344. # Uvicorn's access logger has propagate=False (its own default), so the
  345. # root-attached TraceIDFilter never sees these records. Attach a
  346. # second instance directly so HTTP access lines carry the same trace
  347. # ID column as the application logs they correlate with.
  348. uvicorn_access_logger.addFilter(TraceIDFilter())
  349. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  350. # BaseHTTPMiddleware cancelling the inner task scope on client
  351. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  352. # underlying transaction leak; this filter only suppresses the residual
  353. # log records that pre-existing pools still emit during their cleanup.
  354. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  355. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  356. # handler (console included), whether or not file logging is on.
  357. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  358. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  359. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  360. # Reduce noise from third-party libraries in production
  361. if not app_settings.debug:
  362. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  363. logging.getLogger("httpcore").setLevel(logging.WARNING)
  364. logging.getLogger("httpx").setLevel(logging.WARNING)
  365. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  366. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  367. # Track active prints: {(printer_id, filename): archive_id}
  368. _active_prints: dict[tuple[int, str], int] = {}
  369. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  370. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  371. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  372. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  373. # instead of running its own grab-now chain when present, so the finish photo
  374. # captures the better-framed pre-bed-drop moment without us having to force
  375. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  376. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  377. #
  378. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  379. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  380. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  381. # bank and the others are not — so the consumer can't tell them apart and
  382. # must not rotate again.
  383. _stage22_finish_frames: dict[int, bytes] = {}
  384. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  385. # `finally` block (whether it captured a frame or not). The consumer in
  386. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  387. # so the FINISH-state fallback path — where moment and completion are dispatched
  388. # back-to-back — doesn't race past the producer with an empty pop, and the
  389. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  390. # grab (Bambu printers allow only one RTSP client at a time).
  391. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  392. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  393. # layer-change and on print-progress advances (#2547) while the model is still
  394. # printing, then consumed by the FINISH-state finish-photo path when the
  395. # dispatcher recorded that it injected End G-code into this print. Bambu
  396. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  397. # plate-swap) has run, so a live grab there would capture the swapped/empty
  398. # plate.
  399. #
  400. # The load-bearing property: both drivers are print telemetry that stops before
  401. # the End G-code executes — no further layer_num increases, and mc_percent
  402. # freezes — so the last banked frame is always the finished print before the
  403. # swap. Anything added as a third driver must hold that same property.
  404. _inprint_frame_bank: dict[int, bytes] = {}
  405. # Monotonic timestamp of the last banked frame per printer — throttles banking
  406. # so tall prints don't add a camera grab on every layer.
  407. _inprint_frame_bank_ts: dict[int, float] = {}
  408. # Minimum seconds between banked frames, except the final object layer which
  409. # always refreshes for the best framing.
  410. _INPRINT_BANK_MIN_INTERVAL = 25.0
  411. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  412. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  413. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  414. # the first connected status update for that connection; transitions back
  415. # to False whenever we observe `state.connected = False` so the next
  416. # reconnect re-arms reconciliation. Keyed by printer_id.
  417. _printer_reconciled_since_connect: dict[int, bool] = {}
  418. # Same edge, same keying, for priming the printer's calibration table exactly
  419. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  420. # is otherwise filled only when someone opens the Profiles page or Configure
  421. # Slot, when a GitHub backup runs, or when the printer happens to answer
  422. # somebody else's query on the report topic. Until then the AMS slot card has
  423. # no K value to show on the printers whose trays carry none of their own
  424. # (#2854 — H2-series report cali_idx and nothing more).
  425. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  426. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  427. # {(printer_id, filename): archive_id}
  428. _expected_prints: dict[tuple[int, str], int] = {}
  429. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  430. # Used by usage tracker to map 3MF slots to physical AMS trays
  431. _print_ams_mappings: dict[int, list[int]] = {}
  432. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  433. _print_cost_center_ids: dict[int, int] = {}
  434. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  435. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  436. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  437. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  438. # for the queue path. Cleared on print completion or TTL eviction.
  439. _print_plate_ids: dict[int, int] = {}
  440. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  441. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  442. _last_progress_milestone: dict[int, int] = {}
  443. # Track whether first layer complete notification has been sent for current print
  444. _first_layer_notified: dict[int, bool] = {}
  445. # Track whether we already sent a kill-switch stop for the current unauthorized print
  446. _unauthorized_print_kill_sent: set[int] = set()
  447. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  448. # lookup briefly so an unknown active print does not query the database on
  449. # every status frame. A short TTL keeps settings changes responsive.
  450. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  451. _kill_switch_setting_cache: tuple[bool, float] | None = None
  452. # Provider notification started when the kill switch stops a print. The later
  453. # MQTT print-complete callback awaits this task and only sends its regular
  454. # provider notification when the immediate attempt failed.
  455. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  456. # HMS faults already notified, with when each was last seen:
  457. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  458. # fault that flickers beside a held notice was forgotten on every gap and
  459. # notified on every return (#3226). The window is long because the measured
  460. # gaps reach 64 s.
  461. _notified_hms_errors: dict[int, dict[str, float]] = {}
  462. _HMS_CLEAR_GRACE_SECONDS = 600.0
  463. # The print state each printer was last seen in, and the faults recorded before
  464. # it last changed, which are forgotten as soon as they are gone (see
  465. # _take_new_hms_faults).
  466. _hms_print_state: dict[int, str] = {}
  467. _hms_forget_when_gone: dict[int, set[str]] = {}
  468. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  469. # Used for snapshot-diff detection at print completion
  470. _timelapse_baselines: dict[int, set[str]] = {}
  471. # Track printers waiting for bed to cool after print completion.
  472. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  473. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  474. _bed_cool_waiters: dict[int, dict] = {}
  475. # Track printers where the user explicitly stopped the print from the queue UI.
  476. # When on_print_complete fires with status "failed" for these printers we treat it
  477. # as "cancelled" (stopped by user) so the correct notification email is sent.
  478. _user_stopped_printers: set[int] = set()
  479. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  480. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  481. # holds the previous observation so we only fire on the True → False edge (a
  482. # False → False repeat doesn't notify; an initial False at startup doesn't
  483. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  484. # holds the per-printer pending asyncio task that fires the notification
  485. # after a debounce window — cancelled if the printer reconnects before the
  486. # window elapses, so transient MQTT blips don't flood the user.
  487. _printer_last_connected: dict[int, bool] = {}
  488. # Printers whose relay offline event went out, so the reconnect publishes the
  489. # matching online event and a blip shorter than the debounce publishes neither.
  490. _printer_offline_published: set[int] = set()
  491. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  492. # Debounce: a printer must stay offline this long before we notify. Sized
  493. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  494. # so a single stale-trigger cooldown isn't enough to fire — only a real
  495. # offline that survives one reconnect attempt notifies.
  496. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  497. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  498. # when status="failed" to label the print's failure_reason in archives.
  499. #
  500. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  501. # which is wrong on two counts:
  502. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  503. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  504. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  505. # the public wiki) as part of its user-cancel sequence. Matching on the module
  506. # alone caused user-cancellations to be archived as "Layer shift" failures.
  507. # We now match by full short code only — anything not in this map leaves
  508. # failure_reason=None rather than guessing.
  509. # Values are the canonical camelCase failure-reason keys, NOT display labels
  510. # (issue #2974). The vocabulary is enforced on writes by
  511. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  512. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  513. # Statistics breakdown. Storing a label here instead put a second spelling of
  514. # the same cause into one column: the Failure Analysis widget groups on the raw
  515. # value, so a print the backend classified and an identical one a user
  516. # classified counted as two different reasons, and the label form could never
  517. # be translated because there was no key for ``t()`` to resolve.
  518. _HMS_FAILURE_REASONS: dict[str, str] = {
  519. # Layer shift / step loss
  520. "0300_4057": "layerShift",
  521. "0300_4068": "layerShift",
  522. "0300_800C": "layerShift",
  523. # Filament runout (printer-side & per-AMS-slot)
  524. "0300_8004": "filamentRunout",
  525. "0700_8011": "filamentRunout",
  526. "0701_8011": "filamentRunout",
  527. "0702_8011": "filamentRunout",
  528. "0703_8011": "filamentRunout",
  529. "0704_8011": "filamentRunout",
  530. "0705_8011": "filamentRunout",
  531. "0706_8011": "filamentRunout",
  532. "0707_8011": "filamentRunout",
  533. "07FF_8011": "filamentRunout",
  534. # Clogged nozzle / extruder
  535. "0300_4006": "cloggedNozzle",
  536. "0300_8016": "cloggedNozzle",
  537. "0300_801C": "cloggedNozzle",
  538. "0700_8003": "cloggedNozzle",
  539. "0700_8007": "cloggedNozzle",
  540. "0700_8013": "cloggedNozzle",
  541. "0701_8003": "cloggedNozzle",
  542. "0701_8007": "cloggedNozzle",
  543. "0701_8013": "cloggedNozzle",
  544. "0702_8003": "cloggedNozzle",
  545. # AI print monitoring — spaghetti / the model coming off the plate.
  546. # `spaghettiDetached` is a key the archive editor already offers for this
  547. # failure mode, not a new one, so a derived reason opens the dropdown on
  548. # that option rather than blank — and survives the next save, which clears
  549. # any value the editor does not recognise.
  550. #
  551. # A module-0x0C row is safe here despite the warning above: that warning is
  552. # about matching on the module alone, and 0C00_8042 is a full short code
  553. # with a documented meaning ("The AI print monitor has detected a spaghetti
  554. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  555. # cannot collide.
  556. #
  557. # 0300_8003's own text ends "before continuing your print", but on an X2D
  558. # it arrives with the print already paused, offering only
  559. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  560. #
  561. # Two neighbours are left out on purpose, so this does not get re-derived:
  562. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  563. # reads as a warning about a print that is still running, not a halt.
  564. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  565. # the waste chute. That is not the print failing.
  566. #
  567. # That line is drawn from the text, not from `severity`, because severity
  568. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  569. # module/error word with no level in it, and bambu_mqtt.py gives every
  570. # print_error entry a flat severity=3. Matching on the short code alone is
  571. # the right shape for derive_failure_reason, not an omission.
  572. "0300_8003": "spaghettiDetached",
  573. "0C00_8042": "spaghettiDetached",
  574. }
  575. def _hms_short_code(attr: int, code: int | str) -> str:
  576. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  577. if isinstance(code, str):
  578. code_int = int(code.replace("0x", ""), 16) if code else 0
  579. else:
  580. code_int = int(code or 0)
  581. attr_int = int(attr or 0)
  582. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  583. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  584. """Derive the failure_reason key for an archived print.
  585. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  586. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  587. no HMS code matches (don't guess — null is honest). The keys are the
  588. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  589. translated at render time.
  590. """
  591. if status in ("aborted", "cancelled"):
  592. return "userCancelled"
  593. if status != "failed":
  594. return None
  595. for err in hms_errors or []:
  596. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  597. if short_code in _HMS_FAILURE_REASONS:
  598. return _HMS_FAILURE_REASONS[short_code]
  599. return None
  600. # Track created_by_id for expected prints so the user email can be sent even when
  601. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  602. # {(printer_id, filename): created_by_id}
  603. _expected_print_creators: dict[tuple[int, str], int] = {}
  604. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  605. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  606. # updates for the same printer in quick succession (~30 ms apart, observed in
  607. # the wild on H2D + dual AMS).
  608. #
  609. # Without this serialisation, two concurrent on_ams_change callbacks each read
  610. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  611. # the second commit hits
  612. # IntegrityError: duplicate key value violates unique constraint
  613. # "spool_assignment_printer_id_ams_id_tray_id_key"
  614. # SQLite's WAL serial-write semantics had been silently swallowing the race
  615. # until optional Postgres support landed (asyncpg allows true concurrent
  616. # transactions and surfaces the constraint violation).
  617. #
  618. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  619. # assign) are inside the lock. The Spoolman sync block further down stays
  620. # concurrent because it's network-bound and idempotent.
  621. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  622. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  623. """Return the per-printer assignment lock, creating it on first use."""
  624. lock = _ams_assignment_locks.get(printer_id)
  625. if lock is None:
  626. lock = asyncio.Lock()
  627. _ams_assignment_locks[printer_id] = lock
  628. return lock
  629. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  630. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  631. # tag tuple changes for the slot. Cleared when the slot is reported empty
  632. # so remove + reinsert reliably re-prompts the UI.
  633. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  634. async def _broadcast_unknown_tag(
  635. *,
  636. printer_id: int,
  637. ams_id: int,
  638. tray_id: int,
  639. tag_uid: str,
  640. tray_uuid: str,
  641. tray_type: str | None = None,
  642. tray_color: str | None = None,
  643. tray_sub_brands: str | None = None,
  644. tray_count: int | None = None,
  645. ) -> None:
  646. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  647. _logger = logging.getLogger(__name__)
  648. slot_key = (ams_id, tray_id)
  649. tag_key = (tag_uid or "", tray_uuid or "")
  650. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  651. if per_printer.get(slot_key) == tag_key:
  652. _logger.debug(
  653. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  654. printer_id,
  655. ams_id,
  656. tray_id,
  657. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  658. )
  659. return
  660. _logger.info(
  661. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  662. printer_id,
  663. ams_id,
  664. tray_id,
  665. tray_type,
  666. tray_color,
  667. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  668. )
  669. # Broadcast first; only commit the dedup if the WS write succeeds.
  670. # If broadcast raises, the next MQTT push retries instead of being
  671. # permanently silenced by a poisoned dedup entry.
  672. await ws_manager.broadcast(
  673. {
  674. "type": "unknown_tag",
  675. "printer_id": printer_id,
  676. "ams_id": ams_id,
  677. "tray_id": tray_id,
  678. "tag_uid": tag_uid,
  679. "tray_uuid": tray_uuid,
  680. "tray_type": tray_type,
  681. "tray_color": tray_color,
  682. "tray_sub_brands": tray_sub_brands,
  683. "tray_count": tray_count,
  684. }
  685. )
  686. per_printer[slot_key] = tag_key
  687. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  688. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  689. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  690. if per_printer is None:
  691. return
  692. per_printer.pop((ams_id, tray_id), None)
  693. # TTL for expected-print entries: evict registrations older than this to prevent
  694. # unbounded growth when a print is registered but never starts (e.g. printer
  695. # disconnect, app restart, print started from the printer panel).
  696. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  697. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  698. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  699. # Cleanup loop interval
  700. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  701. _expected_prints_cleanup_task: asyncio.Task | None = None
  702. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  703. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  704. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  705. possible_keys: list[tuple[int, str]] = []
  706. filename = (state.gcode_file or state.current_print or "").strip()
  707. subtask_name = (state.subtask_name or "").strip()
  708. if subtask_name:
  709. possible_keys.append((printer_id, subtask_name))
  710. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  711. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  712. if filename:
  713. base_name = filename.rsplit("/", 1)[-1]
  714. if base_name.endswith(".gcode.3mf"):
  715. root_name = base_name[: -len(".gcode.3mf")]
  716. possible_keys.append((printer_id, root_name))
  717. possible_keys.append((printer_id, base_name))
  718. possible_keys.append((printer_id, f"{root_name}.gcode"))
  719. possible_keys.append((printer_id, f"{root_name}.3mf"))
  720. elif base_name.endswith(".3mf"):
  721. root_name = base_name[: -len(".3mf")]
  722. possible_keys.append((printer_id, root_name))
  723. possible_keys.append((printer_id, base_name))
  724. elif base_name.endswith(".gcode"):
  725. root_name = base_name[: -len(".gcode")]
  726. possible_keys.append((printer_id, root_name))
  727. possible_keys.append((printer_id, f"{root_name}.3mf"))
  728. possible_keys.append((printer_id, base_name))
  729. else:
  730. possible_keys.append((printer_id, base_name))
  731. possible_keys.append((printer_id, f"{base_name}.3mf"))
  732. return possible_keys
  733. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  734. """The id of who started the print, unless that user has been deleted since.
  735. Deleting a user forgets them in printer_manager, but a print that ended a
  736. moment before still holds them.
  737. """
  738. if not print_user or print_user.get("user_id") is None:
  739. return None
  740. from backend.app.models.user import User
  741. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  742. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  743. """Check the cheap, process-local print ownership signals."""
  744. if printer_manager.get_current_print_user(printer_id):
  745. return True
  746. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  747. async def _is_printer_kill_switch_enabled_cached() -> bool:
  748. """Return the kill-switch setting without querying on every MQTT frame."""
  749. global _kill_switch_setting_cache
  750. now = time.monotonic()
  751. if _kill_switch_setting_cache is not None:
  752. enabled, expires_at = _kill_switch_setting_cache
  753. if now < expires_at:
  754. return enabled
  755. async with async_session() as db:
  756. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  757. enabled = await is_printer_kill_switch_enabled(db)
  758. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  759. return enabled
  760. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  761. """Resolve whether the current print was started by Bambuddy.
  762. ``None`` means identity is not yet safe to decide. The kill switch must
  763. defer in that case: stopping a print is irreversible, and the first status
  764. frames after a restart may arrive before all subtask fields are populated.
  765. """
  766. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  767. return True
  768. possible_keys = _build_status_print_keys(printer_id, state)
  769. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  770. # is on disk. subtask_id is minted per print and pins the answer to the job
  771. # actually running, rather than to an unrelated one that reuses a filename.
  772. raw_subtask_id = getattr(state, "subtask_id", None)
  773. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  774. if subtask_id in ("", "0"):
  775. return None
  776. from backend.app.models.archive import PrintArchive
  777. result = await db.execute(
  778. select(PrintArchive)
  779. .where(
  780. PrintArchive.printer_id == printer_id,
  781. PrintArchive.status == "printing",
  782. PrintArchive.subtask_id == subtask_id,
  783. )
  784. .order_by(PrintArchive.created_at.desc())
  785. .limit(1)
  786. )
  787. archive = result.scalar_one_or_none()
  788. # An archive row on its own proves nothing: `on_print_start` archives every
  789. # print it observes, including ones started from Bambu Studio or Handy, and
  790. # stamps them with the same status and subtask_id. Authorizing on its mere
  791. # existence would disable the kill switch the moment the 3MF finishes
  792. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  793. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  794. # (carried over from the queue item that started it).
  795. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  796. # Rehydrate the fast in-memory path for subsequent status frames. Include
  797. # both the archive filename and every normalized key reported by MQTT.
  798. _active_prints[(printer_id, archive.filename)] = archive.id
  799. for key in possible_keys:
  800. _active_prints[key] = archive.id
  801. return True
  802. # No dispatch marker. Before calling this someone else's print, check whether
  803. # Bambuddy has a job of its own running on this printer: a library-file
  804. # dispatch has no archive at send time, and an archive created seconds later
  805. # by `on_print_start` carries neither marker. The queue row, which the
  806. # scheduler commits to status="printing" before the MQTT send, is the one
  807. # durable record every Bambuddy print has. It cannot be tied to this
  808. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  809. # print is irreversible, and refusing to act costs nothing but a log line.
  810. from backend.app.models.print_queue import PrintQueueItem
  811. dispatched_here = await db.scalar(
  812. select(PrintQueueItem.id)
  813. .where(
  814. PrintQueueItem.printer_id == printer_id,
  815. PrintQueueItem.status == "printing",
  816. )
  817. .limit(1)
  818. )
  819. if dispatched_here is not None:
  820. return None
  821. return False
  822. async def _send_kill_switch_provider_notification(
  823. printer_id: int,
  824. printer_name: str,
  825. data: dict,
  826. ) -> bool:
  827. """Send the immediate print-stopped provider notification.
  828. Returning a success flag lets the normal MQTT completion path retry when
  829. this early notification could not be delivered.
  830. """
  831. logger = logging.getLogger(__name__)
  832. try:
  833. async with async_session() as db:
  834. await notification_service.on_print_complete(
  835. printer_id,
  836. printer_name,
  837. "stopped",
  838. data,
  839. db,
  840. )
  841. return True
  842. except Exception as e:
  843. logger.warning(
  844. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  845. printer_id,
  846. e,
  847. )
  848. return False
  849. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  850. """Wait for an immediate kill-switch notification, if one was scheduled."""
  851. if task is None:
  852. return False
  853. try:
  854. return await task
  855. except Exception as e:
  856. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  857. return False
  858. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  859. """Capture the smart plug lifetime counter on the archive at print start.
  860. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  861. tracking survives a backend restart mid-print. The print-end handler reads
  862. this value back from the DB and computes the delta against the current
  863. plug counter.
  864. """
  865. _logger = logging.getLogger(__name__)
  866. try:
  867. candidates = await energy_plug_candidates(db, printer_id)
  868. if not candidates:
  869. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  870. return False
  871. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  872. if selected is None:
  873. # Naming the plugs matters here: with several linked to one printer
  874. # this is the difference between "the meter is offline" and "you
  875. # linked only accessories" (#2859).
  876. _logger.warning(
  877. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  878. printer_id,
  879. archive.id,
  880. ", ".join(plug.name for plug in candidates),
  881. )
  882. return False
  883. plug, energy = selected
  884. archive.energy_start_kwh = float(energy["total"])
  885. # With the plug's snapshots, what lets the cost follow the price over
  886. # the print rather than take the price at its end (#1251). A price that
  887. # can't be had must not cost the print its energy reading.
  888. archive.energy_start_at = utcnow_naive()
  889. archive.energy_start_plug_id = plug.id
  890. try:
  891. from backend.app.services.energy_price import current_price
  892. archive.energy_start_price = await current_price(db)
  893. except Exception as e:
  894. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  895. archive.energy_start_price = None
  896. await db.commit()
  897. _logger.info(
  898. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  899. f" ({context})" if context else "",
  900. archive.id,
  901. plug.name,
  902. energy["total"],
  903. )
  904. return True
  905. except Exception as e:
  906. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  907. return False
  908. def forget_print_creator(user_id: int) -> None:
  909. """The print-start emails of a deleted user's jobs go to nobody, not to
  910. whoever is given the id next (SQLite reuses it)."""
  911. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  912. del _expected_print_creators[key]
  913. def register_expected_print(
  914. printer_id: int,
  915. filename: str,
  916. archive_id: int,
  917. ams_mapping: list[int] | None = None,
  918. created_by_id: int | None = None,
  919. cost_center_id: int | None = None,
  920. plate_id: int | None = None,
  921. ):
  922. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  923. # Store with multiple filename variations to catch different naming patterns
  924. _expected_prints[(printer_id, filename)] = archive_id
  925. # Also store without .3mf extension if present
  926. if filename.endswith(".3mf"):
  927. base = filename[:-4]
  928. _expected_prints[(printer_id, base)] = archive_id
  929. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  930. # Store AMS mapping for usage tracking at print completion
  931. if ams_mapping is not None:
  932. _print_ams_mappings[archive_id] = ams_mapping
  933. if cost_center_id is not None:
  934. _print_cost_center_ids[archive_id] = cost_center_id
  935. # Store plate_id for usage tracking when this is a single-plate dispatch from
  936. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  937. # file's filament total to the spool instead of just the printed plate (#1697).
  938. if plate_id is not None:
  939. _print_plate_ids[archive_id] = plate_id
  940. # Store created_by_id so the user start email can be sent even when the archive
  941. # itself has no created_by_id (e.g. library-file-based queue prints)
  942. if created_by_id is not None:
  943. _expected_print_creators[(printer_id, filename)] = created_by_id
  944. if filename.endswith(".3mf"):
  945. base = filename[:-4]
  946. _expected_print_creators[(printer_id, base)] = created_by_id
  947. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  948. # Record registration time for TTL-based eviction
  949. _registered_at = time.monotonic()
  950. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  951. if filename.endswith(".3mf"):
  952. base = filename[:-4]
  953. _expected_print_registered_at[(printer_id, base)] = _registered_at
  954. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  955. logging.getLogger(__name__).info(
  956. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  957. )
  958. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  959. """Undo :func:`register_expected_print` when the print never went out.
  960. Registration has to happen *before* the MQTT print command, because the
  961. printer can report the print before the line after the send executes. So
  962. every path that registers and then fails to send — a cancel winning the
  963. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  964. between — leaves an expectation for a print that will never arrive.
  965. The TTL sweep evicts those after two hours, which is far longer than it
  966. takes a user to react to a failed dispatch by pressing print again: that
  967. reprint would be folded into the *old* archive and take the stale
  968. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  969. Mirrors the sweep's rules, including the one that is easy to get wrong:
  970. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  971. file, so they may only be dropped once no live key still points at that
  972. archive.
  973. """
  974. keys = [(printer_id, filename)]
  975. if filename.endswith(".3mf"):
  976. base = filename[:-4]
  977. keys.append((printer_id, base))
  978. keys.append((printer_id, f"{base}.gcode"))
  979. removed = False
  980. for key in keys:
  981. if _expected_prints.pop(key, None) is not None:
  982. removed = True
  983. _expected_print_creators.pop(key, None)
  984. _expected_print_registered_at.pop(key, None)
  985. if archive_id not in set(_expected_prints.values()):
  986. _print_ams_mappings.pop(archive_id, None)
  987. _print_plate_ids.pop(archive_id, None)
  988. if removed:
  989. logging.getLogger(__name__).info(
  990. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  991. printer_id,
  992. filename,
  993. archive_id,
  994. )
  995. def _compute_run_filament_grams(
  996. status: str,
  997. archive_filament_used_grams: float | None,
  998. progress: float | int | None,
  999. usage_results: list[dict] | None,
  1000. ) -> float | None:
  1001. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1002. Priority for every status:
  1003. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1004. weight delta — same source that drives "Total Consumed" on the
  1005. Inventory page, so Stats and Inventory totals stay aligned).
  1006. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1007. back to the canonical "this print used X" value).
  1008. 3. For partial statuses: ``estimate * progress%``.
  1009. 4. ``None`` if nothing is known.
  1010. """
  1011. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1012. if tracked_grams > 0:
  1013. return round(tracked_grams, 1)
  1014. if status == "completed":
  1015. return archive_filament_used_grams
  1016. if archive_filament_used_grams:
  1017. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1018. if scale > 0:
  1019. return round(archive_filament_used_grams * scale, 1)
  1020. return None
  1021. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1022. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1023. stored_ams_mapping = data.get("ams_mapping")
  1024. if not stored_ams_mapping and archive_id:
  1025. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1026. return stored_ams_mapping
  1027. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1028. """Resolve plate_id for print start without consuming stored direct-Print state.
  1029. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1030. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1031. read it back at print-start without popping (the entry is popped on print
  1032. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1033. """
  1034. if archive_id is None:
  1035. return None
  1036. return _print_plate_ids.get(archive_id)
  1037. def _partial_progress_scale(progress: int | float | None) -> float:
  1038. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1039. Used by every site that multiplies a "would-have-used" slicer estimate
  1040. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1041. so the three sites in ``_background_notifications`` (and the per-plate
  1042. override helper) can't drift apart on the coercion shape.
  1043. """
  1044. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1045. def _scope_notification_archive_data_to_plate(
  1046. archive_data: dict,
  1047. archive_file_path: str | None,
  1048. plate_id: int | None,
  1049. print_status: str,
  1050. progress: int | float | None,
  1051. base_dir: Path,
  1052. ) -> dict:
  1053. """Override summed-across-plates totals in ``archive_data`` with the values
  1054. for ``plate_id`` so the completion notification reports what was actually
  1055. printed, not the whole project (#1785).
  1056. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1057. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1058. the archive card's "whole project" headline, wrong for the completion
  1059. notification of a single-plate print. The queue UI already re-reads the
  1060. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1061. notification payload (filament grams, time estimate, per-slot breakdown).
  1062. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1063. no per-plate values — in every fail case the original ``archive_data`` is
  1064. returned unchanged so the notification still sends.
  1065. """
  1066. if plate_id is None or not archive_file_path:
  1067. return archive_data
  1068. from backend.app.utils.threemf_tools import (
  1069. extract_filament_usage_from_3mf,
  1070. extract_print_time_from_3mf,
  1071. )
  1072. archive_path = base_dir / archive_file_path
  1073. if not archive_path.exists():
  1074. return archive_data
  1075. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1076. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1077. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1078. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1079. if plate_time:
  1080. archive_data["print_time_seconds"] = plate_time
  1081. # Gate both the grams headline AND the per-slot breakdown on the same
  1082. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1083. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1084. # to the project-level grams the archive columns already provide rather
  1085. # than ship a project-level headline next to an all-zero per-plate
  1086. # breakdown.
  1087. if plate_grams > 0:
  1088. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1089. archive_data["filament_slots"] = [
  1090. {
  1091. "slot_id": s.get("slot_id"),
  1092. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1093. "type": s.get("type", ""),
  1094. "color": s.get("color", ""),
  1095. }
  1096. for s in plate_slots
  1097. ]
  1098. return archive_data
  1099. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1100. """Best-effort filament metadata from the MQTT print-start snapshot.
  1101. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1102. file during print, see #1533) so the fallback PrintArchive still has
  1103. enough filament info to support the inventory views and AMS-expansion
  1104. planning the operator opens it for. Returns a dict with optional
  1105. ``filament_type`` and ``filament_color`` keys in the same
  1106. comma-separated format the 3MF extractor produces, so the rest of the
  1107. codebase treats the fallback archive identically to a normal one.
  1108. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1109. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1110. entries). When supplied, only the slots actually consumed by this
  1111. print contribute. Without it the function falls back to every loaded
  1112. AMS slot — less accurate but still useful.
  1113. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1114. that the unit tests pass directly, AND the on_print_start callback
  1115. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1116. bambu_mqtt service hands to main.py at runtime. The original
  1117. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1118. handled the inner shape and silently returned ``{}`` for every real
  1119. print start, leaving fallback archives' filament fields NULL — the
  1120. exact regression the fix was meant to close. Reported with a log
  1121. proving the AMS state was right there at
  1122. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1123. """
  1124. result: dict[str, str] = {}
  1125. # Look at the on_print_start wrapper first, then the inner shape.
  1126. raw_data = (data or {}).get("raw_data")
  1127. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1128. if not isinstance(ams_root, dict):
  1129. ams_root = (data or {}).get("ams") or {}
  1130. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1131. if not isinstance(ams_units, list) or not ams_units:
  1132. return result
  1133. # Map global tray id (unit * 4 + tray) → (type, color).
  1134. loaded: dict[int, tuple[str, str]] = {}
  1135. for unit in ams_units:
  1136. if not isinstance(unit, dict):
  1137. continue
  1138. try:
  1139. unit_id = int(unit.get("id", 0))
  1140. except (TypeError, ValueError):
  1141. continue
  1142. for tray in unit.get("tray") or []:
  1143. if not isinstance(tray, dict):
  1144. continue
  1145. try:
  1146. tray_id = int(tray.get("id", 0))
  1147. except (TypeError, ValueError):
  1148. continue
  1149. ttype = (tray.get("tray_type") or "").strip()
  1150. tcolor = (tray.get("tray_color") or "").strip().upper()
  1151. if not ttype:
  1152. continue # Empty / unloaded slot.
  1153. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1154. if not loaded:
  1155. return result
  1156. if ams_mapping:
  1157. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1158. filaments = [loaded[g] for g in used_ids if g in loaded]
  1159. if not filaments:
  1160. return result # Mapping points entirely at slots we have no data for.
  1161. else:
  1162. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1163. types_joined = ",".join(f[0] for f in filaments)
  1164. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1165. # Column limits per backend/app/models/archive.py: filament_type=50,
  1166. # filament_color=200.
  1167. if types_joined:
  1168. result["filament_type"] = types_joined[:50]
  1169. if colors_joined:
  1170. result["filament_color"] = colors_joined[:200]
  1171. return result
  1172. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1173. """Start a layer-timelapse session for *archive_id* when the printer has
  1174. an external camera configured. Returns True if a session was started.
  1175. Three call sites in on_print_start (expected-archive promotion, fallback
  1176. archive creation, fresh-archive creation) used to inline this same
  1177. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1178. on the first pass). Centralising the conditional + call here makes the
  1179. contract testable in isolation and keeps the three sites locked in step.
  1180. """
  1181. if not (printer.external_camera_enabled and printer.external_camera_url):
  1182. return False
  1183. from backend.app.services.layer_timelapse import start_session
  1184. start_session(
  1185. printer_id,
  1186. archive_id,
  1187. printer.external_camera_url,
  1188. printer.external_camera_type or "mjpeg",
  1189. snapshot_url=printer.external_camera_snapshot_url,
  1190. rotation=getattr(printer, "camera_rotation", 0),
  1191. )
  1192. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1193. return True
  1194. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1195. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1196. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1197. — since #2926 — the description the parser already resolved, which is preferred
  1198. when present so the queue's failure reason reads the same as the status
  1199. response. The short code still produces the bracketed label, and still
  1200. resolves the sentence for a caller whose entries predate the field. An entry
  1201. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1202. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1203. label when no description is on file. Returns None for an empty list so
  1204. callers can leave error_message unset.
  1205. """
  1206. if not hms_errors:
  1207. return None
  1208. from backend.app.services.hms_errors import get_error_description
  1209. parts: list[str] = []
  1210. for err in hms_errors:
  1211. try:
  1212. # `_hms_short_code` rather than a local derivation: this one used to
  1213. # format the error without masking it to 16 bits, so an `hms[]` entry
  1214. # whose code carries an alert-level group produced a five-digit label
  1215. # like "0500_3000A" — not a code the user can look up, and never a
  1216. # catalogue key, so the sentence was lost with it.
  1217. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1218. except (TypeError, ValueError):
  1219. continue
  1220. description = err.get("description") or get_error_description(short_code)
  1221. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1222. # groups and is not a code anyone can look up; its full code in the
  1223. # printer screen's four groups is (#2728).
  1224. full_code = str(err.get("full_code") or "")
  1225. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1226. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1227. return "; ".join(parts) if parts else None
  1228. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1229. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1230. print completes successfully. Gated to status=='completed': failed, cancelled
  1231. and aborted prints do not count as usage. Caller is responsible for committing
  1232. the session. No-op when the queue item has no linked library file (e.g. reprints
  1233. from an archive). See #1008."""
  1234. if queue_status != "completed" or item.library_file_id is None:
  1235. return
  1236. from backend.app.models.library import LibraryFile
  1237. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1238. if lib_file is None:
  1239. return
  1240. lib_file.print_count = (lib_file.print_count or 0) + 1
  1241. lib_file.last_printed_at = datetime.now(timezone.utc)
  1242. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1243. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1244. When on_print_complete fires with status 'failed' for a printer in this set we
  1245. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1246. rather than a 'print failed' notification.
  1247. """
  1248. _user_stopped_printers.add(printer_id)
  1249. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1250. _last_status_broadcast: dict[int, str] = {}
  1251. # Track printers where we've updated nozzle_count
  1252. _nozzle_count_updated: set[int] = set()
  1253. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1254. """Wait the debounce window then fire `on_printer_offline` if the printer
  1255. is still offline.
  1256. Scheduled by `on_printer_status_change` on the connected → disconnected
  1257. edge (#1752). Cancelled by the same handler if the printer reconnects
  1258. before the window elapses, so a single MQTT blip + recovery doesn't
  1259. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1260. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1261. route through the same status-change callback, so this covers both.
  1262. """
  1263. logger = logging.getLogger(__name__)
  1264. try:
  1265. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1266. still_offline = not printer_manager.is_connected(printer_id)
  1267. logger.info(
  1268. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1269. printer_id,
  1270. still_offline,
  1271. )
  1272. if not still_offline:
  1273. return
  1274. async with async_session() as db:
  1275. from backend.app.models.printer import Printer
  1276. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1277. printer = result.scalar_one_or_none()
  1278. if not printer:
  1279. logger.warning(
  1280. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1281. printer_id,
  1282. )
  1283. return
  1284. # Recorded only when the relay can publish it, so the reconnect's
  1285. # online event always has an offline before it.
  1286. if mqtt_relay.enabled and mqtt_relay.connected:
  1287. _printer_offline_published.add(printer_id)
  1288. try:
  1289. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1290. except Exception as e:
  1291. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1292. logger.info(
  1293. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1294. printer_id,
  1295. printer.name,
  1296. )
  1297. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1298. except asyncio.CancelledError:
  1299. raise
  1300. except Exception as e:
  1301. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1302. finally:
  1303. _printer_offline_notify_tasks.pop(printer_id, None)
  1304. def _hms_notify_key(error) -> str:
  1305. """What identifies a fault for notification de-duplication.
  1306. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1307. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1308. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1309. and -0006 together) shared a key and only the first was ever notified. An
  1310. entry without a full code falls back to attr and code together.
  1311. """
  1312. full_code = getattr(error, "full_code", "") or ""
  1313. if full_code:
  1314. return full_code.upper()
  1315. return f"{error.attr:08X}:{error.code}"
  1316. def _hms_fault_counts(error) -> bool:
  1317. """Whether a fault counts as a problem: the same rule the frontend's
  1318. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1319. It counts when Bambu publishes text for it or it offers action buttons, and
  1320. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1321. no actions does not count: those are things like "the top cover is open" or
  1322. "the chamber is hot, fan speed increased", which a printer can hold through
  1323. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1324. it always has; those are prompts such as "unable to start drying" (#2728).
  1325. """
  1326. if error.severity < 1:
  1327. return False
  1328. has_actions = bool(getattr(error, "actions", None))
  1329. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1330. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1331. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1332. """The new faults that count (see ``_hms_fault_counts``).
  1333. These go to the MQTT relay; the caller also needs a description before it
  1334. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1335. used to read ``severity >= 2`` when severity held the part byte; on the real
  1336. level that would drop the task-stopping errors (#2728).
  1337. """
  1338. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1339. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1340. """The faults on this printer not notified yet, and record them as notified.
  1341. Tracking is updated before anything is sent, so concurrent status callbacks
  1342. cannot notify the same fault twice. A notified fault is forgotten once it
  1343. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1344. and on is notified once (#3226), while one that clears and comes back much
  1345. later is notified again.
  1346. When ``print_state`` changes (a print resumed, started or finished), every
  1347. fault recorded so far is forgotten the first time it is gone, without the
  1348. wait: a runout fixed before resuming must be notified if it happens again a
  1349. few minutes later, while the printer sits paused. Not only the faults gone
  1350. at the change itself, because the update that flips the state can still
  1351. carry the old fault (a ``print_error`` entry stays until a payload brings
  1352. ``hms``).
  1353. """
  1354. now = time.time()
  1355. current = {_hms_notify_key(e) for e in errors}
  1356. seen = _notified_hms_errors.setdefault(printer_id, {})
  1357. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1358. if print_state is not None:
  1359. print_state = print_state.upper()
  1360. if _hms_print_state.get(printer_id, print_state) != print_state:
  1361. forget_when_gone.update(seen)
  1362. _hms_print_state[printer_id] = print_state
  1363. for key, last_seen in list(seen.items()):
  1364. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1365. del seen[key]
  1366. forget_when_gone.discard(key)
  1367. new = current - seen.keys()
  1368. for key in current:
  1369. seen[key] = now
  1370. if not seen:
  1371. _notified_hms_errors.pop(printer_id, None)
  1372. if not forget_when_gone:
  1373. _hms_forget_when_gone.pop(printer_id, None)
  1374. return _hms_errors_to_notify(errors, new)
  1375. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1376. # "Printing", -1 and 255 are "no stage" (#3211).
  1377. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1378. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1379. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1380. Records it as notified. Called only for a printing state with progress above 0.
  1381. Progress before the first layer is not progress through the print (#3211).
  1382. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1383. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1384. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1385. 75% notification together with Print Started, and since 75 was then on
  1386. record, 25 and 50 could never fire. So nothing counts while the printer
  1387. reports a layer count but has not started layer 1.
  1388. Without a layer count -- a print whose first frame carried no
  1389. ``total_layer_num``, until the pushall that asks for it is answered
  1390. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1391. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1392. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1393. reports neither keeps the old behaviour rather than never notifying.
  1394. """
  1395. if (state.layer_num or 0) < 1:
  1396. if (state.total_layers or 0) > 0:
  1397. return None
  1398. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1399. return None
  1400. progress = state.progress or 0
  1401. current_milestone = 0
  1402. if progress >= 75:
  1403. current_milestone = 75
  1404. elif progress >= 50:
  1405. current_milestone = 50
  1406. elif progress >= 25:
  1407. current_milestone = 25
  1408. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1409. _last_progress_milestone[printer_id] = current_milestone
  1410. return current_milestone
  1411. return None
  1412. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1413. """Handle printer status changes - broadcast via WebSocket."""
  1414. try:
  1415. notify_live_activities.observe(printer_id, state)
  1416. except Exception:
  1417. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1418. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1419. # transitions disconnected → connected — which covers both Bambuddy
  1420. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1421. # `reconcile_stale_active_prints` exactly once for this connection so
  1422. # any archive still in `status="printing"` that can't actually be
  1423. # running anymore (printer IDLE / different subtask / empty subtask)
  1424. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1425. # finished during a disconnect window + a smart-plug power cycle
  1426. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1427. # next boot. Reconciliation runs concurrently — it must not block the
  1428. # WebSocket dedup / broadcast logic below, and the connected edge is
  1429. # marked True BEFORE the await so concurrent status updates inside
  1430. # the same connection don't re-trigger reconciliation.
  1431. #
  1432. # Wait for a real push_status before reconciling (#1679): MQTT
  1433. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1434. # the connection, BEFORE `_request_push_all` round-trips. At that
  1435. # instant the `PrinterState` is still on construction defaults — most
  1436. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1437. # If reconcile spawns here, every in-flight archive falls through to
  1438. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1439. # creates a duplicate archive on the real PRINT COMPLETE and
  1440. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1441. # keeps the #1542 mechanism intact: once the first real push_status
  1442. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1443. # fires again with the flag still False — reconcile then runs against
  1444. # actual evidence.
  1445. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1446. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1447. _printer_reconciled_since_connect[printer_id] = True
  1448. spawn_background_task(
  1449. reconcile_stale_active_prints(printer_id),
  1450. name=f"reconcile-stale-prints-{printer_id}",
  1451. )
  1452. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1453. # Re-arm so the next reconnect triggers reconciliation again.
  1454. _printer_reconciled_since_connect[printer_id] = False
  1455. # Same edge, for the calibration table the AMS card reads its K values from.
  1456. #
  1457. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1458. # tables to ask for. A `state_known` gate alone is not enough: the first
  1459. # real push_status is what makes the state known, and the nozzle fields do
  1460. # not always arrive in it. Latching there would spend this connection's one
  1461. # attempt on a printer that could not yet say what was fitted.
  1462. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1463. if (
  1464. state.connected
  1465. and state_known
  1466. and nozzle_known
  1467. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1468. ):
  1469. _printer_kprofiles_primed_since_connect[printer_id] = True
  1470. spawn_background_task(
  1471. prime_kprofile_table(printer_id),
  1472. name=f"prime-kprofiles-{printer_id}",
  1473. )
  1474. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1475. _printer_kprofiles_primed_since_connect[printer_id] = False
  1476. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1477. # else in the AMS report changing -- a power cycle does it to every slot --
  1478. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1479. # while the printer is idle; needs_check is cheap and throttled per slot.
  1480. # Guarded: nothing here may stop the status broadcast below.
  1481. try:
  1482. if not state.connected:
  1483. kprofile_drift.forget_printer(printer_id)
  1484. elif kprofile_drift.needs_check(printer_id, state):
  1485. spawn_background_task(
  1486. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1487. name=f"reapply-kprofiles-{printer_id}",
  1488. )
  1489. except Exception:
  1490. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1491. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1492. # connected → disconnected. The "back online" channel is already covered
  1493. # by the print-failure notification (firmware reports gcode_state=FAILED
  1494. # on reconnect of an interrupted print), so there is no online
  1495. # notification. The MQTT relay gets both: offline after the debounce, and
  1496. # online on the reconnect that follows a published offline.
  1497. prev_connected = _printer_last_connected.get(printer_id)
  1498. _printer_last_connected[printer_id] = state.connected
  1499. if prev_connected is True and not state.connected:
  1500. existing = _printer_offline_notify_tasks.get(printer_id)
  1501. if existing is None or existing.done():
  1502. logging.getLogger(__name__).info(
  1503. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1504. printer_id,
  1505. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1506. )
  1507. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1508. _maybe_notify_printer_offline(printer_id),
  1509. name=f"printer-offline-notify-{printer_id}",
  1510. )
  1511. elif state.connected:
  1512. # Kept until the relay can actually send online: with its broker down
  1513. # now, the next status update after the reconnect sends it.
  1514. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1515. _printer_offline_published.discard(printer_id)
  1516. printer_info = printer_manager.get_printer(printer_id)
  1517. if printer_info:
  1518. try:
  1519. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1520. except Exception as e:
  1521. logging.getLogger(__name__).warning(
  1522. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1523. )
  1524. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1525. if pending is not None and not pending.done():
  1526. logging.getLogger(__name__).info(
  1527. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1528. printer_id,
  1529. )
  1530. pending.cancel()
  1531. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1532. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1533. temps = state.temperatures or {}
  1534. nozzle_temp = round(temps.get("nozzle", 0))
  1535. bed_temp = round(temps.get("bed", 0))
  1536. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1537. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1538. # Auto-detect dual-nozzle printers from MQTT temperature data
  1539. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1540. _nozzle_count_updated.add(printer_id)
  1541. # Update nozzle_count in database
  1542. async with async_session() as db:
  1543. from backend.app.models.printer import Printer
  1544. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1545. printer = result.scalar_one_or_none()
  1546. if printer and printer.nozzle_count != 2:
  1547. printer.nozzle_count = 2
  1548. await db.commit()
  1549. logging.getLogger(__name__).info(
  1550. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1551. )
  1552. # Include target temps for heating phase detection
  1553. bed_target = round(temps.get("bed_target", 0))
  1554. nozzle_target = round(temps.get("nozzle_target", 0))
  1555. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1556. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1557. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1558. #
  1559. # dry_countdown_stalled rides along because it is the one drying signal the
  1560. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1561. # dry_time stopped moving, so on the frame that flips it every other member
  1562. # of this key is identical and the push would be deduplicated away. Mid-print
  1563. # a temperature would eventually break the tie, but a parked command on an
  1564. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1565. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1566. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1567. ams_dry_key = (
  1568. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1569. if state.raw_data
  1570. else ()
  1571. )
  1572. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1573. #
  1574. # The filament identity fields are here because Configure Slot writes
  1575. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1576. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1577. # matched, this function returned before broadcasting, and the card kept
  1578. # showing the old filament until the 30s fallback poll or a page reload —
  1579. # even though the configure route asks the printer for a fresh pushall and
  1580. # that push does carry the new values. Reset always worked, because it
  1581. # clears tray_type.
  1582. #
  1583. # These fields only change when someone configures a slot or swaps a spool,
  1584. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1585. ams_tray_key = (
  1586. tuple(
  1587. (
  1588. t.get("id"),
  1589. t.get("tray_type", ""),
  1590. t.get("state"),
  1591. t.get("tray_color", ""),
  1592. t.get("tray_info_idx", ""),
  1593. t.get("tray_sub_brands", ""),
  1594. t.get("cali_idx"),
  1595. )
  1596. for a in (state.raw_data.get("ams") or [])
  1597. for t in a.get("tray", [])
  1598. )
  1599. if state.raw_data
  1600. else ()
  1601. )
  1602. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1603. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1604. # in the AMS change-hash (tray fields only, and widening that would fire
  1605. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1606. # screen changed no key at all and the card's inlet badges sat stale until a
  1607. # reload. Like the filament-backup flag, these only move when someone
  1608. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1609. fts_key = (
  1610. state.fila_switch.installed if state.fila_switch else False,
  1611. tuple(sorted(state.ams_switch_inlet.items())),
  1612. # Which hotend holds which slot. Unlike the two above this does move
  1613. # mid-print, on every filament change — but only between discrete slots,
  1614. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1615. # it live: it decides which hotend the Load dialog may offer and whether
  1616. # Unload has anything to act on.
  1617. tuple(
  1618. sorted(
  1619. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1620. # Sort on the extruder id alone: the other members are nullable
  1621. # and comparing None with an int raises.
  1622. key=lambda entry: entry[0],
  1623. )
  1624. ),
  1625. )
  1626. status_key = (
  1627. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1628. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1629. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1630. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1631. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1632. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1633. )
  1634. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1635. if not is_active_print:
  1636. _unauthorized_print_kill_sent.discard(printer_id)
  1637. elif printer_id in _unauthorized_print_kill_sent:
  1638. # stop_print() was already sent for this print; avoid all further
  1639. # ownership and settings work until the printer leaves an active state.
  1640. pass
  1641. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1642. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1643. _unauthorized_print_kill_sent.discard(printer_id)
  1644. else:
  1645. kill_switch_enabled = False
  1646. authorization: bool | None = None
  1647. status_logger = logging.getLogger(__name__)
  1648. try:
  1649. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1650. if kill_switch_enabled:
  1651. async with async_session() as db:
  1652. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1653. except Exception as e:
  1654. # Fail safe: a database/reconciliation error must never turn into an
  1655. # irreversible stop of a print whose ownership is still unknown.
  1656. authorization = None
  1657. status_logger.warning(
  1658. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1659. )
  1660. if not kill_switch_enabled or authorization is True:
  1661. _unauthorized_print_kill_sent.discard(printer_id)
  1662. elif authorization is None:
  1663. _unauthorized_print_kill_sent.discard(printer_id)
  1664. status_logger.debug(
  1665. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1666. printer_id,
  1667. )
  1668. else:
  1669. try:
  1670. stopped = printer_manager.stop_print(printer_id)
  1671. if stopped:
  1672. _unauthorized_print_kill_sent.add(printer_id)
  1673. printer_info = printer_manager.get_printer(printer_id)
  1674. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1675. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1676. notification_data = {
  1677. "status": "stopped",
  1678. "filename": state.gcode_file or state.current_print or "",
  1679. "subtask_name": state.subtask_name or "",
  1680. "progress": state.progress,
  1681. "reason": "unauthorized_print",
  1682. }
  1683. status_logger.warning(
  1684. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1685. printer_id,
  1686. state.state,
  1687. )
  1688. try:
  1689. await ws_manager.broadcast(
  1690. {
  1691. "type": "kill_switch_triggered",
  1692. "printer_id": printer_id,
  1693. "printer_name": printer_name,
  1694. "filename": filename,
  1695. "reason": "unauthorized_print",
  1696. }
  1697. )
  1698. except Exception as e:
  1699. status_logger.warning(
  1700. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1701. )
  1702. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1703. if previous_task is not None and not previous_task.done():
  1704. previous_task.cancel()
  1705. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1706. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1707. name=f"kill-switch-notification-{printer_id}",
  1708. )
  1709. else:
  1710. status_logger.warning(
  1711. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1712. printer_id,
  1713. state.state,
  1714. )
  1715. except Exception as e:
  1716. status_logger.warning(
  1717. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1718. )
  1719. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1720. try:
  1721. printer_info = printer_manager.get_printer(printer_id)
  1722. if printer_info:
  1723. await mqtt_relay.on_printer_status(
  1724. printer_id,
  1725. state,
  1726. printer_info.name,
  1727. printer_info.serial_number,
  1728. printer_manager.is_awaiting_plate_clear(printer_id),
  1729. )
  1730. except Exception:
  1731. pass # Don't fail status callback if MQTT fails
  1732. if _last_status_broadcast.get(printer_id) == status_key:
  1733. return # No change, skip WebSocket broadcast
  1734. _last_status_broadcast[printer_id] = status_key
  1735. # Check for progress milestone notifications (25%, 50%, 75%)
  1736. progress = state.progress or 0
  1737. is_printing = state.state in ("RUNNING", "PRINTING")
  1738. if is_printing and progress > 0:
  1739. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1740. if current_milestone is not None:
  1741. try:
  1742. from backend.app.models.printer import Printer
  1743. # Read the printer in a short session and release the connection
  1744. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1745. # pinned a pooled connection per milestone, per printer (issue #2572).
  1746. async with async_session() as db:
  1747. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1748. printer = result.scalar_one_or_none()
  1749. printer_name = printer.name if printer else f"Printer {printer_id}"
  1750. filename = state.subtask_name or state.gcode_file or "Unknown"
  1751. # remaining_time is in minutes, convert to seconds for notification
  1752. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1753. # Capture camera snapshot for notification image attachment (no DB held).
  1754. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1755. # Notification send needs a session (provider/template lookups).
  1756. async with async_session() as db:
  1757. await notification_service.on_print_progress(
  1758. printer_id,
  1759. printer_name,
  1760. filename,
  1761. current_milestone,
  1762. db,
  1763. remaining_time_seconds,
  1764. image_data=image_data,
  1765. )
  1766. except Exception as e:
  1767. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1768. elif progress < 5:
  1769. # Reset milestone tracking when print restarts or new print begins
  1770. _last_progress_milestone[printer_id] = 0
  1771. _first_layer_notified[printer_id] = False
  1772. # HMS error codes that should not trigger notifications even though they
  1773. # have known descriptions (e.g. user-initiated actions, not real errors).
  1774. _HMS_NOTIFICATION_SUPPRESS = {
  1775. "0500_400E", # Printing was cancelled (user action, not an error)
  1776. }
  1777. # Check for new HMS errors and send notifications
  1778. current_hms_errors = getattr(state, "hms_errors", []) or []
  1779. if current_hms_errors:
  1780. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1781. if new_errors:
  1782. try:
  1783. from backend.app.models.printer import Printer
  1784. # Read the printer in a short session and release the connection
  1785. # BEFORE the ~15s camera snapshot below (issue #2572).
  1786. async with async_session() as db:
  1787. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1788. printer = result.scalar_one_or_none()
  1789. printer_name = printer.name if printer else f"Printer {printer_id}"
  1790. # Format error details for notification
  1791. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1792. module_names = {
  1793. 0x03: "Print/Task",
  1794. 0x05: "Nozzle/Extruder",
  1795. 0x07: "AMS/Filament",
  1796. 0x0C: "Motion Controller",
  1797. 0x12: "Chamber",
  1798. }
  1799. # Capture camera snapshot once for all error notifications (no DB held).
  1800. error_image_data = await _capture_snapshot_for_notification(
  1801. printer_id, printer, logging.getLogger(__name__)
  1802. )
  1803. # Notification sends need a session (provider/template lookups).
  1804. async with async_session() as db:
  1805. sent_count = 0
  1806. for error in new_errors:
  1807. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1808. # Build short code like "0700_8010"
  1809. # Mask to 16 bits to handle printers that send larger values
  1810. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1811. error_code_masked = error_code_int & 0xFFFF
  1812. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1813. # Only notify for errors Bambu publishes text for — printers
  1814. # send undocumented codes that aren't real errors, and Bambu
  1815. # lists some with empty text. Resolved at parse time (#2926);
  1816. # short_code is still needed for the suppression set below.
  1817. description = error.description
  1818. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1819. continue
  1820. error_type = f"{module_name} Error"
  1821. error_detail = description
  1822. await notification_service.on_printer_error(
  1823. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1824. )
  1825. sent_count += 1
  1826. if sent_count:
  1827. logging.getLogger(__name__).info(
  1828. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1829. )
  1830. # Also publish to MQTT relay (no DB): every new fault that
  1831. # counts, with or without text, the same set the UI counts.
  1832. printer_info = printer_manager.get_printer(printer_id)
  1833. if printer_info:
  1834. errors_data = [
  1835. {
  1836. "code": e.code,
  1837. "attr": e.attr,
  1838. "module": e.module,
  1839. "severity": e.severity,
  1840. }
  1841. for e in new_errors
  1842. ]
  1843. await mqtt_relay.on_printer_error(
  1844. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1845. )
  1846. except Exception as e:
  1847. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1848. else:
  1849. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1850. # across a print state change) are forgotten. Some codes, e.g. chamber
  1851. # temperature regulation during PETG prints, toggle every few seconds.
  1852. _take_new_hms_faults(printer_id, [], state.state)
  1853. await ws_manager.send_printer_status(
  1854. printer_id,
  1855. printer_state_to_dict(
  1856. state,
  1857. printer_id,
  1858. printer_manager.get_model(printer_id),
  1859. printer_manager.get_drying_targets(printer_id),
  1860. ),
  1861. )
  1862. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1863. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1864. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1865. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1866. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1867. K-profiles are per-nozzle and the printer's calibration table is numbered
  1868. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1869. switch's other inlet therefore silently invalidates every configured slot in
  1870. it: the index stays put and now resolves against the other nozzle's table.
  1871. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1872. and 0.020 on the right kept the left profile after the move, and a manual
  1873. RFID re-read only re-asserted the same wrong one.
  1874. Configuring a slot is a deliberate preparation step, so this re-selects
  1875. rather than re-configures: only the calibration binding moves, and only for
  1876. slots whose spool already has a stored profile for the new nozzle. A slot
  1877. Bambuddy knows nothing about is left exactly as the operator left it.
  1878. """
  1879. logger = logging.getLogger(__name__)
  1880. target_extruder = extruder_for_inlet(inlet)
  1881. if target_extruder is None:
  1882. return
  1883. client = printer_manager.get_client(printer_id)
  1884. state = printer_manager.get_status(printer_id)
  1885. if not client or not state or not state.raw_data:
  1886. return
  1887. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1888. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1889. # the nozzle width, which changes both the K profile to select and the
  1890. # preset the slot should carry.
  1891. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1892. ams_raw = state.raw_data.get("ams")
  1893. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1894. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1895. if not unit:
  1896. return
  1897. try:
  1898. async with async_session() as db:
  1899. for tray in unit.get("tray", []):
  1900. tray_id = int(tray.get("id", -1))
  1901. if tray_id < 0 or not tray.get("tray_type"):
  1902. continue
  1903. current_idx = tray.get("cali_idx")
  1904. profile = await find_slot_kprofile_for_extruder(
  1905. db,
  1906. printer_id,
  1907. ams_id,
  1908. tray_id,
  1909. target_extruder,
  1910. nozzle_diameter,
  1911. printer_manager.get_model(printer_id),
  1912. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1913. )
  1914. if profile is None or profile.cali_idx is None:
  1915. continue
  1916. if current_idx == profile.cali_idx:
  1917. continue # Already on the right one.
  1918. logger.info(
  1919. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1920. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1921. printer_id,
  1922. ams_id,
  1923. tray_id,
  1924. inlet,
  1925. target_extruder,
  1926. profile.name,
  1927. current_idx,
  1928. profile.cali_idx,
  1929. profile.k_value,
  1930. )
  1931. client.extrusion_cali_sel(
  1932. ams_id=ams_id,
  1933. tray_id=tray_id,
  1934. cali_idx=profile.cali_idx,
  1935. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1936. nozzle_diameter=nozzle_diameter,
  1937. )
  1938. except Exception as e:
  1939. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1940. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1941. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1942. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1943. from the delayed re-check -- which is why it takes the AMS data and print
  1944. state as arguments instead of reading them from the push (#3186).
  1945. """
  1946. logger = logging.getLogger(__name__)
  1947. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1948. # Auto-unlink spool assignments with stale fingerprints. Under the
  1949. # per-printer assignment lock since #3186: the held-removal re-check runs
  1950. # this outside any MQTT push, so it can now overlap one.
  1951. try:
  1952. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1953. from sqlalchemy.orm import selectinload
  1954. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1955. from backend.app.models.spool import Spool as _Spool
  1956. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1957. from backend.app.services.ams_slot_presence import spool_present
  1958. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1959. # Built-in assignments only. Since #2812 they survive a switch to
  1960. # Spoolman mode rather than being deleted by it, and this pass ends
  1961. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1962. # time as the AMS contents changed under the other mode, undoing the
  1963. # preservation more slowly but just as completely.
  1964. assignments = []
  1965. if not await spoolman_owns_assignments(db):
  1966. result = await db.execute(
  1967. select(SA)
  1968. .where(SA.printer_id == printer_id)
  1969. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1970. )
  1971. assignments = result.scalars().all()
  1972. # ``printing_now`` (top of this function) keeps a runout from
  1973. # unlinking the spool that fed the print — the next idle-time pass
  1974. # unlinks it if the user really did take it out.
  1975. stale = []
  1976. # Removals this pass is holding rather than unlinking (#3186).
  1977. held: set[tuple] = set()
  1978. for assignment in assignments:
  1979. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1980. if assignment.ams_id == 255:
  1981. ps = printer_manager.get_status(printer_id)
  1982. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1983. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1984. current_tray = None
  1985. for vt in vt_tray_raw:
  1986. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1987. current_tray = vt
  1988. break
  1989. if not current_tray:
  1990. # vt_tray data may not have arrived yet — keep assignment
  1991. continue
  1992. else:
  1993. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1994. if not current_tray:
  1995. if printing_now:
  1996. logger.info(
  1997. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1998. assignment.spool_id,
  1999. assignment.ams_id,
  2000. assignment.tray_id,
  2001. )
  2002. continue
  2003. # A whole AMS unit can drop out of one push and come back in
  2004. # the next; only a slot that stays gone is a removal (#3186).
  2005. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2006. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2007. held.add(hold_key)
  2008. logger.info(
  2009. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2010. "unlinking if it is still gone in %ds",
  2011. assignment.spool_id,
  2012. assignment.ams_id,
  2013. assignment.tray_id,
  2014. int(slot_unlink_grace.GRACE_SECONDS),
  2015. )
  2016. continue
  2017. logger.info(
  2018. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2019. assignment.spool_id,
  2020. assignment.ams_id,
  2021. assignment.tray_id,
  2022. )
  2023. stale.append(assignment) # Slot empty
  2024. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2025. # A Bambu Lab spool is in this slot — check if it's the same spool
  2026. # that's currently assigned. If yes, keep the assignment (avoids
  2027. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2028. # the printer's filament preset on every startup).
  2029. tray_uuid = current_tray.get("tray_uuid", "")
  2030. tag_uid = current_tray.get("tag_uid", "")
  2031. spool = assignment.spool
  2032. spool_matches = False
  2033. if spool:
  2034. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2035. spool.tag_uid
  2036. and tag_uid
  2037. and tag_uid != "0000000000000000"
  2038. and spool.tag_uid.upper() == tag_uid.upper()
  2039. ):
  2040. spool_matches = True
  2041. if spool_matches:
  2042. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2043. cur_color = current_tray.get("tray_color", "")
  2044. cur_type = current_tray.get("tray_type", "")
  2045. fp_color = assignment.fingerprint_color or ""
  2046. fp_type = assignment.fingerprint_type or ""
  2047. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2048. assignment.fingerprint_color = cur_color
  2049. assignment.fingerprint_type = cur_type
  2050. logger.debug(
  2051. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2052. assignment.spool_id,
  2053. assignment.ams_id,
  2054. assignment.tray_id,
  2055. )
  2056. continue
  2057. # Different BL spool or unrecognized — unlink so auto-assign can match
  2058. logger.info(
  2059. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2060. assignment.spool_id,
  2061. assignment.ams_id,
  2062. assignment.tray_id,
  2063. tray_uuid,
  2064. )
  2065. stale.append(assignment)
  2066. else:
  2067. cur_color = current_tray.get("tray_color", "")
  2068. cur_type = current_tray.get("tray_type", "")
  2069. cur_state = current_tray.get("state")
  2070. fp_color = assignment.fingerprint_color or ""
  2071. fp_type = assignment.fingerprint_type or ""
  2072. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2073. # the slot was empty when the user pre-assigned via SpoolBuddy
  2074. # (the firmware drops ams_filament_setting on empty slots, so
  2075. # MQTT was deferred). The moment any filament gets inserted
  2076. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2077. # reconfigured spool — fire the deferred configuration.
  2078. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2079. # extruder" code) OR, on firmwares that don't use the state
  2080. # enum meaningfully, a non-empty tray_type when state is
  2081. # NOT one of the firmware's explicit empty signals (9, 10).
  2082. # state-only was wrong for firmwares that never set 11 — A1
  2083. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2084. # always report state=3 — so the replay never fired for them
  2085. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2086. # explicit "empty" signals authoritative over any stale
  2087. # tray_type that might survive the relay's auto-clearing.
  2088. #
  2089. # tray_exist_bits comes first because that guard cannot tell
  2090. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2091. # writes state=9 when the bit is 0 and leaves it there when the
  2092. # bit returns. A non-RFID spool inserted into a pre-assigned
  2093. # slot brings no tray_type with it, so the stale 9 made this
  2094. # expression false forever and the deferred config never fired
  2095. # — the deadlock #1322 removed from the assign path, still in
  2096. # place here (#3084, #3100).
  2097. loaded = spool_present(current_tray) is True or (
  2098. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2099. )
  2100. if not fp_type.strip() and loaded and assignment.spool:
  2101. try:
  2102. from backend.app.api.routes.inventory import (
  2103. apply_spool_to_slot_via_mqtt,
  2104. )
  2105. await apply_spool_to_slot_via_mqtt(
  2106. db=db,
  2107. current_user=None,
  2108. spool=assignment.spool,
  2109. printer_id=printer_id,
  2110. ams_id=assignment.ams_id,
  2111. tray_id=assignment.tray_id,
  2112. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2113. current_tray_type=cur_type,
  2114. )
  2115. logger.info(
  2116. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2117. assignment.spool_id,
  2118. printer_id,
  2119. assignment.ams_id,
  2120. assignment.tray_id,
  2121. )
  2122. except Exception:
  2123. logger.exception(
  2124. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2125. assignment.spool_id,
  2126. printer_id,
  2127. assignment.ams_id,
  2128. assignment.tray_id,
  2129. )
  2130. assignment.fingerprint_color = cur_color
  2131. assignment.fingerprint_type = cur_type
  2132. continue
  2133. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2134. # Blank tray data mid-print is a runout, not a swap: the
  2135. # firmware clears colour and type when it unloads a spool
  2136. # it just emptied. Unlinking here would erase the record
  2137. # of which spool fed the print so far.
  2138. if printing_now and not cur_color.strip() and not cur_type.strip():
  2139. logger.info(
  2140. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2141. "(runout?)",
  2142. assignment.spool_id,
  2143. assignment.ams_id,
  2144. assignment.tray_id,
  2145. )
  2146. continue
  2147. # Same reasoning off the print, on firmware's own say-so:
  2148. # a blank tray report from a slot whose tray_exist_bits
  2149. # bit is set describes a spool the AMS cannot identify —
  2150. # a non-RFID one, or one whose slot was reset — not a
  2151. # spool that was taken out. Deleting the assignment there
  2152. # threw away the identity the user had supplied, which is
  2153. # the only place it existed (#3100). A slot the bit calls
  2154. # empty, or one that carries no bit at all, still unlinks.
  2155. #
  2156. # Unless the slot was reported empty first: a removal
  2157. # already held means a spool came out and another went
  2158. # in, so the blank report keeps the hold running below
  2159. # rather than cancelling it (#3186).
  2160. if (
  2161. spool_present(current_tray) is True
  2162. and not cur_color.strip()
  2163. and not cur_type.strip()
  2164. and not slot_unlink_grace.is_held(
  2165. printer_id,
  2166. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2167. )
  2168. ):
  2169. logger.info(
  2170. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2171. "tray reports no filament data yet",
  2172. assignment.spool_id,
  2173. assignment.ams_id,
  2174. assignment.tray_id,
  2175. )
  2176. continue
  2177. # A blank report the presence bit does not vouch for is
  2178. # still only one push. An idle X1C cleared a whole AMS
  2179. # unit's bits, colour and type for a moment and lost
  2180. # four saved assignments that way (#3186); unlink only
  2181. # if the slot is still blank after the grace period.
  2182. if not cur_color.strip() and not cur_type.strip():
  2183. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2184. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2185. held.add(hold_key)
  2186. logger.info(
  2187. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2188. "unlinking if it is still blank in %ds",
  2189. assignment.spool_id,
  2190. assignment.ams_id,
  2191. assignment.tray_id,
  2192. int(slot_unlink_grace.GRACE_SECONDS),
  2193. )
  2194. continue
  2195. # Fingerprint mismatch — but check if tray now matches the
  2196. # assigned spool (e.g. auto-configure changed the tray).
  2197. # Both sides are reduced to the type the slot can carry
  2198. # before comparing: the assign path writes that rather
  2199. # than the spool's raw material (#2902), so a spool whose
  2200. # material is a product line — "PLA+", "HTPLA" — reports
  2201. # back as "PLA" and would otherwise fail this check and
  2202. # be auto-unlinked from the slot it was just assigned to.
  2203. # Reducing the printer's side too keeps slots configured
  2204. # by an older Bambuddy, still reporting "PLA+", matching.
  2205. spool = assignment.spool
  2206. if spool:
  2207. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2208. # Two ways the assign path can have arrived at the
  2209. # slot's type, so both count as "we wrote this".
  2210. # The material column is one; the spool's preset is
  2211. # the other, and it outranks the material when the
  2212. # spool has one -- a spool whose material says PLA
  2213. # and whose preset is "Bambu PLA Aero" puts
  2214. # PLA-AERO in the slot (#2902). Read from the stored
  2215. # preset name rather than resolving the preset,
  2216. # because this runs on every AMS push and a cloud
  2217. # lookup here would be both slow and unavailable on
  2218. # the unauthenticated replay path.
  2219. spool_types = {printer_filament_type(spool.material).upper()}
  2220. if spool.slicer_filament_name:
  2221. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2222. # An imported local preset stores its type outright,
  2223. # which is what the assign path used -- and the name
  2224. # above may be unset. One keyed read, and only on a
  2225. # mismatch, which is rare.
  2226. #
  2227. # slicer_filament is free text up to fifty characters,
  2228. # so the digits have to be checked against the range
  2229. # of the integer primary key they are about to be
  2230. # compared with. Postgres raises on an out-of-range
  2231. # integer rather than simply not matching, and that
  2232. # would poison this session and abandon the rest of
  2233. # the cleanup pass.
  2234. lp_ref = (spool.slicer_filament or "").strip()
  2235. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2236. from backend.app.models.local_preset import LocalPreset as _LP
  2237. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2238. if lp_type:
  2239. spool_types.add(printer_filament_type(lp_type).upper())
  2240. if (
  2241. _colors_similar(cur_color, spool_color)
  2242. and printer_filament_type(cur_type).upper() in spool_types
  2243. ):
  2244. logger.info(
  2245. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2246. assignment.spool_id,
  2247. assignment.ams_id,
  2248. assignment.tray_id,
  2249. )
  2250. assignment.fingerprint_color = cur_color
  2251. assignment.fingerprint_type = cur_type
  2252. continue
  2253. logger.info(
  2254. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2255. assignment.spool_id,
  2256. assignment.ams_id,
  2257. assignment.tray_id,
  2258. cur_color,
  2259. cur_type,
  2260. fp_color,
  2261. fp_type,
  2262. spool.rgba if spool else "?",
  2263. spool.material if spool else "?",
  2264. )
  2265. stale.append(assignment) # Spool changed
  2266. slot_unlink_grace.settle(printer_id, "inventory", held)
  2267. # Snapshot slots before delete — ORM attribute access after the
  2268. # commit would refresh against a deleted row.
  2269. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2270. for a in stale:
  2271. await db.delete(a)
  2272. if stale:
  2273. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2274. # Commit any changes (stale deletions and/or fingerprint updates)
  2275. await db.commit()
  2276. # Tell open browsers the assignment is gone (#2575). Only the manual
  2277. # REST assign/unassign endpoints broadcast this event; without it the
  2278. # frontend's spool-assignments cache keeps rendering the unlinked
  2279. # spool on the slot until an unrelated refetch — which reads exactly
  2280. # like "the fix didn't work" (reporter verified: a browser refresh
  2281. # after the swap showed the correct state all along).
  2282. for ams_id, tray_id in unlinked_slots:
  2283. await ws_manager.broadcast(
  2284. {
  2285. "type": "spool_assignment_changed",
  2286. "printer_id": printer_id,
  2287. "ams_id": ams_id,
  2288. "tray_id": tray_id,
  2289. }
  2290. )
  2291. except Exception as e:
  2292. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2293. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2294. """Delete Spoolman slot rows whose held removal has run its grace period.
  2295. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2296. talks to Spoolman for every tray; this only needs the local rows, so it
  2297. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2298. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2299. not in a slot the presence bit calls occupied -- and nothing else.
  2300. """
  2301. logger = logging.getLogger(__name__)
  2302. try:
  2303. async with async_session() as db:
  2304. from backend.app.api.routes.settings import get_setting
  2305. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2306. from backend.app.services.ams_slot_presence import spool_present
  2307. enabled = await get_setting(db, "spoolman_enabled")
  2308. if not enabled or enabled.lower() != "true":
  2309. return
  2310. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2311. if sync_mode and sync_mode != "auto":
  2312. return
  2313. trays: dict[tuple[int, int], dict] = {}
  2314. for ams_unit in ams_data or []:
  2315. if not isinstance(ams_unit, dict):
  2316. continue
  2317. for tray in ams_unit.get("tray", []):
  2318. if isinstance(tray, dict):
  2319. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2320. rows = (
  2321. (
  2322. await db.execute(
  2323. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2324. )
  2325. )
  2326. .scalars()
  2327. .all()
  2328. )
  2329. held: set[tuple] = set()
  2330. expired: list[tuple[int, int]] = []
  2331. for row in rows:
  2332. tray = trays.get((row.ams_id, row.tray_id))
  2333. if tray is None or printing_now:
  2334. continue
  2335. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2336. continue
  2337. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2338. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2339. continue
  2340. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2341. expired.append((row.ams_id, row.tray_id))
  2342. else:
  2343. held.add(hold_key)
  2344. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2345. if not expired:
  2346. return
  2347. # A statement rather than ORM deletes, like the sync pass: the two
  2348. # can overlap, and a row the other already removed must not fail
  2349. # this commit.
  2350. for ams_id, tray_id in expired:
  2351. await db.execute(
  2352. delete(SpoolmanSlotAssignment).where(
  2353. SpoolmanSlotAssignment.printer_id == printer_id,
  2354. SpoolmanSlotAssignment.ams_id == ams_id,
  2355. SpoolmanSlotAssignment.tray_id == tray_id,
  2356. )
  2357. )
  2358. await db.commit()
  2359. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2360. for ams_id, tray_id in expired:
  2361. await ws_manager.broadcast(
  2362. {
  2363. "type": "spool_assignment_changed",
  2364. "printer_id": printer_id,
  2365. "ams_id": ams_id,
  2366. "tray_id": tray_id,
  2367. }
  2368. )
  2369. except Exception as e:
  2370. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2371. async def _recheck_held_unlinks(printer_id: int) -> None:
  2372. """Re-run just the slot cleanup against the printer's current AMS state.
  2373. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2374. passes otherwise run only when the AMS hash changes, and a slot that went
  2375. empty and stayed empty may never change it again.
  2376. """
  2377. status = printer_manager.get_status(printer_id)
  2378. # A disconnected printer's state is its last report, not a new one: acting
  2379. # on it would "confirm" a removal nobody has seen for the whole grace
  2380. # period. Leave the holds; the first push after reconnecting decides.
  2381. if status is None or not status.connected:
  2382. return
  2383. ams_raw = status.raw_data.get("ams")
  2384. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2385. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2386. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2387. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2388. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2389. async def on_ams_change(printer_id: int, ams_data: list):
  2390. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2391. logger = logging.getLogger(__name__)
  2392. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2393. # on_print_complete may pop _active_sessions during our awaits (#880).
  2394. from backend.app.services.usage_tracker import _active_sessions
  2395. _print_active = printer_id in _active_sessions
  2396. # A slot that reports empty while a print is running is a filament runout,
  2397. # not a spool swap: the spool is still physically in the AMS, just
  2398. # consumed. Dropping either inventory backend's slot link there loses the
  2399. # only record of which spool fed the print, so the completion path can't
  2400. # charge the runout segment to anything. Both cleanup passes below consult
  2401. # this; computed once, up front, so neither depends on the other having run.
  2402. _unlink_state = printer_manager.get_status(printer_id)
  2403. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2404. # MQTT relay - publish AMS change
  2405. try:
  2406. printer_info = printer_manager.get_printer(printer_id)
  2407. if printer_info:
  2408. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2409. except Exception:
  2410. pass # Don't fail AMS callback if MQTT fails
  2411. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2412. # This ensures frontend gets immediate updates when AMS slots are configured
  2413. try:
  2414. state = printer_manager.get_status(printer_id)
  2415. if state:
  2416. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2417. await ws_manager.send_printer_status(
  2418. printer_id,
  2419. printer_state_to_dict(
  2420. state,
  2421. printer_id,
  2422. printer_manager.get_model(printer_id),
  2423. printer_manager.get_drying_targets(printer_id),
  2424. ),
  2425. )
  2426. except Exception as e:
  2427. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2428. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2429. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2430. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2431. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2432. # "no existing assignment" for the same (printer, ams, tray) and race to
  2433. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2434. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2435. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2436. try:
  2437. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2438. from sqlalchemy.orm import selectinload
  2439. from backend.app.api.routes.settings import get_setting
  2440. from backend.app.models.spool import Spool
  2441. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2442. from backend.app.services.spool_tag_matcher import (
  2443. auto_assign_spool,
  2444. create_spool_from_tray,
  2445. find_matching_untagged_spool,
  2446. get_spool_by_tag,
  2447. is_bambu_tag,
  2448. is_valid_tag,
  2449. link_tag_to_inventory_spool,
  2450. )
  2451. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2452. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2453. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2454. if not _spoolman_on or _spoolman_on.lower() != "true":
  2455. for ams_unit in ams_data:
  2456. if not isinstance(ams_unit, dict):
  2457. continue
  2458. ams_id = int(ams_unit.get("id", 0))
  2459. for tray in ams_unit.get("tray", []):
  2460. if not isinstance(tray, dict):
  2461. continue
  2462. tray_id = int(tray.get("id", 0))
  2463. tag_uid = tray.get("tag_uid", "")
  2464. tray_uuid = tray.get("tray_uuid", "")
  2465. tray_info_idx = tray.get("tray_info_idx", "")
  2466. if not tray.get("tray_type"):
  2467. # Slot reported empty — drop any cached unknown-tag
  2468. # broadcast so reinserting the same spool re-prompts.
  2469. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2470. continue # Empty slot
  2471. # Check if assignment already exists for this slot
  2472. existing = await db.execute(
  2473. select(SA)
  2474. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2475. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2476. )
  2477. existing_assignment = existing.scalar_one_or_none()
  2478. if existing_assignment:
  2479. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2480. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2481. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2482. # Skip during active prints: the usage tracker handles deduction
  2483. # precisely via 3MF data on print completion. Without this guard the
  2484. # AMS remain% SET and the usage tracker ADD both fire from the same
  2485. # MQTT message, doubling the deduction (#880).
  2486. if _print_active:
  2487. continue
  2488. remain_raw = tray.get("remain")
  2489. if (
  2490. remain_raw is not None
  2491. and existing_assignment.spool
  2492. and not existing_assignment.spool.weight_locked
  2493. ):
  2494. try:
  2495. remain_val = int(remain_raw)
  2496. except (TypeError, ValueError):
  2497. remain_val = -1
  2498. if 1 <= remain_val <= 100:
  2499. lw = existing_assignment.spool.label_weight or 1000
  2500. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2501. current_used = existing_assignment.spool.weight_used or 0
  2502. if new_used > current_used + 1:
  2503. logger.info(
  2504. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2505. existing_assignment.spool_id,
  2506. current_used,
  2507. new_used,
  2508. remain_val,
  2509. )
  2510. existing_assignment.spool.weight_used = new_used
  2511. await db.commit()
  2512. # Re-apply stored K-profile when the live tray's
  2513. # cali_idx drifted from the spool's stored profile.
  2514. # This catches "reset slot → re-read" and any other
  2515. # path where the firmware loses the user's K-profile
  2516. # selection while the SpoolAssignment row persists.
  2517. # Per the maintainer's rule: any time a spool tag is
  2518. # identified and matches inventory, the slot must be
  2519. # configured with the spool's stored settings. Without
  2520. # this block the existing-assignment branch only ran
  2521. # weight-sync and let the firmware-default cali_idx win.
  2522. try:
  2523. spool = existing_assignment.spool
  2524. if (
  2525. spool is not None
  2526. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2527. and spool.k_profiles
  2528. ):
  2529. state = printer_manager.get_status(printer_id)
  2530. slot_nozzle = resolve_slot_nozzle(
  2531. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2532. )
  2533. nozzle_diameter = slot_nozzle.diameter
  2534. slot_extruder = slot_nozzle.extruder
  2535. # Prefer exact extruder match, fall back to
  2536. # extruder-agnostic kp for the same printer +
  2537. # nozzle. Avoids hard-skipping when the AMS is
  2538. # mapped differently than at calibration time.
  2539. matching_kp = None
  2540. fallback_kp = None
  2541. for kp in spool.k_profiles:
  2542. if (
  2543. kp.printer_id != printer_id
  2544. or kp.nozzle_diameter != nozzle_diameter
  2545. or kp.cali_idx is None
  2546. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2547. ):
  2548. continue
  2549. if (
  2550. slot_extruder is not None
  2551. and kp.extruder is not None
  2552. and kp.extruder == slot_extruder
  2553. ):
  2554. matching_kp = kp
  2555. break
  2556. if fallback_kp is None:
  2557. fallback_kp = kp
  2558. chosen_kp = matching_kp or fallback_kp
  2559. if chosen_kp is not None:
  2560. live_cali_idx = tray.get("cali_idx")
  2561. # Only fire MQTT when the printer's live
  2562. # cali_idx differs from the stored value.
  2563. # Avoids spamming the broker on every
  2564. # MQTT push during steady-state operation.
  2565. if live_cali_idx != chosen_kp.cali_idx:
  2566. client = printer_manager.get_client(printer_id)
  2567. if client:
  2568. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2569. client.extrusion_cali_sel(
  2570. ams_id=ams_id,
  2571. tray_id=tray_id,
  2572. cali_idx=chosen_kp.cali_idx,
  2573. filament_id=cali_filament_id,
  2574. nozzle_diameter=nozzle_diameter,
  2575. )
  2576. logger.info(
  2577. "Re-applied K-profile cali_idx=%d for spool %d "
  2578. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2579. chosen_kp.cali_idx,
  2580. spool.id,
  2581. printer_id,
  2582. ams_id,
  2583. tray_id,
  2584. live_cali_idx,
  2585. )
  2586. except Exception:
  2587. logger.exception(
  2588. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2589. printer_id,
  2590. ams_id,
  2591. tray_id,
  2592. )
  2593. continue
  2594. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2595. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2596. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2597. if not spool:
  2598. # Try matching an untagged inventory spool (same material/color)
  2599. spool = await find_matching_untagged_spool(db, tray)
  2600. if spool:
  2601. await link_tag_to_inventory_spool(db, spool, tray)
  2602. elif _auto_add_unknown:
  2603. spool = await create_spool_from_tray(db, tray)
  2604. else:
  2605. # Auto-add disabled: surface the slot so the
  2606. # user can add it manually via the UI.
  2607. await _broadcast_unknown_tag(
  2608. printer_id=printer_id,
  2609. ams_id=ams_id,
  2610. tray_id=tray_id,
  2611. tag_uid=tag_uid,
  2612. tray_uuid=tray_uuid,
  2613. tray_type=tray.get("tray_type"),
  2614. tray_color=tray.get("tray_color"),
  2615. tray_sub_brands=tray.get("tray_sub_brands"),
  2616. tray_count=len(ams_unit.get("tray", [])),
  2617. )
  2618. continue
  2619. # Slot matched (existing tag, untagged inventory
  2620. # match, or freshly auto-created spool) — drop any
  2621. # stale dedup so a future tag swap re-prompts.
  2622. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2623. await auto_assign_spool(
  2624. printer_id,
  2625. ams_id,
  2626. tray_id,
  2627. spool,
  2628. printer_manager,
  2629. db,
  2630. tray_info_idx=tray_info_idx,
  2631. )
  2632. await db.commit()
  2633. await ws_manager.broadcast(
  2634. {
  2635. "type": "spool_auto_assigned",
  2636. "printer_id": printer_id,
  2637. "ams_id": ams_id,
  2638. "tray_id": tray_id,
  2639. "spool_id": spool.id,
  2640. }
  2641. )
  2642. logger.info(
  2643. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2644. spool.id,
  2645. printer_id,
  2646. ams_id,
  2647. tray_id,
  2648. )
  2649. elif is_valid_tag(tag_uid, tray_uuid):
  2650. # Non-BL spool with some tag — let user choose
  2651. await _broadcast_unknown_tag(
  2652. printer_id=printer_id,
  2653. ams_id=ams_id,
  2654. tray_id=tray_id,
  2655. tag_uid=tag_uid,
  2656. tray_uuid=tray_uuid,
  2657. tray_type=tray.get("tray_type"),
  2658. tray_color=tray.get("tray_color"),
  2659. tray_sub_brands=tray.get("tray_sub_brands"),
  2660. tray_count=len(ams_unit.get("tray", [])),
  2661. )
  2662. # No-tag slots (generic non-RFID filament) are left alone:
  2663. # nothing to identify, prompting "+ Add" would just create
  2664. # ghost spools with empty tags on every confirm.
  2665. except Exception as e:
  2666. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2667. try:
  2668. async with async_session() as db:
  2669. from backend.app.api.routes.settings import get_setting
  2670. from backend.app.models.printer import Printer
  2671. # Check if Spoolman is enabled
  2672. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2673. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2674. return
  2675. # Check sync mode
  2676. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2677. if sync_mode and sync_mode != "auto":
  2678. return # Only sync on auto mode
  2679. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2680. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2681. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2682. # always owned by per-print tracking, never by AMS auto-sync. The
  2683. # setting is still read by the settings UI for backwards compat but
  2684. # has no effect on the sync path here.
  2685. # Get Spoolman URL
  2686. spoolman_url = await get_setting(db, "spoolman_url")
  2687. if not spoolman_url:
  2688. return
  2689. # Get or create Spoolman client
  2690. client = await get_spoolman_client()
  2691. if not client:
  2692. try:
  2693. client = await init_spoolman_client(spoolman_url)
  2694. except ValueError as exc:
  2695. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2696. return
  2697. # Check if Spoolman is reachable
  2698. if not await client.health_check():
  2699. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2700. return
  2701. # Get printer name for location
  2702. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2703. printer = result.scalar_one_or_none()
  2704. printer_name = printer.name if printer else f"Printer {printer_id}"
  2705. # OPTIMIZATION: Fetch all spools once before processing trays
  2706. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2707. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2708. try:
  2709. cached_spools = await client.get_spools()
  2710. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2711. except Exception as e:
  2712. logger.error(
  2713. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2714. printer_id,
  2715. e,
  2716. )
  2717. return
  2718. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2719. from sqlalchemy.orm import selectinload
  2720. from backend.app.models.spool_assignment import SpoolAssignment
  2721. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2722. from backend.app.services.ams_slot_presence import spool_present
  2723. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2724. # Built-in remaining weight, used by sync_ams_tray only when the
  2725. # firmware reports an unusable remain%/tray_weight for a slot.
  2726. #
  2727. # Left empty since #2812. This block runs in Spoolman mode only,
  2728. # and until then the built-in table was emptied on the switch, so
  2729. # there was never anything here to read and the fallback was inert.
  2730. # Preserving those rows makes it live again, and it is keyed by slot
  2731. # rather than by spool: after a mode switch the tray may well hold
  2732. # different filament, and ``create_spool`` writes ``remaining_weight``
  2733. # unconditionally, so a stale figure would be seeded into a brand new
  2734. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2735. # intent survives for whoever revisits the cross-mode fallback.
  2736. inventory_weights: dict[tuple[int, int], float] = {}
  2737. if not await spoolman_owns_assignments(db):
  2738. try:
  2739. assign_result = await db.execute(
  2740. select(SpoolAssignment)
  2741. .options(selectinload(SpoolAssignment.spool))
  2742. .where(SpoolAssignment.printer_id == printer_id)
  2743. )
  2744. for assignment in assign_result.scalars().all():
  2745. spool = assignment.spool
  2746. if spool and spool.label_weight > 0:
  2747. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2748. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2749. except Exception as e:
  2750. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2751. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2752. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2753. try:
  2754. slot_result = await db.execute(
  2755. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2756. )
  2757. for slot in slot_result.scalars().all():
  2758. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2759. except Exception as e:
  2760. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2761. # Sync each AMS tray and collect slot changes for DB persistence
  2762. synced = 0
  2763. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2764. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2765. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2766. for ams_unit in ams_data:
  2767. if not isinstance(ams_unit, dict):
  2768. continue
  2769. ams_id = int(ams_unit.get("id", 0))
  2770. trays = ams_unit.get("tray", [])
  2771. for tray_data in trays:
  2772. if not isinstance(tray_data, dict):
  2773. continue
  2774. tray_id_raw = int(tray_data.get("id", 0))
  2775. tray = client.parse_ams_tray(ams_id, tray_data)
  2776. if not tray:
  2777. # Empty tray slot — record for local assignment cleanup
  2778. # and drop any cached unknown-tag broadcast so a
  2779. # reinserted spool re-prompts.
  2780. #
  2781. # Not during a running print: a slot that empties there
  2782. # is a filament runout, and the spool is still in the
  2783. # AMS. `spoolman_slot_assignments` is how a tag-less
  2784. # spool assigned through the Bambuddy UI is resolved at
  2785. # completion (#1459), so deleting the row mid-print
  2786. # loses the runout segment's usage — the same failure
  2787. # the internal inventory's auto-unlink had.
  2788. #
  2789. # Nor when firmware's presence bit says the slot is
  2790. # occupied. parse_ams_tray calls a tray with no type or
  2791. # no colour empty, and a spool the AMS cannot read has
  2792. # neither until something configures it — so a tag-less
  2793. # spool assigned through the UI had its row deleted by
  2794. # the first idle push after it was inserted. Same
  2795. # deletion as the internal inventory's in #3100, same
  2796. # answer, so the two modes stay in step.
  2797. #
  2798. # And only once the slot has stayed empty for the grace
  2799. # period -- the internal inventory's #3186 answer, for
  2800. # the same one-push blank.
  2801. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2802. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2803. if not printing_now and (
  2804. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2805. ):
  2806. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2807. empty_slots.append((ams_id, tray_id_raw))
  2808. else:
  2809. spoolman_held.add(hold_key)
  2810. logger.info(
  2811. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2812. "unlinking if it is still empty in %ds",
  2813. ams_id,
  2814. tray_id_raw,
  2815. linked_spool,
  2816. int(slot_unlink_grace.GRACE_SECONDS),
  2817. )
  2818. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2819. continue
  2820. spool_tag = (
  2821. tray.tray_uuid
  2822. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2823. else tray.tag_uid
  2824. )
  2825. # Provide the hint only when no RFID is available
  2826. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2827. try:
  2828. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2829. result = await client.sync_ams_tray(
  2830. tray,
  2831. printer_name,
  2832. db,
  2833. # Per-print tracking is the only weight writer (#1119).
  2834. # AMS auto-sync still maintains spool metadata / slot
  2835. # assignments but no longer touches remaining_weight.
  2836. disable_weight_sync=True,
  2837. cached_spools=cached_spools,
  2838. inventory_remaining=inv_remaining,
  2839. spoolman_spool_id_hint=hint,
  2840. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2841. )
  2842. if result is None and spool_tag and not auto_add_unknown_rfid:
  2843. # Spoolman skipped auto-create per user setting — surface
  2844. # the slot so the UI can offer "+ Add to inventory".
  2845. await _broadcast_unknown_tag(
  2846. printer_id=printer_id,
  2847. ams_id=ams_id,
  2848. tray_id=tray.tray_id,
  2849. tag_uid=tray.tag_uid or "",
  2850. tray_uuid=tray.tray_uuid or "",
  2851. tray_type=tray.tray_type,
  2852. tray_color=tray.tray_color,
  2853. tray_sub_brands=tray.tray_sub_brands,
  2854. tray_count=len(trays),
  2855. )
  2856. elif result:
  2857. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2858. if result:
  2859. synced += 1
  2860. if result.get("id"):
  2861. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2862. # If a new spool was created, add it to the cache
  2863. # so subsequent trays can find it if they reference the same tag
  2864. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2865. if not spool_exists:
  2866. cached_spools.append(result)
  2867. logger.debug(
  2868. "[Printer %s] Added newly created spool %s to cache",
  2869. printer_id,
  2870. result["id"],
  2871. )
  2872. # Reconcile slot_preset_mappings (the same row internal
  2873. # mode keeps in sync via inventory + spool_tag_matcher).
  2874. # Without this the slot card surfaces the previous spool's
  2875. # preset name — same bug shape, different inventory mode.
  2876. from backend.app.services.slot_preset_writer import (
  2877. upsert_slot_preset_for_spoolman_spool,
  2878. )
  2879. await upsert_slot_preset_for_spoolman_spool(
  2880. db=db,
  2881. spoolman_spool=result,
  2882. tray_info_idx=tray.tray_info_idx or "",
  2883. tray_sub_brands=tray.tray_sub_brands or "",
  2884. tray_type=tray.tray_type or "",
  2885. printer_id=printer_id,
  2886. ams_id=ams_id,
  2887. tray_id=tray.tray_id,
  2888. )
  2889. except Exception as e:
  2890. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2891. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2892. if synced > 0:
  2893. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2894. # Persist slot assignment changes to the local table
  2895. if slot_changes or empty_slots:
  2896. try:
  2897. for ams_id, tray_id, spool_id in slot_changes:
  2898. await db.execute(
  2899. text(
  2900. "INSERT INTO spoolman_slot_assignments"
  2901. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2902. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2903. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2904. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2905. ),
  2906. {
  2907. "printer_id": printer_id,
  2908. "ams_id": ams_id,
  2909. "tray_id": tray_id,
  2910. "spool_id": spool_id,
  2911. },
  2912. )
  2913. for ams_id, tray_id in empty_slots:
  2914. await db.execute(
  2915. delete(SpoolmanSlotAssignment).where(
  2916. SpoolmanSlotAssignment.printer_id == printer_id,
  2917. SpoolmanSlotAssignment.ams_id == ams_id,
  2918. SpoolmanSlotAssignment.tray_id == tray_id,
  2919. )
  2920. )
  2921. await db.commit()
  2922. except Exception as e:
  2923. await db.rollback()
  2924. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2925. else:
  2926. # Tell open browsers the slot changed. This loop rewrites
  2927. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2928. # above, and the AMS slot card reads that row ahead of the
  2929. # live tray_info_idx -- so with no event the card keeps
  2930. # showing the previous spool's preset name. Internal mode
  2931. # raises spool_auto_assigned for the same reason; this loop
  2932. # broadcast nothing at all, which made Spoolman mode the
  2933. # worse half of the same bug. On the else branch so a
  2934. # failed commit stays silent and a broadcast failure cannot
  2935. # roll back rows that are already committed.
  2936. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2937. await ws_manager.broadcast(
  2938. {
  2939. "type": "spool_assignment_changed",
  2940. "printer_id": printer_id,
  2941. "ams_id": ams_id,
  2942. "tray_id": tray_id,
  2943. }
  2944. )
  2945. except Exception as e:
  2946. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2947. # Largest finish photo attached to a notification; a bigger one is still linked.
  2948. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2949. async def _finish_photo_for_notification(
  2950. db, archive, archive_id: int, filename: str
  2951. ) -> tuple[str | None, bytes | None]:
  2952. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2953. With authentication off the link is the archive's own photo route, as it
  2954. always was: it opens without a login and doesn't expire. With
  2955. authentication on that route needs a media token, which nothing tapping a
  2956. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2957. link only ever answered 401. The photo is then saved as a notification
  2958. photo as well (utils/notification_photos.py) and the link points there: an
  2959. unguessable name that opens this one photo and nothing else, for 3 days.
  2960. The link is relative when no External URL is set. Bytes over
  2961. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2962. ``(None, None)`` when the photo can't be found.
  2963. """
  2964. from backend.app.api.routes.settings import get_setting
  2965. from backend.app.core.auth import is_auth_enabled
  2966. from backend.app.utils.archive_paths import find_archive_photo
  2967. from backend.app.utils.notification_photos import save_notification_photo
  2968. log = logging.getLogger(__name__)
  2969. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2970. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2971. photo_bytes: bytes | None = None
  2972. try:
  2973. photo_path = find_archive_photo(archive, filename)
  2974. if photo_path is not None:
  2975. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2976. except Exception as e:
  2977. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2978. try:
  2979. auth_on = await is_auth_enabled(db)
  2980. except Exception:
  2981. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2982. if auth_on:
  2983. url = None
  2984. if photo_bytes:
  2985. try:
  2986. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2987. url = f"{base}/api/v1/notifications/photos/{name}"
  2988. except Exception as e:
  2989. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2990. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2991. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2992. return url, None
  2993. if photo_bytes:
  2994. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2995. return url, photo_bytes
  2996. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  2997. """Capture a camera snapshot for notification image attachment.
  2998. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2999. Uses: external camera > buffered frame > fresh capture.
  3000. Turns the chamber light on for the picture when the printer asks for it
  3001. (#1655). ``light=False`` is for callers that capture all through a print,
  3002. where the light would flash with every frame.
  3003. """
  3004. if not printer:
  3005. return None
  3006. async with camera_light(printer if light else None):
  3007. return await _capture_snapshot_frame(printer_id, printer, logger)
  3008. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3009. """The capture behind ``_capture_snapshot_for_notification``."""
  3010. try:
  3011. from backend.app.api.routes.settings import get_setting
  3012. async with async_session() as db:
  3013. capture_enabled = await get_setting(db, "capture_finish_photo")
  3014. if capture_enabled is not None and capture_enabled.lower() != "true":
  3015. return None
  3016. # Try external camera first
  3017. if printer.external_camera_enabled and printer.external_camera_url:
  3018. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3019. from backend.app.api.routes.camera import live_frame_for_capture
  3020. from backend.app.services.external_camera import capture_frame
  3021. # An external camera allows one reader, so capturing while a viewer
  3022. # is attached fails (#2707). A None here falls through to the paths
  3023. # below exactly as a failed capture did.
  3024. defer, buffered = live_frame_for_capture(printer_id)
  3025. if defer:
  3026. frame_data = buffered
  3027. else:
  3028. frame_data = await capture_frame(
  3029. printer.external_camera_url,
  3030. printer.external_camera_type or "mjpeg",
  3031. snapshot_url=printer.external_camera_snapshot_url,
  3032. )
  3033. if frame_data and len(frame_data) <= 2_500_000:
  3034. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3035. return _apply_camera_rotation(frame_data, printer, logger)
  3036. # Try buffered frame from active stream
  3037. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3038. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3039. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3040. buffered_frame = get_buffered_frame(printer_id)
  3041. if (active_for_printer or active_chamber) and buffered_frame:
  3042. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3043. if len(buffered_frame) <= 2_500_000:
  3044. return _apply_camera_rotation(buffered_frame, printer, logger)
  3045. # Fresh capture from printer camera
  3046. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3047. from backend.app.services.camera import capture_camera_frame_bytes
  3048. frame_data = await capture_camera_frame_bytes(
  3049. printer.ip_address, printer.access_code, printer.model, timeout=15
  3050. )
  3051. if frame_data and len(frame_data) <= 2_500_000:
  3052. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3053. return _apply_camera_rotation(frame_data, printer, logger)
  3054. except Exception as e:
  3055. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3056. return None
  3057. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3058. """#1867: bank a recent in-print camera frame for the finish photo.
  3059. Called on every layer change and (#2547) on every print-progress advance.
  3060. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3061. path has a pre-End-G-code image for prints that end with a plate swap.
  3062. Both drivers are print telemetry that stops the instant printing ends: no
  3063. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3064. plate swap) executes. So the last banked frame is always the finished print,
  3065. never the swapped plate — that property is what the #1867 path relies on and
  3066. it must survive any change to the throttle below.
  3067. Layer changes alone were not enough: they stop when the *final* layer
  3068. begins, which on a three-minute last layer left the bank stale by the whole
  3069. length of that layer (#2547). Progress keeps ticking through it.
  3070. Best-effort: any failure just leaves the previous banked frame.
  3071. """
  3072. logger = logging.getLogger(__name__)
  3073. client = printer_manager.get_client(printer_id)
  3074. state = client.state if client else None
  3075. if not state or state.state != "RUNNING":
  3076. return
  3077. # Only during actual extrusion — firmware ticks layer_num during the
  3078. # pre-print calibration sequence, whose sub-stages are non-zero.
  3079. if state.mc_print_sub_stage not in (None, 0):
  3080. return
  3081. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3082. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3083. # now that progress advances also drive banking, that exemption would fire a
  3084. # camera grab on every percent tick of the last layer. Bambu printers accept
  3085. # one RTSP client at a time, so each grab contends with the live view.
  3086. now = time.monotonic()
  3087. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3088. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3089. return
  3090. total = state.total_layers or 0
  3091. try:
  3092. async with async_session() as db:
  3093. from backend.app.models.printer import Printer
  3094. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3095. printer = result.scalar_one_or_none()
  3096. if not printer:
  3097. return
  3098. # Reuses the notification snapshot path, which honours the
  3099. # `capture_finish_photo` setting (returns None when disabled) so we
  3100. # don't bank frames the user never asked for. Without the chamber light
  3101. # (#1655): this runs every 25 seconds for the whole print.
  3102. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3103. if frame:
  3104. _inprint_frame_bank[printer_id] = frame
  3105. _inprint_frame_bank_ts[printer_id] = now
  3106. logger.debug(
  3107. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3108. printer_id,
  3109. layer_num,
  3110. total,
  3111. len(frame),
  3112. )
  3113. except Exception as e:
  3114. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3115. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3116. """Apply camera rotation to snapshot image if configured."""
  3117. from backend.app.services.camera import apply_camera_rotation
  3118. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3119. async def _send_print_start_notification(
  3120. printer_id: int,
  3121. data: dict,
  3122. archive_data: dict | None = None,
  3123. logger=None,
  3124. ):
  3125. """Helper to send print start notification with optional archive data."""
  3126. if logger is None:
  3127. logger = logging.getLogger(__name__)
  3128. try:
  3129. async with async_session() as db:
  3130. from backend.app.models.printer import Printer
  3131. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3132. printer = result.scalar_one_or_none()
  3133. printer_name = printer.name if printer else f"Printer {printer_id}"
  3134. # Capture camera snapshot for notification image attachment
  3135. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3136. if image_data:
  3137. if archive_data is None:
  3138. archive_data = {}
  3139. archive_data["image_data"] = image_data
  3140. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3141. # Send user-specific email notification for print start
  3142. if archive_data and archive_data.get("created_by_id"):
  3143. await notification_service.send_user_print_email(
  3144. event_type="user_print_start",
  3145. created_by_id=archive_data["created_by_id"],
  3146. printer_name=printer_name,
  3147. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3148. db=db,
  3149. )
  3150. except Exception as e:
  3151. logger.warning("Notification on_print_start failed: %s", e)
  3152. async def _dispatch_user_print_email(
  3153. status: str,
  3154. created_by_id: int | None,
  3155. printer_name: str,
  3156. filename: str,
  3157. db,
  3158. image_data: bytes | None = None,
  3159. finish_photo_url: str | None = None,
  3160. ) -> None:
  3161. """Send a user-specific print-completion email based on print status.
  3162. Maps the normalised print status to the correct event type and delegates
  3163. to :meth:`NotificationService.send_user_print_email`. A single helper
  3164. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3165. "stopped"`` dispatch block at every call site.
  3166. Does nothing if *created_by_id* is ``None``.
  3167. """
  3168. if created_by_id is None:
  3169. return
  3170. if status == "completed":
  3171. event_type = "user_print_complete"
  3172. elif status == "failed":
  3173. event_type = "user_print_failed"
  3174. elif status in ("stopped", "aborted", "cancelled"):
  3175. event_type = "user_print_stopped"
  3176. else:
  3177. return
  3178. await notification_service.send_user_print_email(
  3179. event_type=event_type,
  3180. created_by_id=created_by_id,
  3181. printer_name=printer_name,
  3182. filename=filename,
  3183. db=db,
  3184. image_data=image_data,
  3185. finish_photo_url=finish_photo_url,
  3186. )
  3187. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3188. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3189. try:
  3190. from backend.app.services.archive import extract_printable_objects_from_archive
  3191. client = printer_manager.get_client(printer_id)
  3192. if not client:
  3193. return
  3194. # Extract with positions for UI overlay, scoped to the plate that
  3195. # is printing — resolve_plate_id is the same resolver /cover uses,
  3196. # so the object list can't disagree with the thumbnail it is drawn
  3197. # over (#2522).
  3198. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3199. app_settings.base_dir / archive.file_path,
  3200. plate_number=resolve_plate_id(client.state),
  3201. )
  3202. if printable_objects:
  3203. client.state.printable_objects = printable_objects
  3204. client.state.printable_objects_bbox_all = bbox_all
  3205. client.state.skipped_objects = []
  3206. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3207. except Exception as e:
  3208. logger.debug("Failed to extract printable objects from archive: %s", e)
  3209. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3210. """Put the skip-objects list back after a restart mid-print.
  3211. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3212. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3213. which the #1304 guard suppresses on the first RUNNING push after startup.
  3214. Everything else this hook restores (the archive, the usage-tracking session,
  3215. the timelapse baseline) was already handled; the object list was not, so a
  3216. restart mid-print took skip-objects away for the rest of that print.
  3217. Nothing recovered it either: the printer card gates its Skip button on the
  3218. object count, and the one endpoint that can rebuild the list is reachable
  3219. only from the modal that button opens.
  3220. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3221. leftover ``status="printing"`` row from a completion we never saw cannot
  3222. hand this print someone else's objects. Without one, nothing is loaded
  3223. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3224. case on demand.
  3225. """
  3226. client = printer_manager.get_client(printer_id)
  3227. if client is None or client.state.printable_objects:
  3228. return
  3229. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3230. if subtask_id in ("", "0"):
  3231. return
  3232. from backend.app.models.archive import PrintArchive
  3233. archive = await db.scalar(
  3234. select(PrintArchive)
  3235. .where(
  3236. PrintArchive.printer_id == printer_id,
  3237. PrintArchive.status == "printing",
  3238. PrintArchive.subtask_id == subtask_id,
  3239. )
  3240. .order_by(PrintArchive.created_at.desc())
  3241. .limit(1)
  3242. )
  3243. if archive is not None:
  3244. _load_objects_from_archive(archive, printer_id, logger)
  3245. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3246. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3247. # past it; the second covers a handshake that failed again on the way back and
  3248. # armed a fresh one. Module-level so tests can shrink them.
  3249. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3250. # Retry ladder for the other temporary give-up: the file service answered and
  3251. # the transfer still did not finish, which at print start is usually the printer
  3252. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3253. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3254. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3255. # two cover a printer that stays busy well into the print.
  3256. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3257. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3258. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3259. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3260. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3261. # by view, so two views race), the cool-off retry task, and print completion.
  3262. # Without this they each read file_path == "" and each run a full copy, so the row
  3263. # ends up pointing at one timestamped directory while the others sit orphaned.
  3264. #
  3265. # Keyed by printer rather than archive because a printer runs one print at a time,
  3266. # which makes the two equally strong here — and it bounds the dict by printer
  3267. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3268. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3269. # resuming, so "no waiters" is not a question this API can answer.
  3270. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3271. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3272. """Fill in a no-3MF archive from a 3MF that turned up later.
  3273. Returns True when the row was upgraded. Safe to call speculatively: it
  3274. verifies the archive still exists, is still a fallback, and that the file
  3275. is a readable 3MF before touching anything.
  3276. Serialised per printer — see ``_fallback_recovery_locks``.
  3277. """
  3278. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3279. async with lock:
  3280. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3281. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3282. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3283. import zipfile
  3284. from backend.app.models.archive import PrintArchive
  3285. from backend.app.services.archive import ArchiveService
  3286. logger = logging.getLogger(__name__)
  3287. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3288. return False
  3289. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3290. # A truncated or half-written download is worse than no download: it
  3291. # would replace an honest empty archive with wrong metadata.
  3292. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3293. return False
  3294. async with async_session() as db:
  3295. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3296. if archive is None or archive.deleted_at is not None:
  3297. return False
  3298. if archive.file_path:
  3299. # Already recovered, or never was a fallback. Either way there is a
  3300. # real 3MF attached and overwriting it is not this function's job.
  3301. return False
  3302. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3303. service = ArchiveService(db)
  3304. recovered = await service.archive_print(
  3305. printer_id=printer_id,
  3306. source_file=source_3mf,
  3307. print_data={**print_data, "status": archive.status or "printing"},
  3308. subtask_id=archive.subtask_id,
  3309. update_archive_id=archive.id,
  3310. )
  3311. if recovered is None:
  3312. return False
  3313. logger.info(
  3314. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3315. archive_id,
  3316. source_3mf,
  3317. recovered.file_size,
  3318. )
  3319. # `archive_updated`, not `archive_created` — the row was already on the
  3320. # Archives page as an empty card and is now filled in, not new.
  3321. await ws_manager.send_archive_updated(
  3322. {
  3323. "id": recovered.id,
  3324. "printer_id": recovered.printer_id,
  3325. "filename": recovered.filename,
  3326. "print_name": recovered.print_name,
  3327. "status": recovered.status,
  3328. }
  3329. )
  3330. return True
  3331. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3332. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3333. Called from the paths that pull a 3MF for a print that is already under way
  3334. — chiefly the cover endpoint, which downloads the very file the archive flow
  3335. could not get and, before #2957, used it for a thumbnail and nothing else.
  3336. The bytes are already local, so this costs a parse and a row update.
  3337. No-op when the running print has a real archive, which is the common case.
  3338. """
  3339. from backend.app.models.archive import PrintArchive
  3340. logger = logging.getLogger(__name__)
  3341. # `_active_prints` is keyed on the raw names seen at print start — the
  3342. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3343. # Callers here arrive with whichever variant their own path produced, so
  3344. # match on the same normalization the download cache uses rather than on an
  3345. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3346. # endpoint find an archive registered under "Desktop_Goose".
  3347. wanted = normalize_3mf_name(name)
  3348. archive_id = None
  3349. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3350. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3351. archive_id = value
  3352. break
  3353. if archive_id is None:
  3354. return False
  3355. async with async_session() as db:
  3356. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3357. # Cheap pre-check so the common case (a normal archive) does no work.
  3358. if archive is None or archive.file_path or archive.deleted_at is not None:
  3359. return False
  3360. try:
  3361. return await _recover_fallback_archive(archive_id, path, printer_id)
  3362. except Exception as e:
  3363. # Recovery is opportunistic. A failure here must never take down the
  3364. # caller, which is usually just trying to render a thumbnail.
  3365. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3366. return False
  3367. def _schedule_fallback_3mf_retry(
  3368. printer_id: int,
  3369. archive_id: int,
  3370. filenames: list[str],
  3371. delays: tuple[float, ...] | None = None,
  3372. reason: str = REASON_FTPS_COOLOFF,
  3373. ) -> None:
  3374. """Re-attempt the 3MF download after a temporary give-up.
  3375. ``reason`` says which give-up this is, and picks the default ladder: an
  3376. FTPS cool-off has to be waited out, while a transfer that timed out under
  3377. contention is worth asking about again straight away (#3063). It is only
  3378. read for the ladder and the log line -- the retry itself is identical, since
  3379. in both cases the file is on the printer and the last attempt at it failed
  3380. for a reason that does not last.
  3381. """
  3382. logger = logging.getLogger(__name__)
  3383. if delays is None:
  3384. delays = (
  3385. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3386. if reason == REASON_FTP_TRANSFER_FAILED
  3387. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3388. )
  3389. async def _retry() -> None:
  3390. from backend.app.models.archive import PrintArchive
  3391. from backend.app.models.printer import Printer
  3392. for delay in delays:
  3393. await asyncio.sleep(delay)
  3394. async with async_session() as db:
  3395. archive = (
  3396. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3397. ).scalar_one_or_none()
  3398. if archive is None or archive.deleted_at is not None or archive.file_path:
  3399. return
  3400. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3401. if printer is None:
  3402. return
  3403. # Read the fields while the session is open rather than touching
  3404. # a detached instance minutes later, mid-download.
  3405. printer_ip = printer.ip_address
  3406. printer_code = printer.access_code
  3407. printer_model = printer.model
  3408. # Someone else may have fetched it in the meantime — the cover
  3409. # endpoint routinely does, and its copy is the same bytes.
  3410. for name in filenames:
  3411. cached = get_cached_3mf(printer_id, name)
  3412. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3413. return
  3414. if ftps_handshake_blocked(printer_ip):
  3415. logger.info(
  3416. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3417. printer_id,
  3418. archive_id,
  3419. )
  3420. continue
  3421. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3422. for candidate in filenames:
  3423. # Bare name only. These come from the print-start flow, which
  3424. # already strips the path, but the local temp write must not
  3425. # depend on that holding for every future caller — a name that
  3426. # is absolute or contains ".." would otherwise escape the data
  3427. # volume via the `/` operator.
  3428. name = Path(candidate).name
  3429. if not name or name in (".", ".."):
  3430. continue
  3431. if not name.endswith(".3mf"):
  3432. name = f"{name}.3mf"
  3433. temp_path = app_settings.archive_dir / "temp" / name
  3434. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3435. try:
  3436. hit = await download_file_try_paths_async(
  3437. printer_ip,
  3438. printer_code,
  3439. ftp_probe_paths(name),
  3440. temp_path,
  3441. socket_timeout=ftp_timeout,
  3442. printer_model=printer_model,
  3443. )
  3444. except Exception as e:
  3445. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3446. continue
  3447. if not hit:
  3448. continue
  3449. cache_3mf_download(printer_id, name, temp_path)
  3450. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3451. return
  3452. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3453. async def _guarded() -> None:
  3454. try:
  3455. await _retry()
  3456. except asyncio.CancelledError:
  3457. raise
  3458. except Exception as e:
  3459. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3460. finally:
  3461. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3462. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3463. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3464. if existing and not existing.done():
  3465. existing.cancel()
  3466. task = asyncio.create_task(_guarded())
  3467. _fallback_3mf_retry_tasks[printer_id] = task
  3468. logger.info(
  3469. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3470. archive_id,
  3471. reason,
  3472. printer_id,
  3473. ", ".join(f"{d:g}s" for d in delays),
  3474. )
  3475. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3476. """Whether an archive created here should ask for the print's outcome (#1898).
  3477. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3478. branches below: a queued job already has its archive and takes the
  3479. expected-print branch, where the queue item's own ``confirm_outcome``
  3480. decides. The queue is still consulted, because a restart mid-print empties
  3481. ``_expected_prints`` — without the check the setting could override a queue
  3482. item that deliberately has the flag off. Any failure answers "don't ask":
  3483. an unwanted prompt is worse than a missing one, and this must never be the
  3484. reason a print goes unarchived.
  3485. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3486. leaves one behind when a completion cannot be matched to it
  3487. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3488. only takes it back once the printer has sat connected and terminal for
  3489. minutes. Until then every screen-started print on that printer would
  3490. silently lose its prompt, so the row is held against ``observed_name`` by
  3491. the same comparison a completion uses: a positive disagreement means the row
  3492. is about some other run and this print is external after all.
  3493. """
  3494. logger = logging.getLogger(__name__)
  3495. try:
  3496. # A savepoint rather than a rollback of the caller's transaction on
  3497. # failure: a failed statement leaves the transaction unusable, but a
  3498. # full rollback also expires every object the caller has loaded (the
  3499. # printer, the archive it just created), and on an async session the
  3500. # next attribute read then raises instead of reloading. Everything here
  3501. # is a read, so undoing the savepoint loses nothing.
  3502. async with db.begin_nested():
  3503. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3504. except Exception as e:
  3505. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3506. return False
  3507. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3508. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3509. from backend.app.api.routes.settings import get_setting, setting_is_true
  3510. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3511. return False
  3512. from backend.app.models.print_queue import PrintQueueItem
  3513. dispatched_here = await db.scalar(
  3514. select(PrintQueueItem)
  3515. .where(
  3516. PrintQueueItem.printer_id == printer_id,
  3517. PrintQueueItem.status == "printing",
  3518. )
  3519. .limit(1)
  3520. )
  3521. if dispatched_here is None:
  3522. return True
  3523. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3524. observed = (observed_name or "").strip()
  3525. if not expected or not observed or _subtask_names_match(expected, observed):
  3526. logger.info(
  3527. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3528. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3529. printer_id,
  3530. dispatched_here.id,
  3531. )
  3532. return False
  3533. logger.info(
  3534. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3535. "%r; treating this as an externally started print.",
  3536. dispatched_here.id,
  3537. printer_id,
  3538. expected,
  3539. observed,
  3540. )
  3541. return True
  3542. async def _dispatch_outcome_confirmation_safely(
  3543. db,
  3544. printer_id: int,
  3545. printer_name: str,
  3546. data: dict,
  3547. archive_id: int,
  3548. archive_data: dict | None = None,
  3549. ) -> None:
  3550. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3551. The completion task sends the per-user print email on the same session
  3552. right after the prompt. A failed statement in the prompt leaves that
  3553. session needing a rollback, and without one the email step fails with
  3554. PendingRollbackError; the prompt is the optional part, so it must not be
  3555. the reason the email never goes out.
  3556. """
  3557. try:
  3558. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3559. except Exception as e:
  3560. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3561. try:
  3562. await db.rollback()
  3563. except Exception:
  3564. pass
  3565. async def dispatch_outcome_confirmation(
  3566. db,
  3567. printer_id: int,
  3568. printer_name: str,
  3569. data: dict,
  3570. archive_id: int,
  3571. archive_data: dict | None = None,
  3572. ) -> bool:
  3573. """Emit the post-print outcome prompt for a completed archive (#1898).
  3574. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3575. queue item, or from ``confirm_outcome_external_prints`` for a print
  3576. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3577. question still open. Mints the per-archive capability token the one-tap
  3578. verdict links carry.
  3579. Lives here rather than inline in ``on_print_complete``'s notification task
  3580. because that task swallows every exception: extracted, the gate and the two
  3581. emissions can be driven by a test, which is the only thing standing between
  3582. a regression here and a farm that quietly stops asking.
  3583. Returns whether a prompt was sent.
  3584. """
  3585. logger = logging.getLogger(__name__)
  3586. from backend.app.models.archive import PrintArchive
  3587. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3588. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3589. return False
  3590. import secrets as _secrets
  3591. # A spent token stays on the row so the one-tap route can recognise it, so
  3592. # "has a token" no longer means "answerable". A prompt going out now needs a
  3593. # live one: mint a new token whenever the stored one is already spent, or
  3594. # every button in the new message would land on the already-answered page.
  3595. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3596. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3597. confirm_archive.confirm_token_used_at = None
  3598. await db.commit()
  3599. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3600. base = await get_external_base_url(db)
  3601. if not await get_setting(db, "external_url"):
  3602. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3603. # absolute URL, so an unconfigured install used to get a message body
  3604. # with two unusable relative paths and no buttons at all. The shared
  3605. # fallback at least produces tappable links; say which setting makes
  3606. # them resolve from a phone.
  3607. logger.warning(
  3608. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3609. "Set Settings → External URL so they resolve away from this host.",
  3610. base,
  3611. )
  3612. token = confirm_archive.confirm_token
  3613. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3614. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3615. confirm_url = f"{base}/archives?confirm={archive_id}"
  3616. await ws_manager.send_print_confirm_request(
  3617. printer_id,
  3618. {
  3619. "archive_id": archive_id,
  3620. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3621. },
  3622. )
  3623. await notification_service.on_print_confirm_request(
  3624. printer_id,
  3625. printer_name,
  3626. data,
  3627. db,
  3628. archive_data=archive_data,
  3629. good_url=good_url,
  3630. reject_url=reject_url,
  3631. confirm_url=confirm_url,
  3632. archive_id=archive_id,
  3633. )
  3634. return True
  3635. async def on_print_start(printer_id: int, data: dict):
  3636. """Handle print start - archive the 3MF file immediately."""
  3637. logger = logging.getLogger(__name__)
  3638. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3639. try:
  3640. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3641. except Exception:
  3642. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3643. # Clear any stale user-stopped flag from previous print cycles
  3644. _user_stopped_printers.discard(printer_id)
  3645. # A new print starts its milestones from zero (#3211). The status path only
  3646. # resets on progress below 5 while not printing, which a printer that goes
  3647. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3648. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3649. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3650. _last_progress_milestone[printer_id] = 0
  3651. _kill_switch_notification_tasks.pop(printer_id, None)
  3652. # #1721: drop any leftover pre-captured finish frame from a prior print
  3653. # so a never-consumed cache entry can't bleed into the new print's photo.
  3654. _stage22_finish_frames.pop(printer_id, None)
  3655. # #1867: same for the in-print frame bank — a queued print must not reuse
  3656. # the previous job's banked frame.
  3657. _inprint_frame_bank.pop(printer_id, None)
  3658. _inprint_frame_bank_ts.pop(printer_id, None)
  3659. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3660. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3661. # print's flag instead of inheriting it.
  3662. print_dispatch_context.adopt(printer_id)
  3663. # Cancel any active bed cooldown waiter for this printer
  3664. if _bed_cool_waiters.pop(printer_id, None):
  3665. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3666. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3667. from backend.app.api.routes.printers import clear_cover_cache
  3668. clear_cover_cache(printer_id)
  3669. await ws_manager.send_print_start(printer_id, data)
  3670. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3671. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3672. # MQTT relay - publish print start
  3673. try:
  3674. printer_info = printer_manager.get_printer(printer_id)
  3675. if printer_info:
  3676. await mqtt_relay.on_print_start(
  3677. printer_id,
  3678. printer_info.name,
  3679. printer_info.serial_number,
  3680. data.get("filename", ""),
  3681. data.get("subtask_name", ""),
  3682. )
  3683. except Exception:
  3684. pass # Don't fail print start callback if MQTT fails
  3685. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3686. # and mapping, and the seeded tray-change log.
  3687. #
  3688. # Unconditional, for both inventory backends. This only *captures* — the
  3689. # writing is still split, with the internal tracker skipped at completion
  3690. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3691. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3692. # tray-change log, and that log is the only record of which spool fed
  3693. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3694. # it on one side only would leave Spoolman users with the mid-print
  3695. # restart bug this fixes for everyone else.
  3696. try:
  3697. async with async_session() as db:
  3698. from backend.app.api.routes.settings import get_setting
  3699. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3700. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3701. await usage_on_print_start(
  3702. printer_id,
  3703. data,
  3704. printer_manager,
  3705. db=db,
  3706. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3707. )
  3708. except Exception as e:
  3709. logger.warning("Usage tracker on_print_start failed: %s", e)
  3710. # Track if notification was sent (to avoid sending twice)
  3711. notification_sent = False
  3712. # Smart plug automation: turn on plug when print starts
  3713. try:
  3714. async with async_session() as db:
  3715. await smart_plug_manager.on_print_start(printer_id, db)
  3716. except Exception as e:
  3717. logger.warning("Smart plug on_print_start failed: %s", e)
  3718. async with async_session() as db:
  3719. from backend.app.models.printer import Printer
  3720. from backend.app.services.bambu_ftp import list_files_async
  3721. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3722. printer = result.scalar_one_or_none()
  3723. # Plate detection check - pause if objects detected on build plate
  3724. logger.info(
  3725. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3726. )
  3727. if printer and printer.plate_detection_enabled:
  3728. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3729. # Release the pooled DB connection before the plate-detection camera
  3730. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3731. # printer SELECT has run so far — nothing to persist — so this commit
  3732. # is a data-noop that ends the read transaction and returns the
  3733. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3734. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3735. # archive lookups below re-acquire a fresh connection on next execute.
  3736. await db.commit()
  3737. try:
  3738. from backend.app.services.plate_detection import check_plate_empty
  3739. # Build ROI tuple from printer settings if available
  3740. roi = None
  3741. if all(
  3742. [
  3743. printer.plate_detection_roi_x is not None,
  3744. printer.plate_detection_roi_y is not None,
  3745. printer.plate_detection_roi_w is not None,
  3746. printer.plate_detection_roi_h is not None,
  3747. ]
  3748. ):
  3749. roi = (
  3750. printer.plate_detection_roi_x,
  3751. printer.plate_detection_roi_y,
  3752. printer.plate_detection_roi_w,
  3753. printer.plate_detection_roi_h,
  3754. )
  3755. # Auto-turn on chamber light if it's off for better detection
  3756. light_was_off = False
  3757. client = printer_manager.get_client(printer_id)
  3758. if client and client.state:
  3759. light_was_off = not client.state.chamber_light
  3760. if light_was_off:
  3761. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3762. client.set_chamber_light(True)
  3763. # Wait for light to physically turn on and camera to adjust exposure
  3764. await asyncio.sleep(2.5)
  3765. plate_photo_data = None
  3766. objects_detected = False
  3767. try:
  3768. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3769. plate_result = await check_plate_empty(
  3770. printer_id=printer_id,
  3771. ip_address=printer.ip_address,
  3772. access_code=printer.access_code,
  3773. model=printer.model,
  3774. include_debug_image=False,
  3775. external_camera_url=printer.external_camera_url,
  3776. external_camera_type=printer.external_camera_type,
  3777. use_external=printer.external_camera_enabled,
  3778. roi=roi,
  3779. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3780. )
  3781. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3782. if objects_detected:
  3783. # Objects detected - pause the print!
  3784. logger.warning(
  3785. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3786. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3787. )
  3788. pause_client = printer_manager.get_client(printer_id)
  3789. if pause_client:
  3790. pause_client.pause_print()
  3791. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3792. # Snapshot while the light's still on — restoring it first
  3793. # would leave the notification with a dark photo.
  3794. try:
  3795. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3796. except Exception as snap_err:
  3797. logger.warning(
  3798. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3799. )
  3800. finally:
  3801. # Restore chamber light to original state as soon as the
  3802. # camera is done with it, whatever happened above.
  3803. if light_was_off and client:
  3804. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3805. try:
  3806. client.set_chamber_light(False)
  3807. except Exception as light_err:
  3808. logger.warning(
  3809. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3810. printer_id,
  3811. light_err,
  3812. )
  3813. if objects_detected:
  3814. # Send notification about plate not empty
  3815. await ws_manager.broadcast(
  3816. {
  3817. "type": "plate_not_empty",
  3818. "printer_id": printer_id,
  3819. "printer_name": printer.name,
  3820. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3821. }
  3822. )
  3823. # Also send push notification
  3824. try:
  3825. await notification_service.on_plate_not_empty(
  3826. printer_id=printer_id,
  3827. printer_name=printer.name,
  3828. db=db,
  3829. difference_percent=plate_result.difference_percent,
  3830. image_data=plate_photo_data,
  3831. )
  3832. except Exception as notif_err:
  3833. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3834. else:
  3835. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3836. except Exception as plate_err:
  3837. # Don't block print on plate detection errors
  3838. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3839. if not printer:
  3840. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3841. if not notification_sent:
  3842. await _send_print_start_notification(printer_id, data, logger=logger)
  3843. return
  3844. if not printer.auto_archive:
  3845. # auto-archive disabled — check if there's an expected print (dispatched
  3846. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3847. # If so, fall through to the expected-print handling below so the archive
  3848. # is tracked in _active_prints and usage tracking works at completion.
  3849. _fn = data.get("filename", "")
  3850. _sn = data.get("subtask_name", "")
  3851. _check_keys: list[tuple[int, str]] = []
  3852. if _sn:
  3853. _check_keys += [
  3854. (printer_id, _sn),
  3855. (printer_id, f"{_sn}.3mf"),
  3856. (printer_id, f"{_sn}.gcode.3mf"),
  3857. ]
  3858. if _fn:
  3859. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3860. _check_keys.append((printer_id, _base_fn))
  3861. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3862. _check_keys += [
  3863. (printer_id, _no_archive_base),
  3864. (printer_id, f"{_no_archive_base}.3mf"),
  3865. ]
  3866. _has_expected = any(k in _expected_prints for k in _check_keys)
  3867. if not _has_expected:
  3868. # No expected print — truly external print (started from slicer/touchscreen)
  3869. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3870. if not notification_sent:
  3871. _no_archive_creator: int | None = None
  3872. for _key in _check_keys:
  3873. _expected_prints.pop(_key, None)
  3874. _expected_print_registered_at.pop(_key, None)
  3875. popped_creator = _expected_print_creators.pop(_key, None)
  3876. if _no_archive_creator is None:
  3877. _no_archive_creator = popped_creator
  3878. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3879. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3880. return
  3881. else:
  3882. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3883. # Get the filename and subtask_name
  3884. filename = data.get("filename", "")
  3885. subtask_name = data.get("subtask_name", "")
  3886. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3887. # present, it lets us match an archive across a backend restart (#972):
  3888. # same id → same print → resume the existing row instead of cancelling
  3889. # it and recreating from scratch (which loses started_at). Treat "0"
  3890. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3891. raw_mqtt = data.get("raw_data") or {}
  3892. subtask_id = raw_mqtt.get("subtask_id")
  3893. if subtask_id is not None:
  3894. subtask_id = str(subtask_id).strip()
  3895. if subtask_id in ("", "0"):
  3896. subtask_id = None
  3897. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3898. # Skip the printer's own jobs — a calibration run is not a user's print.
  3899. # See is_internal_printer_job for what counts and why both fields are
  3900. # tested; the pressure-advance line reports as a subtask name with no
  3901. # /usr/ path, which the old prefix-only test here missed entirely.
  3902. #
  3903. # No notification either. The event describes the printer calibrating
  3904. # itself, so "Print started" is as wrong as the archive was, and the
  3905. # matching completion is suppressed in on_print_complete for the same
  3906. # reason.
  3907. if is_internal_printer_job(filename, subtask_name):
  3908. logger.info(
  3909. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3910. filename,
  3911. subtask_name,
  3912. )
  3913. return
  3914. if not filename and not subtask_name:
  3915. # Send notification without archive data (no filename)
  3916. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3917. if not notification_sent:
  3918. await _send_print_start_notification(printer_id, data, logger=logger)
  3919. return
  3920. # Check if this is an expected print from reprint/scheduled
  3921. # Build list of possible keys to check
  3922. expected_keys = []
  3923. if subtask_name:
  3924. expected_keys.append((printer_id, subtask_name))
  3925. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3926. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3927. if filename:
  3928. fname = filename.split("/")[-1] if "/" in filename else filename
  3929. expected_keys.append((printer_id, fname))
  3930. # Strip extensions to match
  3931. base = fname.replace(".gcode", "").replace(".3mf", "")
  3932. expected_keys.append((printer_id, base))
  3933. expected_keys.append((printer_id, f"{base}.3mf"))
  3934. expected_archive_id = None
  3935. for key in expected_keys:
  3936. expected_archive_id = _expected_prints.pop(key, None)
  3937. _expected_print_registered_at.pop(key, None)
  3938. if expected_archive_id:
  3939. # Clean up other possible keys for this print
  3940. for other_key in expected_keys:
  3941. _expected_prints.pop(other_key, None)
  3942. _expected_print_registered_at.pop(other_key, None)
  3943. break
  3944. if expected_archive_id:
  3945. # This is a reprint/scheduled print - use existing archive, don't create new one
  3946. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3947. from backend.app.models.archive import PrintArchive
  3948. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3949. archive = result.scalar_one_or_none()
  3950. if archive:
  3951. # Update archive status to printing
  3952. archive.status = "printing"
  3953. archive.started_at = datetime.now(timezone.utc)
  3954. # The previous run's answer is still on this row and the
  3955. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3956. # so without a reset the second run inherits the first run's
  3957. # verdict: no prompt at all, and a green "good" badge on a run
  3958. # nobody ever judged.
  3959. if archive.confirm_requested:
  3960. archive.user_verdict = None
  3961. archive.user_verdict_source = None
  3962. archive.user_verdict_at = None
  3963. archive.confirm_token = None
  3964. archive.confirm_token_used_at = None
  3965. # Reprint of an archive reuses the source row. Without resetting
  3966. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3967. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3968. # extracts the *original* print's last frame, which then ships in
  3969. # the completion notification (#1707). Clear the path so the
  3970. # scanner runs fresh; also unlink the old video file so reprints
  3971. # don't accumulate orphans in the archive directory. Photos list
  3972. # is left alone — accumulating one finish photo per run is fine.
  3973. # The print-start baseline (#2704) is stale for the same reason:
  3974. # it describes the printer before the previous run. The capture
  3975. # below overwrites it, but clear it here too so an early failure
  3976. # can't leave the scan diffing against the wrong snapshot.
  3977. #
  3978. # Unlinked only when it is the same plate printing again. Every
  3979. # plate of a Send All shares this archive, and the video on it
  3980. # can be the only copy of another plate's run -- the printer's
  3981. # was deleted once it attached (#3275). That one is left in the
  3982. # archive directory, which goes with the archive. A video whose
  3983. # plate is not on record (attached by hand, or before the
  3984. # column existed) is kept too: nothing tells it apart from
  3985. # another plate's, and keeping costs one file where deleting
  3986. # can cost the only copy.
  3987. archive.timelapse_baseline = None
  3988. stale_timelapse_relpath = archive.timelapse_path
  3989. stale_timelapse_plate_id = archive.timelapse_plate_id
  3990. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  3991. if stale_timelapse_relpath:
  3992. archive.timelapse_path = None
  3993. archive.timelapse_plate_id = None
  3994. if stale_timelapse_relpath and stale_timelapse_plate_id != starting_plate_id:
  3995. logger.info(
  3996. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  3997. stale_timelapse_relpath,
  3998. stale_timelapse_plate_id,
  3999. expected_archive_id,
  4000. starting_plate_id,
  4001. )
  4002. elif stale_timelapse_relpath:
  4003. try:
  4004. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4005. if stale_path.is_file():
  4006. stale_path.unlink()
  4007. logger.info(
  4008. "Deleted stale timelapse %s on reprint of archive %s",
  4009. stale_timelapse_relpath,
  4010. expected_archive_id,
  4011. )
  4012. except OSError as e:
  4013. logger.warning(
  4014. "Failed to delete stale timelapse %s on reprint: %s",
  4015. stale_timelapse_relpath,
  4016. e,
  4017. )
  4018. # Persist a restart-stable id so a later restart resumes this
  4019. # archive by subtask_id instead of name-matching + duplicating
  4020. # it (#1485). The printer often hasn't echoed subtask_id back
  4021. # this soon after dispatch, so fall back to the id Bambuddy
  4022. # minted when it sent the print command. Scoped to this
  4023. # expected-print branch on purpose: an expected match means
  4024. # Bambuddy dispatched this exact print in this process, so the
  4025. # client's last-dispatch id genuinely belongs to it — using it
  4026. # for an externally-started print could mis-tag the archive.
  4027. effective_subtask_id = subtask_id
  4028. if not effective_subtask_id:
  4029. _client = printer_manager.get_client(printer_id)
  4030. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4031. if _dispatched:
  4032. effective_subtask_id = str(_dispatched).strip() or None
  4033. # Update on first-set OR on reprint (the queue dispatcher mints
  4034. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4035. # the rewrite for reprints leaves the archive holding the FIRST
  4036. # run's id; if MQTT then reconnects mid-print, the reconciler
  4037. # (#1542) compares the stale stored id against the printer's
  4038. # live id, sees a mismatch, and synthesises a bogus PRINT
  4039. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4040. # in #1807. Inequality check preserves the noop-on-stable-push
  4041. # behaviour the earlier `not archive.subtask_id` guard provided.
  4042. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4043. archive.subtask_id = effective_subtask_id
  4044. # #1403 follow-up: VP-queue archives are created with
  4045. # printer_id=None at queue-add time (we don't know which
  4046. # printer will run the job yet). When the print actually
  4047. # starts on a specific printer the expected-archive lookup
  4048. # used to skip this assignment, leaving printer_id=None
  4049. # forever — which then disables the "Scan for timelapse"
  4050. # button in ArchivesPage (gated on !archive.printer_id).
  4051. if archive.printer_id != printer_id:
  4052. archive.printer_id = printer_id
  4053. await db.commit()
  4054. # Track as active print
  4055. _active_prints[(printer_id, archive.filename)] = archive.id
  4056. if subtask_name:
  4057. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4058. # Start timelapse session if external camera is enabled (#1353).
  4059. # Queue / VP-dispatched prints land here in the expected-archive
  4060. # branch and used to skip start_session entirely — frames were
  4061. # never captured and the post-print stitch silently returned None.
  4062. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4063. # Inject ams_mapping into usage tracker session — the session was created
  4064. # before expected-print promotion, so it may have ams_mapping=None when
  4065. # the MQTT request topic subscription failed (common on P1S/A1).
  4066. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4067. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4068. if _stored_map or _stored_plate_id is not None:
  4069. try:
  4070. from backend.app.services.usage_tracker import _active_sessions
  4071. _ut_session = _active_sessions.get(printer_id)
  4072. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4073. _ut_session.ams_mapping = _stored_map
  4074. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4075. # plate_id injection covers direct-Print of plate N of a multi-plate
  4076. # 3MF — queue prints already capture it via the on_print_start queue
  4077. # lookup, but direct-Print never goes through the queue (#1697).
  4078. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4079. _ut_session.plate_id = _stored_plate_id
  4080. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4081. except Exception:
  4082. pass
  4083. # Set up energy tracking (#941: persist start on archive row)
  4084. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4085. await ws_manager.send_archive_updated(
  4086. {
  4087. "id": archive.id,
  4088. "status": "printing",
  4089. }
  4090. )
  4091. # Send notification with archive data (reprint/scheduled)
  4092. if not notification_sent:
  4093. # Use archive's created_by_id; fall back to the creator registered via
  4094. # register_expected_print (handles library-file-based queue items where
  4095. # the freshly-created archive has no created_by_id yet).
  4096. # Pop ALL matching keys so no stale entries remain in the dict.
  4097. fallback_creator = None
  4098. for key in expected_keys:
  4099. popped = _expected_print_creators.pop(key, None)
  4100. if fallback_creator is None:
  4101. fallback_creator = popped
  4102. archive_data = {
  4103. "print_time_seconds": archive.print_time_seconds,
  4104. "created_by_id": archive.created_by_id or fallback_creator,
  4105. }
  4106. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4107. # Extract printable objects from the archived 3MF file
  4108. _load_objects_from_archive(archive, printer_id, logger)
  4109. # Store Spoolman tracking data for per-filament usage reporting
  4110. try:
  4111. await _store_spoolman_print_data(
  4112. printer_id,
  4113. archive.id,
  4114. archive.file_path,
  4115. db,
  4116. printer_manager,
  4117. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4118. plate_id=_get_start_plate_id(archive.id),
  4119. )
  4120. except Exception as e:
  4121. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4122. # Price the print from its spools now rather than only at completion (#3261)
  4123. _schedule_archive_cost_estimate(
  4124. printer_id,
  4125. archive.id,
  4126. printer_manager,
  4127. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4128. plate_id=_get_start_plate_id(archive.id),
  4129. session_factory=async_session,
  4130. )
  4131. # Capture timelapse file baseline for snapshot-diff on completion
  4132. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4133. # hit this branch — without the baseline the completion-time scan
  4134. # falls into its "take baseline now" fallback, which snapshots
  4135. # AFTER the new MP4 already exists and never matches a diff
  4136. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4137. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4138. return # Skip creating a new archive
  4139. # Check if there's already a "printing" archive for this printer/file
  4140. # This prevents duplicates when backend restarts during an active print
  4141. from backend.app.models.archive import PrintArchive
  4142. existing_archive: PrintArchive | None = None
  4143. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4144. # across a backend restart for the same print, so this is the most
  4145. # reliable way to reattach. We also accept a previously stale-cancelled
  4146. # archive here so users upgrading mid-print get revived when the row
  4147. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4148. if subtask_id:
  4149. by_id = await db.execute(
  4150. select(PrintArchive)
  4151. .where(PrintArchive.printer_id == printer_id)
  4152. .where(PrintArchive.subtask_id == subtask_id)
  4153. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4154. .order_by(PrintArchive.created_at.desc())
  4155. .limit(1)
  4156. )
  4157. candidate = by_id.scalar_one_or_none()
  4158. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4159. existing_archive = candidate
  4160. # Fallback match: name-based lookup. Kept as-is for prints whose
  4161. # subtask_id is missing ("0" / local / non-cloud prints).
  4162. if existing_archive is None:
  4163. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4164. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4165. # A print started from the printer's screen names its file in full,
  4166. # so the forms above double its extension. The file itself is the
  4167. # one exact match, and nothing looser is added (#3009).
  4168. if _subtask_is_the_file(subtask_name, filename):
  4169. archive_filenames.append(subtask_name)
  4170. existing = await db.execute(
  4171. select(PrintArchive)
  4172. .where(PrintArchive.printer_id == printer_id)
  4173. .where(PrintArchive.status == "printing")
  4174. .where(
  4175. or_(
  4176. PrintArchive.print_name == check_name,
  4177. PrintArchive.filename.in_(archive_filenames),
  4178. )
  4179. )
  4180. .order_by(PrintArchive.created_at.desc())
  4181. .limit(1)
  4182. )
  4183. existing_archive = existing.scalar_one_or_none()
  4184. if existing_archive:
  4185. # subtask_id match → always resume, regardless of age. Same print,
  4186. # just a backend restart. Revive if it was previously stale-cancelled.
  4187. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4188. if subtask_match:
  4189. if existing_archive.status == "cancelled":
  4190. logger.warning(
  4191. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4192. existing_archive.id,
  4193. subtask_id,
  4194. )
  4195. existing_archive.status = "printing"
  4196. existing_archive.failure_reason = None
  4197. await db.commit()
  4198. else:
  4199. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4200. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4201. if existing_archive.energy_start_kwh is None:
  4202. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4203. if not notification_sent:
  4204. archive_data = {
  4205. "print_time_seconds": existing_archive.print_time_seconds,
  4206. "created_by_id": existing_archive.created_by_id,
  4207. }
  4208. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4209. _load_objects_from_archive(existing_archive, printer_id, logger)
  4210. return
  4211. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4212. # stale from the printer's *current* progress, not wall-clock age.
  4213. # A genuinely long print used to trip a blind 4h cutoff and have its
  4214. # live archive cancelled + duplicated on every backend restart
  4215. # (#1485). If the printer reports real progress, this name-matched
  4216. # 'printing' archive IS that ongoing print — resume it whatever its
  4217. # age. Only treat it as a stale leftover when the printer clearly
  4218. # shows a different, freshly-started print: near-0% progress on an
  4219. # archive far too old to still be at 0%. Unknown progress (printer
  4220. # not connected) never cancels — resuming is the safe default.
  4221. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4222. live_status = printer_manager.get_status(printer_id)
  4223. live_progress = getattr(live_status, "progress", None) if live_status else None
  4224. looks_stale = (
  4225. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4226. )
  4227. if looks_stale:
  4228. logger.warning(
  4229. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4230. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4231. )
  4232. existing_archive.status = "cancelled"
  4233. # Canonical key, not a sentence (issue #2974). "No status update
  4234. # received" is what both stale paths actually observed; which of
  4235. # the two it was is already carried by ``status`` -- cancelled
  4236. # here, the reconciled outcome at the reconnect site -- so one
  4237. # key loses no information and gives the Statistics breakdown a
  4238. # single bucket instead of two untranslatable prose strings.
  4239. existing_archive.failure_reason = "noStatusUpdate"
  4240. await db.commit()
  4241. # Fall through to create new archive (don't return)
  4242. else:
  4243. logger.info(
  4244. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4245. )
  4246. # Track this as the active print
  4247. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4248. # Attach subtask_id retroactively so future restarts can resume.
  4249. # Compare for inequality (not "is empty") to also pick up reprint
  4250. # dispatches that mint a fresh id — see #1807 for the bogus
  4251. # "Print Stopped" the strict-empty guard caused on reconnect.
  4252. if subtask_id and existing_archive.subtask_id != subtask_id:
  4253. existing_archive.subtask_id = subtask_id
  4254. await db.commit()
  4255. # Also set up energy tracking if not already tracked (#941: persisted column)
  4256. if existing_archive.energy_start_kwh is None:
  4257. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4258. # Send notification with archive data (existing archive)
  4259. if not notification_sent:
  4260. archive_data = {
  4261. "print_time_seconds": existing_archive.print_time_seconds,
  4262. "created_by_id": existing_archive.created_by_id,
  4263. }
  4264. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4265. # Extract printable objects from the archived 3MF file
  4266. _load_objects_from_archive(existing_archive, printer_id, logger)
  4267. return
  4268. # Build list of possible 3MF filenames to try
  4269. possible_names = []
  4270. # Bambu printers typically store files as "Name.gcode.3mf"
  4271. # The subtask_name is usually the best source for the filename
  4272. if subtask_name:
  4273. if _subtask_is_the_file(subtask_name, filename):
  4274. # A print started from the printer's own screen reports the
  4275. # file's full name, extension included. That is the file, so
  4276. # no extension is appended to it (#3009).
  4277. possible_names.append(subtask_name)
  4278. else:
  4279. # Try common Bambu naming patterns
  4280. possible_names.append(f"{subtask_name}.gcode.3mf")
  4281. possible_names.append(f"{subtask_name}.3mf")
  4282. # Try original filename with .3mf extension
  4283. if filename:
  4284. # Extract just the filename part, not the full path
  4285. fname = filename.split("/")[-1] if "/" in filename else filename
  4286. if fname.endswith(".3mf"):
  4287. possible_names.append(fname)
  4288. elif fname.endswith(".gcode"):
  4289. base = fname.rsplit(".", 1)[0]
  4290. possible_names.append(f"{base}.gcode.3mf")
  4291. possible_names.append(f"{base}.3mf")
  4292. else:
  4293. possible_names.append(f"{fname}.gcode.3mf")
  4294. possible_names.append(f"{fname}.3mf")
  4295. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4296. space_variants = []
  4297. for name in possible_names:
  4298. if " " in name:
  4299. space_variants.append(name.replace(" ", "_"))
  4300. possible_names.extend(space_variants)
  4301. # Remove duplicates while preserving order
  4302. seen = set()
  4303. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4304. logger.info("Trying filenames: %s", possible_names)
  4305. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4306. # here means none of the expected-/existing-archive write branches ran
  4307. # (they all return earlier) — only SELECTs have executed on this path, so
  4308. # this commit persists nothing; it ends the read transaction so the
  4309. # connection returns to the pool during the download. That download tries
  4310. # up to five remote paths per candidate filename with retry/backoff and
  4311. # can run for minutes under FTP contention; holding the session across it
  4312. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4313. # work runs during the download — the new-archive writes below re-acquire
  4314. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4315. await db.commit()
  4316. # Try to find and download the 3MF file
  4317. temp_path = None
  4318. downloaded_filename = None
  4319. # Cache check: cover endpoint may have already pulled this 3MF during
  4320. # the print (frontend opens the card and shows the thumbnail) — reuse
  4321. # that file instead of re-downloading 36MB over the same FTP link that
  4322. # just served it (#972). The cache keys on a normalized filename so
  4323. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4324. for try_filename in possible_names:
  4325. if not try_filename.endswith(".3mf"):
  4326. continue
  4327. cached = get_cached_3mf(printer_id, try_filename)
  4328. if cached:
  4329. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4330. temp_path = cached
  4331. downloaded_filename = try_filename
  4332. break
  4333. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4334. # H2-series and P2S the answer is routinely no — the file stays on
  4335. # internal eMMC and port 990 only ever serves external storage — and
  4336. # then the whole sweep below (six filenames x five directories x four
  4337. # retries, then the directory walk) is ~110 connections that cannot
  4338. # succeed. Skip it and say why (#2780).
  4339. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4340. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4341. # running rather than because the file is somewhere unreachable. The
  4342. # distinction is the whole of #2957: one is permanent, the other clears
  4343. # in minutes with the file still sitting on the printer.
  4344. blocked_by_ftps_cooloff = False
  4345. # Set when a probe reached the printer and still came back without the
  4346. # file -- a timeout mid-transfer, a refused connection, anything that is
  4347. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4348. # caught by name below, so a file that genuinely is not on the card
  4349. # leaves this False and schedules nothing. Anything else means the
  4350. # transfer, not the file, is what failed, and that does not last (#3063).
  4351. ftp_transfer_failed = False
  4352. # The print's name, for a fallback archive whose `subtask_name` the
  4353. # plate guard below had to disown. Display only, and deliberately kept
  4354. # apart from `subtask_name`: that variable is what every file lookup
  4355. # here is built from, and once a name has been shown to fetch another
  4356. # plate's 3MF it must not key `_active_prints` either, or the cover
  4357. # endpoint hands the same contradicted file to
  4358. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4359. display_name_after_plate_reject: str | None = None
  4360. # Get FTP retry settings
  4361. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4362. # ...but "the printer put it on eMMC" is where it went, not whether we
  4363. # can read it. An H2D with a card in mirrors the job to /cache and
  4364. # serves it happily, and skipping on the URL alone cost that reporter
  4365. # every archive for two days (#2856). So ask the printer instead of
  4366. # guessing: the dispatch named the exact file, which is one connection
  4367. # walking five paths rather than the sweep's ~110. Only when the probe
  4368. # comes back empty does the verdict's reason stand.
  4369. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4370. if ftps_handshake_blocked(printer.ip_address):
  4371. # Deliberately NOT recorded as a cool-off give-up. This branch
  4372. # only runs on an unreachable verdict, and that verdict is the
  4373. # honest, permanent reason the archive is empty — the probe was
  4374. # a long shot on top of it. Blaming the cool-off here would
  4375. # schedule a retry for a file sitting on internal eMMC, which is
  4376. # the sweep #2780 removed (#2957).
  4377. logger.debug(
  4378. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4379. storage.probe_filename,
  4380. printer_id,
  4381. )
  4382. else:
  4383. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4384. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4385. try:
  4386. probe_hit = await download_file_try_paths_async(
  4387. printer.ip_address,
  4388. printer.access_code,
  4389. ftp_probe_paths(storage.probe_filename),
  4390. probe_path,
  4391. socket_timeout=ftp_timeout,
  4392. printer_model=printer.model,
  4393. )
  4394. except Exception as e:
  4395. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4396. probe_hit = False
  4397. if probe_hit:
  4398. downloaded_filename = storage.probe_filename
  4399. temp_path = probe_path
  4400. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4401. # Naming the path, not just the file: a printer that keeps
  4402. # uploads around for weeks can serve a same-named copy of an
  4403. # earlier slice, and without the directory in the log that
  4404. # mismatch is invisible rather than merely rare (#1820).
  4405. logger.info(
  4406. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4407. downloaded_filename,
  4408. probe_hit,
  4409. printer_id,
  4410. storage.reason,
  4411. )
  4412. if not storage.reachable and not downloaded_filename:
  4413. # Same opening words whether or not a probe ran, because that is
  4414. # the phrase support asks people to grep for — only the tail says
  4415. # which of the two happened.
  4416. logger.info(
  4417. "Skipping the 3MF lookup for printer %s: %s — %s",
  4418. printer_id,
  4419. storage.reason,
  4420. "no copy of it on external storage either"
  4421. if storage.probe_filename
  4422. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4423. )
  4424. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4425. if not try_filename.endswith(".3mf"):
  4426. continue
  4427. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4428. # printers, so try it first — deferring it to last cost #972's reporter
  4429. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4430. # landing on the path that actually had the file.
  4431. remote_paths = [
  4432. f"/{try_filename}",
  4433. f"/cache/{try_filename}",
  4434. f"/model/{try_filename}",
  4435. f"/data/{try_filename}",
  4436. f"/data/Metadata/{try_filename}",
  4437. ]
  4438. temp_path = app_settings.archive_dir / "temp" / try_filename
  4439. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4440. for remote_path in remote_paths:
  4441. if ftps_handshake_blocked(printer.ip_address):
  4442. # The printer's FTPS service is not completing a TLS
  4443. # handshake, so it has no path we could reach — walking the
  4444. # remaining candidates only re-runs the same failure
  4445. # (#2780). Fall through to the no-3MF archive now.
  4446. #
  4447. # Remember *why*, though. This is the one give-up that is
  4448. # temporary: the cool-off clears in minutes and the file was
  4449. # on the printer the whole time. The fallback archive is
  4450. # stamped with it so a retry can be scheduled, and so the
  4451. # Archives banner stops blaming storage (#2957).
  4452. blocked_by_ftps_cooloff = True
  4453. logger.warning(
  4454. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4455. printer_id,
  4456. )
  4457. break
  4458. logger.debug("Trying FTP download: %s", remote_path)
  4459. try:
  4460. if ftp_retry_enabled:
  4461. downloaded = await with_ftp_retry(
  4462. download_file_async,
  4463. printer.ip_address,
  4464. printer.access_code,
  4465. remote_path,
  4466. temp_path,
  4467. timeout=ftp_timeout,
  4468. socket_timeout=ftp_timeout,
  4469. printer_model=printer.model,
  4470. max_retries=ftp_retry_count,
  4471. retry_delay=ftp_retry_delay,
  4472. operation_name=f"Download 3MF from {remote_path}",
  4473. cooloff_ip=printer.ip_address,
  4474. non_retry_exceptions=(FileNotOnPrinterError,),
  4475. )
  4476. else:
  4477. downloaded = await download_file_async(
  4478. printer.ip_address,
  4479. printer.access_code,
  4480. remote_path,
  4481. temp_path,
  4482. timeout=ftp_timeout,
  4483. socket_timeout=ftp_timeout,
  4484. printer_model=printer.model,
  4485. )
  4486. if downloaded:
  4487. downloaded_filename = try_filename
  4488. logger.info("Downloaded: %s", remote_path)
  4489. # Populate shared cache so the cover endpoint (if it
  4490. # runs next) doesn't refetch the same 36MB over FTP.
  4491. cache_3mf_download(printer_id, try_filename, temp_path)
  4492. break
  4493. # with_ftp_retry returns None once it has spent its budget,
  4494. # and download_file_async returns False on a timeout, so an
  4495. # exhausted transfer arrives here rather than as an
  4496. # exception (#3063).
  4497. ftp_transfer_failed = True
  4498. except FileNotOnPrinterError:
  4499. # 550 — file isn't at this path. Advance to next candidate
  4500. # without burning the retry budget.
  4501. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4502. except Exception as e:
  4503. ftp_transfer_failed = True
  4504. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4505. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4506. break
  4507. # If still not found, try listing directories to find matching file
  4508. # Different printer models use different directory structures. Skipped
  4509. # when the printer's FTPS handshake is failing — the directory walk is
  4510. # five more connections that cannot get further than the download did.
  4511. if (
  4512. not downloaded_filename
  4513. and storage.reachable
  4514. and (filename or subtask_name)
  4515. and not ftps_handshake_blocked(printer.ip_address)
  4516. ):
  4517. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4518. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4519. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4520. for search_dir in search_dirs:
  4521. if downloaded_filename:
  4522. break
  4523. try:
  4524. dir_files = await list_files_async(
  4525. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4526. )
  4527. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4528. if threemf_files:
  4529. logger.info(
  4530. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4531. )
  4532. for f in dir_files:
  4533. if f.get("is_directory"):
  4534. continue
  4535. fname = f.get("name", "")
  4536. # Normalize both for comparison (spaces and underscores are equivalent)
  4537. fname_normalized = fname.lower().replace(" ", "_")
  4538. search_normalized = search_term.replace(" ", "_")
  4539. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4540. logger.info("Found matching file in %s: %s", search_dir, fname)
  4541. temp_path = app_settings.archive_dir / "temp" / fname
  4542. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4543. remote_full_path = posixpath.join(search_dir, fname)
  4544. if ftp_retry_enabled:
  4545. downloaded = await with_ftp_retry(
  4546. download_file_async,
  4547. printer.ip_address,
  4548. printer.access_code,
  4549. remote_full_path,
  4550. temp_path,
  4551. timeout=ftp_timeout,
  4552. socket_timeout=ftp_timeout,
  4553. printer_model=printer.model,
  4554. max_retries=ftp_retry_count,
  4555. retry_delay=ftp_retry_delay,
  4556. operation_name=f"Download 3MF from {remote_full_path}",
  4557. cooloff_ip=printer.ip_address,
  4558. )
  4559. else:
  4560. downloaded = await download_file_async(
  4561. printer.ip_address,
  4562. printer.access_code,
  4563. remote_full_path,
  4564. temp_path,
  4565. timeout=ftp_timeout,
  4566. socket_timeout=ftp_timeout,
  4567. printer_model=printer.model,
  4568. )
  4569. if downloaded:
  4570. downloaded_filename = fname
  4571. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4572. cache_3mf_download(printer_id, fname, temp_path)
  4573. break
  4574. # The listing named the file, so it is on the card;
  4575. # only the transfer failed (#3063).
  4576. ftp_transfer_failed = True
  4577. except Exception as e:
  4578. logger.debug("Failed to list %s: %s", search_dir, e)
  4579. # Validate the downloaded 3MF actually matches the plate that's running
  4580. # (#1204): subtask_name lags across consecutive plates of the same model,
  4581. # so the first FTP candidate (built from subtask_name) can land on the
  4582. # previous plate's still-resident upload. Cross-check the slice_info
  4583. # plate index against the plate parsed from gcode_file (always fresh —
  4584. # it's the field whose change triggered this callback).
  4585. if downloaded_filename and temp_path:
  4586. expected_plate = parse_plate_id(filename)
  4587. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4588. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4589. logger.warning(
  4590. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4591. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4592. downloaded_filename,
  4593. actual_plate,
  4594. expected_plate,
  4595. subtask_name,
  4596. )
  4597. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4598. retry_succeeded = False
  4599. if corrected_subtask and corrected_subtask != subtask_name:
  4600. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4601. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4602. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4603. for remote_path in (
  4604. f"/{try_filename}",
  4605. f"/cache/{try_filename}",
  4606. f"/model/{try_filename}",
  4607. f"/data/{try_filename}",
  4608. f"/data/Metadata/{try_filename}",
  4609. ):
  4610. try:
  4611. if ftp_retry_enabled:
  4612. downloaded = await with_ftp_retry(
  4613. download_file_async,
  4614. printer.ip_address,
  4615. printer.access_code,
  4616. remote_path,
  4617. retry_temp_path,
  4618. timeout=ftp_timeout,
  4619. socket_timeout=ftp_timeout,
  4620. printer_model=printer.model,
  4621. max_retries=ftp_retry_count,
  4622. retry_delay=ftp_retry_delay,
  4623. operation_name=f"Re-download 3MF from {remote_path}",
  4624. cooloff_ip=printer.ip_address,
  4625. non_retry_exceptions=(FileNotOnPrinterError,),
  4626. )
  4627. else:
  4628. downloaded = await download_file_async(
  4629. printer.ip_address,
  4630. printer.access_code,
  4631. remote_path,
  4632. retry_temp_path,
  4633. timeout=ftp_timeout,
  4634. socket_timeout=ftp_timeout,
  4635. printer_model=printer.model,
  4636. )
  4637. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4638. logger.info(
  4639. "[CALLBACK] Re-download succeeded with corrected name %s "
  4640. "(plate %s) — replacing wrong file",
  4641. try_filename,
  4642. expected_plate,
  4643. )
  4644. try:
  4645. temp_path.unlink(missing_ok=True)
  4646. except OSError:
  4647. pass
  4648. temp_path = retry_temp_path
  4649. downloaded_filename = try_filename
  4650. subtask_name = corrected_subtask
  4651. cache_3mf_download(printer_id, try_filename, temp_path)
  4652. retry_succeeded = True
  4653. break
  4654. elif downloaded:
  4655. # Wrong plate again — discard and keep trying
  4656. try:
  4657. retry_temp_path.unlink(missing_ok=True)
  4658. except OSError:
  4659. pass
  4660. except FileNotOnPrinterError:
  4661. continue
  4662. except Exception as e:
  4663. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4664. if retry_succeeded:
  4665. break
  4666. # If the retry didn't find a matching file, drop the wrong 3MF
  4667. # so the no-3MF fallback below creates an archive whose name
  4668. # at least reflects the right plate.
  4669. if not retry_succeeded:
  4670. logger.warning(
  4671. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4672. expected_plate,
  4673. )
  4674. try:
  4675. temp_path.unlink(missing_ok=True)
  4676. except OSError:
  4677. pass
  4678. temp_path = None
  4679. downloaded_filename = None
  4680. # Whatever the sweep's transport did earlier, it is not why
  4681. # this archive ends up empty: a 3MF downloaded fine, it was
  4682. # just the wrong plate. Retrying would re-fetch that same
  4683. # contradicted file under the same stale names and hand it
  4684. # to _recover_fallback_archive, which checks that a
  4685. # candidate is a readable 3MF but not which plate it is --
  4686. # so the row would be filled in with another plate's
  4687. # filament and cost, the exact swap #2957 removed (#3063).
  4688. ftp_transfer_failed = False
  4689. # Disown the name for *lookups*: it has just been shown to
  4690. # fetch another plate's 3MF, and it keys `_active_prints`
  4691. # below, where the cover endpoint's own download of that
  4692. # same name would find this archive and fill it in with the
  4693. # file we are discarding here.
  4694. #
  4695. # Keep it for the *title*, which is a separate question.
  4696. # ``swap_plate_suffix`` returns None both for a name that
  4697. # carries no "- Plate N" / "_plate_N" suffix and for no
  4698. # name at all, and those are not the same situation: a name
  4699. # without a suffix holds no stale plate number to be wrong
  4700. # about. Blanking both uses at once dropped the project
  4701. # name too, and the row fell through to the gcode_file path
  4702. # titled "plate_1" though the real name was in hand.
  4703. # #1204's own premise is consecutive plates *of the same
  4704. # model*, so the project part is right either way (#3126).
  4705. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4706. subtask_name = corrected_subtask or ""
  4707. if not downloaded_filename or not temp_path:
  4708. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4709. # Create a fallback archive without 3MF data so the print is still tracked
  4710. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4711. try:
  4712. from backend.app.models.archive import PrintArchive
  4713. # Why the card is empty. The two temporary causes outrank the
  4714. # storage verdict because they say the sweep never got a fair
  4715. # answer: a cool-off skipped it at the transport, and a failed
  4716. # transfer reached the printer but never finished. Either way
  4717. # the file is still on the card, so reporting where the printer
  4718. # files its jobs would describe a setting that is not the
  4719. # problem (#2957, #3063).
  4720. if blocked_by_ftps_cooloff:
  4721. no_3mf_reason = REASON_FTPS_COOLOFF
  4722. elif storage.reachable and ftp_transfer_failed:
  4723. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4724. else:
  4725. no_3mf_reason = storage.reason
  4726. # Derive print name from subtask_name or filename. The
  4727. # plate guard's disowned name comes second: it is a real name
  4728. # for a real print, and only the gcode_file path is left
  4729. # otherwise -- which titles the row "plate_1" (#3126).
  4730. print_name = subtask_name or display_name_after_plate_reject or filename
  4731. if print_name:
  4732. # Clean up the name (remove extensions, path parts)
  4733. print_name = print_name.split("/")[-1]
  4734. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4735. else:
  4736. print_name = "Unknown Print"
  4737. # Recover estimated print time from MQTT (best-effort for notifications)
  4738. fallback_print_time = None
  4739. mqtt_remaining = data.get("remaining_time")
  4740. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4741. fallback_print_time = int(mqtt_remaining)
  4742. if fallback_print_time is None:
  4743. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4744. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4745. fallback_print_time = int(mc_remaining * 60)
  4746. # Best-effort filament metadata from MQTT — see
  4747. # _extract_filament_data_from_mqtt. Without this the fallback
  4748. # archive's filament fields stayed NULL even though the AMS
  4749. # state at print start was sitting right there in `data`.
  4750. # The slicer's ams_mapping (when present) narrows the result
  4751. # to slots actually used by the print (#1533).
  4752. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4753. # Create minimal archive entry
  4754. fallback_archive = PrintArchive(
  4755. printer_id=printer_id,
  4756. filename=filename or f"{print_name}.3mf",
  4757. file_path="", # Empty - no 3MF file available
  4758. file_size=0,
  4759. print_name=print_name,
  4760. print_time_seconds=fallback_print_time,
  4761. status="printing",
  4762. started_at=datetime.now(timezone.utc),
  4763. subtask_id=subtask_id,
  4764. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4765. filament_type=mqtt_filament_meta.get("filament_type"),
  4766. filament_color=mqtt_filament_meta.get("filament_color"),
  4767. extra_data={
  4768. "no_3mf_available": True,
  4769. # Why the card is empty, when we know -- see above. The
  4770. # banner reads this to stop telling H2/P2 owners to
  4771. # switch on a setting that is already on and would not
  4772. # have helped (#2780).
  4773. "no_3mf_reason": no_3mf_reason,
  4774. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4775. "_print_data": data,
  4776. },
  4777. )
  4778. db.add(fallback_archive)
  4779. await db.commit()
  4780. await db.refresh(fallback_archive)
  4781. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4782. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4783. # Track as active print
  4784. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4785. if filename:
  4786. _active_prints[(printer_id, filename)] = fallback_archive.id
  4787. if subtask_name:
  4788. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4789. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4790. # Record starting energy if smart plug available (#941: persisted column)
  4791. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4792. # Send WebSocket notification
  4793. await ws_manager.send_archive_created(
  4794. {
  4795. "id": fallback_archive.id,
  4796. "printer_id": fallback_archive.printer_id,
  4797. "filename": fallback_archive.filename,
  4798. "print_name": fallback_archive.print_name,
  4799. "status": fallback_archive.status,
  4800. }
  4801. )
  4802. # MQTT relay - publish archive created
  4803. try:
  4804. await mqtt_relay.on_archive_created(
  4805. archive_id=fallback_archive.id,
  4806. print_name=fallback_archive.print_name,
  4807. printer_name=printer.name,
  4808. status=fallback_archive.status,
  4809. )
  4810. except Exception:
  4811. pass # Don't fail if MQTT fails
  4812. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4813. try:
  4814. await _store_spoolman_print_data(
  4815. printer_id,
  4816. fallback_archive.id,
  4817. fallback_archive.file_path,
  4818. db,
  4819. printer_manager,
  4820. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4821. plate_id=_get_start_plate_id(fallback_archive.id),
  4822. )
  4823. except Exception as e:
  4824. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4825. # Both temporary give-ups are worth coming back for, and for
  4826. # the same reason: the file is on the printer and the last look
  4827. # failed at the transport rather than finding nothing. One waits
  4828. # out the handshake block (#2957), the other waits for the
  4829. # printer to stop being busy (#3063). Deliberately not scheduled
  4830. # for a storage verdict: a file on internal eMMC will not appear
  4831. # at any FTPS path however long we wait, and retrying it is
  4832. # exactly the sweep #2780 removed.
  4833. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4834. # `possible_names`, not the raw MQTT strings: it is the exact
  4835. # list this flow just tried, already stripped of any path
  4836. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4837. # some firmware) and deduped.
  4838. _schedule_fallback_3mf_retry(
  4839. printer_id=printer_id,
  4840. archive_id=fallback_archive.id,
  4841. filenames=list(possible_names),
  4842. reason=no_3mf_reason,
  4843. )
  4844. # Send notification without archive data (file not found)
  4845. if not notification_sent:
  4846. await _send_print_start_notification(printer_id, data, logger=logger)
  4847. # The same baseline the other two on_print_start branches take
  4848. # (#2704), and last for the same reason they are: it lists the
  4849. # printer's timelapse directory, so a slow card must not delay
  4850. # the _active_prints registration, the energy reading, the
  4851. # archive-created event or the start notification above it.
  4852. #
  4853. # This branch never took one, so every no-3MF archive reached
  4854. # completion with no baseline in memory and none on the row, and
  4855. # the completion scan fell into its "snapshot now" fallback --
  4856. # which runs after the printer has written the video, so the new
  4857. # file landed inside the baseline and no diff ever matched
  4858. # (#2957 follow-up).
  4859. #
  4860. # Skipped when the FTPS cool-off is what produced this fallback:
  4861. # the listing needs the same connection that just failed, so it
  4862. # could only record that the card was unreadable. The scan
  4863. # handles that case by refusing to choose between candidates.
  4864. if not blocked_by_ftps_cooloff:
  4865. await _capture_timelapse_baseline_at_start(
  4866. printer, printer_id, logger, archive_id=fallback_archive.id
  4867. )
  4868. return
  4869. except Exception as e:
  4870. logger.error("Failed to create fallback archive: %s", e)
  4871. # Send notification without archive data (file not found)
  4872. if not notification_sent:
  4873. await _send_print_start_notification(printer_id, data, logger=logger)
  4874. return
  4875. try:
  4876. # Archive the file with status "printing"
  4877. service = ArchiveService(db)
  4878. archive = await service.archive_print(
  4879. printer_id=printer_id,
  4880. source_file=temp_path,
  4881. print_data={**data, "status": "printing"},
  4882. subtask_id=subtask_id,
  4883. )
  4884. if archive:
  4885. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4886. # Set on the row rather than passed to archive_print, which also
  4887. # serves the queue dispatcher — there the queue item decides.
  4888. # Guarded because this branch has no ``except``: an unhandled
  4889. # write error would take the _active_prints registration, the
  4890. # start notification, the energy reading and the timelapse
  4891. # baseline below it with it, and a missing prompt is by far the
  4892. # cheaper failure.
  4893. archive_id = archive.id
  4894. try:
  4895. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4896. archive.confirm_requested = True
  4897. await db.commit()
  4898. except Exception as e:
  4899. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4900. # The rollback expires every loaded object, and on an async
  4901. # session reading one afterwards raises instead of
  4902. # reloading, so the two this branch goes on to use are
  4903. # fetched again. The archive itself was committed by
  4904. # archive_print; only the flag is lost.
  4905. try:
  4906. await db.rollback()
  4907. archive = await db.get(PrintArchive, archive_id)
  4908. printer = await db.get(Printer, printer_id)
  4909. except Exception as reload_error:
  4910. logger.warning(
  4911. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4912. )
  4913. # Track this active print (use both original filename and downloaded filename)
  4914. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4915. if filename and filename != downloaded_filename:
  4916. _active_prints[(printer_id, filename)] = archive.id
  4917. if subtask_name:
  4918. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4919. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4920. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4921. # Record starting energy from smart plug if available (#941: persisted column)
  4922. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4923. await ws_manager.send_archive_created(
  4924. {
  4925. "id": archive.id,
  4926. "printer_id": archive.printer_id,
  4927. "filename": archive.filename,
  4928. "print_name": archive.print_name,
  4929. "status": archive.status,
  4930. }
  4931. )
  4932. # MQTT relay - publish archive created
  4933. try:
  4934. await mqtt_relay.on_archive_created(
  4935. archive_id=archive.id,
  4936. print_name=archive.print_name,
  4937. printer_name=printer.name,
  4938. status=archive.status,
  4939. )
  4940. except Exception:
  4941. pass # Don't fail if MQTT fails
  4942. # Send notification with archive data (new archive created)
  4943. if not notification_sent:
  4944. archive_data = {
  4945. "print_time_seconds": archive.print_time_seconds,
  4946. "created_by_id": archive.created_by_id,
  4947. }
  4948. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4949. # Extract printable objects for skip object functionality
  4950. try:
  4951. from backend.app.services.archive import extract_printable_objects_from_3mf
  4952. client = printer_manager.get_client(printer_id)
  4953. if client:
  4954. with open(temp_path, "rb") as f:
  4955. threemf_data = f.read()
  4956. # Extract with positions for UI overlay, scoped to the
  4957. # plate that is printing — an all-plates 3MF carries
  4958. # every plate's objects (#2522).
  4959. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4960. threemf_data,
  4961. plate_number=resolve_plate_id(client.state),
  4962. include_positions=True,
  4963. )
  4964. if printable_objects:
  4965. # Store objects in printer state
  4966. client.state.printable_objects = printable_objects
  4967. client.state.printable_objects_bbox_all = bbox_all
  4968. client.state.skipped_objects = [] # Reset skipped objects for new print
  4969. logger.info(
  4970. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4971. )
  4972. except Exception as e:
  4973. logger.debug("Failed to extract printable objects: %s", e)
  4974. # Store Spoolman tracking data for per-filament usage reporting
  4975. try:
  4976. await _store_spoolman_print_data(
  4977. printer_id,
  4978. archive.id,
  4979. archive.file_path,
  4980. db,
  4981. printer_manager,
  4982. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4983. plate_id=_get_start_plate_id(archive.id),
  4984. )
  4985. except Exception as e:
  4986. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4987. # Price the print from its spools now rather than only at completion (#3261)
  4988. _schedule_archive_cost_estimate(
  4989. printer_id,
  4990. archive.id,
  4991. printer_manager,
  4992. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4993. plate_id=_get_start_plate_id(archive.id),
  4994. session_factory=async_session,
  4995. )
  4996. # Capture timelapse file baseline for snapshot-diff on completion
  4997. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4998. finally:
  4999. # Keep temp_path around until print completes so the cover endpoint
  5000. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5001. # the file. If the cache entry was evicted early (file vanished),
  5002. # clean up any stragglers here to avoid leaking disk on retries.
  5003. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5004. if temp_path and temp_path.exists() and cached_now != temp_path:
  5005. temp_path.unlink()
  5006. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5007. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5008. # tests can shrink them without waiting out real delays.
  5009. #
  5010. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5011. # looking. Across 247 support bundles the attempt that found the video was #1
  5012. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5013. # decaying one, which is the signature of a budget that expires while files are
  5014. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5015. # prints make big videos and the printer writes them after the print ends, so
  5016. # the poll now runs for minutes and costs one FTP LIST per round.
  5017. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5018. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5019. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5020. def _timelapse_scan_max_attempts() -> int:
  5021. """Round cap for the poll, derived from the wall-clock budget.
  5022. The deadline alone is not a sufficient bound: it assumes each round really
  5023. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5024. and an FTP list that fails immediately would otherwise spin against the
  5025. printer at full speed for the whole window. Whichever bound is reached
  5026. first ends the poll.
  5027. """
  5028. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5029. # A zero interval makes the wall-clock budget meaningless; fall back to
  5030. # the round count the production interval would have given.
  5031. return 32
  5032. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5033. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5034. """Video filenames already attached to some other archive of this printer.
  5035. Used to disambiguate when more than one file is new since the baseline —
  5036. which happens when a previous print's video landed after this print's
  5037. baseline was taken. Ordering the candidates would be the obvious fix and is
  5038. the wrong one: it can only be done on mtime or on the filename timestamp,
  5039. both of which come from the printer's own clock, and a LAN-only printer
  5040. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5041. ``attach_timelapse`` saves the video into the archive directory under the
  5042. printer's original filename, and the later MP4 conversion keeps the stem,
  5043. so the stem of ``timelapse_path`` recovers what was claimed.
  5044. """
  5045. from backend.app.models.archive import PrintArchive
  5046. rows = await db.execute(
  5047. select(PrintArchive.timelapse_path).where(
  5048. PrintArchive.printer_id == printer_id,
  5049. PrintArchive.id != exclude_archive_id,
  5050. PrintArchive.timelapse_path.is_not(None),
  5051. )
  5052. )
  5053. return {Path(p).stem for p in rows.scalars().all() if p}
  5054. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5055. """Whether an *empty* timelapse listing for *printer* can be believed.
  5056. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5057. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5058. from one holding no videos. Everywhere that only wants to know "is there a
  5059. video yet" the difference does not matter — both mean "not yet, retry".
  5060. It matters where an empty listing is recorded as a *baseline*. Recording
  5061. "the card held nothing" for a card that was never read means every video on
  5062. it counts as new once the cool-off expires, and the completion scan then
  5063. attaches a stale video to this print and deletes it from the printer
  5064. (#2957 follow-up). Those two callers ask this first.
  5065. """
  5066. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5067. ip_address = getattr(printer, "ip_address", None)
  5068. if not ip_address:
  5069. return True
  5070. return not ftps_handshake_blocked(ip_address)
  5071. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5072. """List video files from printer's timelapse directory.
  5073. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5074. Returns (video_files, found_path) where video_files is a list of file dicts
  5075. and found_path is the directory where they were found, or ([], None).
  5076. An empty return does not distinguish "no videos" from "could not read the
  5077. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5078. baseline callers consult before believing one.
  5079. """
  5080. from backend.app.services.bambu_ftp import list_files_async
  5081. logger = logging.getLogger(__name__)
  5082. # No card in the slot means no /timelapse to walk — four connections that
  5083. # can only fail, on a path whose failures are swallowed and so would go on
  5084. # costing time silently forever (#2780).
  5085. #
  5086. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5087. # inside the loop's own try/except, so a caller that passed something
  5088. # unexpected used to get an empty listing rather than an exception. Keep
  5089. # that, instead of making this gate the first thing that can raise here.
  5090. printer_id = getattr(printer, "id", None)
  5091. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5092. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5093. return [], None
  5094. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5095. try:
  5096. found_files = await list_files_async(
  5097. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5098. )
  5099. if found_files:
  5100. video_files = [
  5101. f
  5102. for f in found_files
  5103. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5104. ]
  5105. if video_files:
  5106. return video_files, timelapse_path
  5107. except Exception as e:
  5108. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5109. continue
  5110. return [], None
  5111. async def _capture_timelapse_baseline_at_start(
  5112. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5113. ) -> None:
  5114. """Snapshot the printer's timelapse directory at print start so the
  5115. completion-time scan can pick the new file by set-difference.
  5116. Must be called from every on_print_start path that proceeds to a real
  5117. print — both the new-archive branch and the expected-archive branch (which
  5118. queue / VP-dispatched prints take). Without a baseline,
  5119. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5120. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5121. so the new file ends up in the "baseline" set and no diff ever matches.
  5122. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5123. unreliable — the snapshot-diff approach sidesteps that entirely.
  5124. When ``archive_id`` is known the baseline is also written to the archive
  5125. row, so it survives a restart and the manual "Scan for Timelapse" button
  5126. can run the same diff instead of falling back to clock-based matching
  5127. (#2704). Only baselines taken at print start are persisted — one taken at
  5128. completion already contains the new video and would poison a later scan.
  5129. """
  5130. names: set[str] | None = None
  5131. try:
  5132. if not _timelapse_listing_is_trustworthy(printer):
  5133. # Recorded anyway, deliberately. An empty baseline taken off a card
  5134. # we could not read is not authoritative, but it is still the right
  5135. # *default*: Bambuddy deletes each video from the printer once it is
  5136. # attached, so the usual card holds exactly one video at completion
  5137. # and an empty baseline resolves it correctly. Persisting NULL
  5138. # instead would send completion to take its own snapshot, by which
  5139. # point this print's video is on the card and would be swallowed by
  5140. # it. The ambiguity is handled where it actually bites — see
  5141. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5142. logger.warning(
  5143. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5144. "handshake cool-off, so the card could not be read — treating it as empty",
  5145. printer_id,
  5146. )
  5147. baseline_files, _ = await _list_timelapse_videos(printer)
  5148. names = {f.get("name", "") for f in baseline_files}
  5149. _timelapse_baselines[printer_id] = names
  5150. logger.info(
  5151. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5152. len(names),
  5153. printer_id,
  5154. )
  5155. except Exception as e:
  5156. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5157. if archive_id is None:
  5158. return
  5159. try:
  5160. async with async_session() as db:
  5161. from backend.app.models.archive import PrintArchive
  5162. archive = await db.get(PrintArchive, archive_id)
  5163. if archive is not None:
  5164. # Written even when the listing failed, and then as NULL. A
  5165. # reprint reuses the archive row, so leaving the previous run's
  5166. # baseline in place would have the scan diff this print against
  5167. # the state of the printer before the *last* one — and a stale
  5168. # baseline reads as authoritative, where NULL correctly falls
  5169. # back to a fresh snapshot.
  5170. archive.timelapse_baseline = sorted(names) if names is not None else None
  5171. await db.commit()
  5172. except Exception as e:
  5173. # In-memory baseline still covers the normal completion path.
  5174. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5175. async def _scan_for_timelapse_with_retries(
  5176. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5177. ):
  5178. """Poll the printer for this print's timelapse and attach it.
  5179. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5180. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5181. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5182. (#2704). Comparing the current listing against the set of filenames that
  5183. existed when the print started needs no clock at all, because the printer
  5184. writes the video only once the print has ended.
  5185. Baseline precedence: the caller's in-memory set, then the one persisted on
  5186. the archive at print start, then a snapshot taken now. The last of those is
  5187. a poor substitute — by completion the new video may already be on the card,
  5188. in which case it lands in the "baseline" and no diff can ever match — but it
  5189. is all that is available for a print that began before Bambuddy started.
  5190. On success the video is deleted from the printer, which keeps ``/timelapse``
  5191. down to the unclaimed files and makes the next diff unambiguous.
  5192. """
  5193. logger = logging.getLogger(__name__)
  5194. # Cleared when the baseline had to be taken off a card we could not read, so
  5195. # the attach step refuses to choose between several candidates (#2957).
  5196. baseline_trusted = True
  5197. # --- Phase 1: establish the baseline -------------------------------------
  5198. try:
  5199. async with async_session() as db:
  5200. from backend.app.models.printer import Printer
  5201. service = ArchiveService(db)
  5202. archive = await service.get_archive(archive_id)
  5203. if not archive:
  5204. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5205. return
  5206. if archive.timelapse_path:
  5207. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5208. return
  5209. if not archive.printer_id:
  5210. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5211. return
  5212. if baseline_names is not None:
  5213. logger.info(
  5214. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5215. len(baseline_names),
  5216. archive_id,
  5217. )
  5218. elif archive.timelapse_baseline is not None:
  5219. # Persisted at print start — survives a restart mid-print.
  5220. baseline_names = set(archive.timelapse_baseline)
  5221. logger.info(
  5222. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5223. len(baseline_names),
  5224. archive_id,
  5225. )
  5226. else:
  5227. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5228. printer = result.scalar_one_or_none()
  5229. if not printer:
  5230. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5231. return
  5232. if not _timelapse_listing_is_trustworthy(printer):
  5233. # The card is unreadable at the one moment a baseline has to
  5234. # be taken, so the empty listing below means "we never
  5235. # looked", not "these are all new". Carry on with it anyway
  5236. # — the usual card holds exactly one video, which resolves
  5237. # correctly — but stop the poll from *choosing* between
  5238. # several, which is how a stale video got attached to this
  5239. # print and then deleted off the printer (#2957 follow-up).
  5240. baseline_trusted = False
  5241. logger.warning(
  5242. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5243. "handshake cool-off. A single new video still resolves; several will not be "
  5244. "guessed between — use Scan for Timelapse to pick one by hand",
  5245. archive_id,
  5246. archive.printer_id,
  5247. )
  5248. baseline_files, _ = await _list_timelapse_videos(printer)
  5249. baseline_names = {f.get("name", "") for f in baseline_files}
  5250. logger.info(
  5251. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5252. len(baseline_names),
  5253. archive_id,
  5254. )
  5255. except Exception as e:
  5256. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5257. return
  5258. # --- Phase 2: poll for a file that was not there when the print began -----
  5259. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5260. max_attempts = _timelapse_scan_max_attempts()
  5261. seen_names: set[str] = set()
  5262. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5263. attempt = 0
  5264. while True:
  5265. await asyncio.sleep(delay)
  5266. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5267. attempt += 1
  5268. try:
  5269. from backend.app.models.printer import Printer
  5270. # Read phase: fetch archive + printer in a short session and release
  5271. # the pooled connection BEFORE the FTP list/download below. Holding it
  5272. # across the FTP round-trips left one connection idle-in-transaction per
  5273. # in-flight scan (issue #2572).
  5274. async with async_session() as db:
  5275. service = ArchiveService(db)
  5276. archive = await service.get_archive(archive_id)
  5277. if not archive:
  5278. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5279. return
  5280. if archive.timelapse_path:
  5281. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5282. return
  5283. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5284. printer = result.scalar_one_or_none()
  5285. if not printer:
  5286. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5287. return
  5288. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5289. # I/O phase (no DB connection held): FTP list + download.
  5290. video_files, found_path = await _list_timelapse_videos(printer)
  5291. # The poll can run for dozens of rounds, so only narrate a round
  5292. # that saw something change. Repeating the whole listing every 30 s
  5293. # would bury the one interesting line in the support bundle.
  5294. names_now = {f.get("name", "") for f in video_files}
  5295. changed = attempt == 1 or names_now != seen_names
  5296. seen_names = names_now
  5297. speak = logger.info if changed else logger.debug
  5298. if video_files:
  5299. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5300. if changed:
  5301. for f in video_files[:5]:
  5302. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5303. attached = await _attach_first_unclaimed_timelapse(
  5304. archive_id,
  5305. printer,
  5306. video_files,
  5307. baseline_names,
  5308. claimed,
  5309. attempt,
  5310. logger,
  5311. quiet=not changed,
  5312. require_unambiguous=not baseline_trusted,
  5313. plate_id=plate_id,
  5314. )
  5315. if attached:
  5316. return
  5317. else:
  5318. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5319. except Exception as e:
  5320. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5321. if attempt >= max_attempts or time.monotonic() >= deadline:
  5322. break
  5323. # No name-match fallback: it compared the print name against the filename,
  5324. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5325. # bundles it fired 159 times and matched zero times, so all it added was a
  5326. # misleading log line before giving up.
  5327. logger.warning(
  5328. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5329. archive_id,
  5330. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5331. )
  5332. async def _attach_first_unclaimed_timelapse(
  5333. archive_id: int,
  5334. printer,
  5335. video_files: list[dict],
  5336. baseline_names: set[str],
  5337. claimed: set[str],
  5338. attempt: int,
  5339. logger: logging.Logger,
  5340. *,
  5341. quiet: bool = False,
  5342. require_unambiguous: bool = False,
  5343. plate_id: int | None = None,
  5344. ) -> bool:
  5345. """Download and attach the one video that belongs to this print.
  5346. A candidate is any file absent from the print-start baseline. More than one
  5347. can qualify when a previous print's video landed late, after this print's
  5348. baseline was taken — those are filtered out by name, because they are
  5349. already attached to another archive. Sorting the candidates instead would
  5350. mean sorting on mtime or on the filename timestamp, both of which come from
  5351. the printer's unsynced clock.
  5352. Returns True once a video is attached. The printer's copy is deleted only
  5353. after the attach succeeds on bytes whose length matched the listing.
  5354. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5355. already seen this exact listing — the poll runs for many rounds and only the
  5356. rounds where something changed are worth an INFO line.
  5357. """
  5358. from backend.app.services.bambu_ftp import (
  5359. delete_archived_timelapse,
  5360. download_file_bytes_async,
  5361. remote_file_settled,
  5362. )
  5363. speak = logger.debug if quiet else logger.info
  5364. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5365. if not new_files:
  5366. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5367. return False
  5368. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5369. if not candidates:
  5370. speak(
  5371. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5372. attempt,
  5373. len(new_files),
  5374. )
  5375. return False
  5376. if len(candidates) > 1:
  5377. if require_unambiguous:
  5378. # The baseline is not evidence -- it was taken off a card that could
  5379. # not be read -- so "new since the baseline" does not narrow these
  5380. # down at all. Taking the first would attach an arbitrary video to
  5381. # this print and then delete it from the printer.
  5382. logger.warning(
  5383. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5384. "leaving all of them on the printer for manual selection",
  5385. attempt,
  5386. len(candidates),
  5387. ", ".join(str(f.get("name")) for f in candidates),
  5388. )
  5389. return False
  5390. logger.warning(
  5391. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5392. "the rest stay on the printer for manual selection",
  5393. attempt,
  5394. len(candidates),
  5395. ", ".join(str(f.get("name")) for f in candidates),
  5396. )
  5397. target = candidates[0]
  5398. file_name = target.get("name")
  5399. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5400. logger.info(
  5401. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5402. attempt,
  5403. file_name,
  5404. archive_id,
  5405. )
  5406. # The listing always carries a size (`list_files` skips entries it can't
  5407. # parse), but read it explicitly: the delete below is destructive and must
  5408. # depend on a size we actually had, not on one we hoped was there.
  5409. expected_size = target.get("size")
  5410. timelapse_data = await download_file_bytes_async(
  5411. printer.ip_address,
  5412. printer.access_code,
  5413. remote_path,
  5414. printer_model=printer.model,
  5415. expected_size=expected_size,
  5416. )
  5417. if not timelapse_data:
  5418. # Short or failed transfer. The printer keeps its copy, so the next
  5419. # round can try again — which is exactly why the delete below is
  5420. # gated on a verified download.
  5421. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5422. return False
  5423. # The length check above proves we got what the listing said, not that the
  5424. # printer had finished writing. A video still being written can be listed
  5425. # short, served short, and pass — so confirm it has stopped growing before
  5426. # committing to it and deleting the original (#2704).
  5427. if not await remote_file_settled(
  5428. printer.ip_address,
  5429. printer.access_code,
  5430. remote_path,
  5431. len(timelapse_data),
  5432. printer_model=printer.model,
  5433. ):
  5434. return False
  5435. # Write phase: attach in a fresh short-lived session.
  5436. async with async_session() as db:
  5437. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5438. if not success:
  5439. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5440. return False
  5441. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5442. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5443. await delete_archived_timelapse(
  5444. printer.ip_address,
  5445. printer.access_code,
  5446. remote_path,
  5447. verified=expected_size is not None,
  5448. printer_model=printer.model,
  5449. printer_name=printer.name,
  5450. )
  5451. return True
  5452. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5453. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5454. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5455. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5456. # How long the *background* upgrade keeps waiting after the notification has
  5457. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5458. # printer can't hold up the print-complete notification; this one exists so the
  5459. # archive still ends up with the better frame afterwards.
  5460. #
  5461. # Measured across 261 attaches in the support bundles, the video lands a median
  5462. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5463. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5464. # was 546s. Every other model was inside 26s. The long budget is therefore
  5465. # almost entirely for P1-series users; on everything else the short wait already
  5466. # wins and this task never runs.
  5467. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5468. async def _capture_finish_photo_from_timelapse(
  5469. archive_id: int,
  5470. archive_dir: Path,
  5471. timeout: float | None = None,
  5472. rotation: int = 0,
  5473. ) -> tuple[str | None, bool]:
  5474. """Wait for the per-print timelapse to land on the archive and extract its
  5475. last frame as the finish photo (#1397).
  5476. Bambu firmware stops timelapse recording after the toolhead parks but
  5477. before the bed-drop end-gcode runs, so the last frame frames the finished
  5478. print correctly. A live camera grab at gcode_state=FINISH captures the
  5479. bed already lowered.
  5480. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5481. ``archive.timelapse_path`` when the file lands. This function polls for
  5482. that field.
  5483. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5484. the wait ran out with no video on the archive yet — i.e. the video may
  5485. still be coming and a later attempt could succeed. It is False when the
  5486. video landed (whether or not extraction worked), because in that case
  5487. waiting longer changes nothing. The caller uses that to decide between
  5488. falling back permanently and scheduling a background upgrade.
  5489. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5490. still (#2708) so this source agrees with every other finish-photo source.
  5491. The archived video itself is the printer's own file and is left alone —
  5492. rotating it would mean re-encoding it.
  5493. """
  5494. import uuid
  5495. from backend.app.models.archive import PrintArchive
  5496. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5497. logger = logging.getLogger(__name__)
  5498. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5499. deadline = asyncio.get_event_loop().time() + budget
  5500. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5501. while True:
  5502. async with async_session() as db:
  5503. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5504. archive = result.scalar_one_or_none()
  5505. timelapse_relpath = archive.timelapse_path if archive else None
  5506. if timelapse_relpath:
  5507. video_path = app_settings.base_dir / timelapse_relpath
  5508. if video_path.exists() and video_path.stat().st_size > 0:
  5509. photos_dir = archive_dir / "photos"
  5510. photos_dir.mkdir(parents=True, exist_ok=True)
  5511. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5512. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5513. output_path = photos_dir / filename
  5514. if await extract_video_last_frame(video_path, output_path):
  5515. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5516. logger.info(
  5517. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5518. video_path.name,
  5519. archive_id,
  5520. )
  5521. return filename, False
  5522. logger.warning(
  5523. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5524. video_path.name,
  5525. archive_id,
  5526. )
  5527. return None, False
  5528. if asyncio.get_event_loop().time() >= deadline:
  5529. logger.info(
  5530. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5531. archive_id,
  5532. budget,
  5533. )
  5534. return None, True
  5535. await asyncio.sleep(poll_interval)
  5536. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5537. """Add the timelapse's last frame to an archive after the fact (#2704).
  5538. The print-complete notification waits only ~60s for the video, because
  5539. holding a notification for minutes is worse than sending it with a live
  5540. camera grab. On a P1-series printer the video often lands well after that,
  5541. so the archive used to be stuck with the live grab — which is taken at
  5542. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5543. the worse photo of the two.
  5544. This keeps waiting in the background and, when the video arrives, extracts
  5545. the frame and puts it *first* in the archive's photo list, so opening the
  5546. gallery shows it. The live grab is deliberately kept: the notification that
  5547. already went out links to that exact file, and deleting it would leave a
  5548. broken image in Discord or Telegram.
  5549. """
  5550. logger = logging.getLogger(__name__)
  5551. filename, _ = await _capture_finish_photo_from_timelapse(
  5552. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5553. )
  5554. if not filename:
  5555. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5556. return
  5557. try:
  5558. async with async_session() as db:
  5559. from backend.app.models.archive import PrintArchive
  5560. archive = await db.get(PrintArchive, archive_id)
  5561. if archive is None:
  5562. return
  5563. photos = list(archive.photos or [])
  5564. if filename in photos:
  5565. return
  5566. # Front of the list: PhotoGalleryModal opens at index 0.
  5567. archive.photos = [filename, *photos]
  5568. await db.commit()
  5569. except Exception as e:
  5570. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5571. return
  5572. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5573. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5574. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5575. """Put the filament-attribution context back after a restart mid-print.
  5576. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5577. both die with the process. The print keeps running, so at completion the
  5578. tracker would fall back to whatever the printer reports *now* — and AMS
  5579. filament backup makes "now" the substitute tray, charging the whole print
  5580. to the spool that only finished it.
  5581. The persisted row is only trusted when its print name still matches what
  5582. the printer says it is running: a row left behind by a completion we never
  5583. saw must not attach itself to the next print.
  5584. """
  5585. try:
  5586. from backend.app.api.routes.settings import get_setting
  5587. from backend.app.services.usage_tracker import (
  5588. clear_persisted_session,
  5589. get_persisted_print_name,
  5590. restore_session,
  5591. )
  5592. persisted_name = await get_persisted_print_name(db, printer_id)
  5593. current_name = (state.subtask_name or "").strip()
  5594. if persisted_name and current_name and persisted_name.strip() != current_name:
  5595. logger.info(
  5596. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5597. printer_id,
  5598. persisted_name,
  5599. current_name,
  5600. )
  5601. await clear_persisted_session(db, printer_id)
  5602. # Fall through to seeding: the print on the printer is real, it just
  5603. # isn't the one the row described.
  5604. persisted_log = None
  5605. else:
  5606. # Spoolman users get the tray-change log back but no in-memory
  5607. # session — see ``on_print_start`` on why that dict is load-bearing
  5608. # for the remain%-sync guard.
  5609. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5610. persisted_log = await restore_session(
  5611. db,
  5612. printer_id,
  5613. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5614. )
  5615. if persisted_log:
  5616. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5617. # Anything this process already observed goes after the persisted
  5618. # history — the log is ordered by layer, and a fresh process can
  5619. # only have seen changes from later in the print.
  5620. for entry in state.tray_change_log or []:
  5621. if tuple(entry) not in restored:
  5622. restored.append(tuple(entry))
  5623. state.tray_change_log = restored
  5624. tray_now = state.tray_now
  5625. if 0 <= tray_now <= 254:
  5626. if not state.tray_change_log:
  5627. # No persisted history — a print that started before this build,
  5628. # or before the row existed. Seed with the tray feeding right
  5629. # now so the remainder of the print is at least attributable to
  5630. # the right spool.
  5631. state.tray_change_log = [(tray_now, state.layer_num)]
  5632. logger.info(
  5633. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5634. printer_id,
  5635. tray_now,
  5636. state.layer_num,
  5637. )
  5638. # The tray handler updates ``last_loaded_tray`` on every push
  5639. # regardless of whether it logged a change, so re-align it to avoid
  5640. # a duplicate entry on the next push. Only ever with a real tray:
  5641. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5642. # 255" fallback, and writing 255 into it would defeat that.
  5643. state.last_loaded_tray = tray_now
  5644. except Exception:
  5645. # Never let attribution recovery cost the caller its timelapse
  5646. # baseline — that capture has to happen before the printer uploads
  5647. # the in-flight MP4 and there is no second chance at it.
  5648. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5649. async def on_print_running_observed(printer_id: int, data: dict):
  5650. """Restart-recovery for a print that started before Bambuddy came up.
  5651. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5652. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5653. creation). This hook restores the persisted archive into ``_active_prints``
  5654. and captures the timelapse baseline that normally hangs off print start.
  5655. Fires once per session, in lieu of on_print_start when restart-recovery
  5656. kicks in. The printer doesn't upload the timelapse until after PRINT
  5657. COMPLETE, so a baseline captured any time during the print is still
  5658. pre-upload.
  5659. """
  5660. logger = logging.getLogger(__name__)
  5661. async with async_session() as db:
  5662. from backend.app.models.printer import Printer
  5663. state = printer_manager.get_status(printer_id)
  5664. if state is not None:
  5665. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5666. if authorization is True:
  5667. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5668. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5669. await _restore_printable_objects(printer_id, state, db, logger)
  5670. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5671. printer = result.scalar_one_or_none()
  5672. if not printer:
  5673. logger.warning(
  5674. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5675. printer_id,
  5676. )
  5677. return
  5678. # Avoid double-capture: ownership reconciliation above must still run when
  5679. # a baseline already exists, but the camera work itself is one-shot.
  5680. if printer_id in _timelapse_baselines:
  5681. logger.debug(
  5682. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5683. printer_id,
  5684. )
  5685. return
  5686. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5687. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5688. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5689. against the printer's current MQTT state.
  5690. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5691. COMPLETE events, typically a print finishing during an MQTT disconnect
  5692. window followed by a smart-plug power cycle):
  5693. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5694. provably not running anymore — only branch that should fire under
  5695. normal disconnect-then-reconnect timing.
  5696. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5697. firmware mints a fresh ``subtask_id`` for each print, including the
  5698. ghost replay it runs after a power cycle from a leftover SD file —
  5699. so a mismatch unambiguously means the in-DB archive is no longer
  5700. the print on the printer.
  5701. 3. Printer is running but ``subtask_name`` is empty. The printer
  5702. doesn't know what it's running; the archive's reference to it is
  5703. already broken.
  5704. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5705. with matching subtask_id+subtask_name is left alone. The cost of a false
  5706. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5707. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5708. clears on synthesis, so the real completion creates a fresh row instead
  5709. of overwriting the synthesised one (#1679). The cost of a false negative
  5710. is the ghost-print loop in #1542.
  5711. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5712. MQTT has connected but the first ``push_status`` response hasn't been
  5713. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5714. The reconcile caller in ``on_printer_status_change`` is already gated
  5715. on a real ``state.state``, so in normal operation this branch is
  5716. unreachable; it's kept as belt-and-braces for future callers and for
  5717. the narrow window where a partial state update could arrive
  5718. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5719. ``not stale`` on degenerate input is strictly conservative: a real
  5720. stale archive will still be caught by the next push_status arriving
  5721. with terminal state.
  5722. """
  5723. current_state = (state.state or "").upper()
  5724. if current_state in ("", "UNKNOWN"):
  5725. # No real push_status yet — PrinterState defaults are not evidence.
  5726. return False, ""
  5727. if current_state in ("IDLE", "FINISH", "FAILED"):
  5728. return True, f"printer state {current_state}"
  5729. # Below here the printer is in a running / pre-running state (RUNNING /
  5730. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5731. current_subtask_id = (state.subtask_id or "").strip()
  5732. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5733. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5734. current_subtask_name = (state.subtask_name or "").strip()
  5735. if not current_subtask_name:
  5736. return True, "printer subtask_name empty"
  5737. return False, ""
  5738. async def prime_kprofile_table(printer_id: int) -> int:
  5739. """Read the printer's calibration table once per connection.
  5740. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5741. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5742. report ``cali_idx`` and nothing else -- that number can only come from
  5743. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5744. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5745. backup, or the printer answering a query BambuStudio made on the report
  5746. topic we share. A Bambuddy that nobody visited showed a card with no K
  5747. values at all.
  5748. Only the diameters actually fitted are asked for, which is one request on a
  5749. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5750. what the backup does, and it is both wasteful and the thing that used to
  5751. blank the table.
  5752. Returns the number of nozzles whose table was read.
  5753. """
  5754. client = printer_manager.get_client(printer_id)
  5755. state = printer_manager.get_status(printer_id)
  5756. if client is None or state is None or not state.connected:
  5757. return 0
  5758. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5759. # ask once, and both entries are empty until the first push_status lands.
  5760. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5761. if not diameters:
  5762. logging.getLogger(__name__).debug(
  5763. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5764. printer_id,
  5765. )
  5766. return 0
  5767. primed = 0
  5768. for diameter in diameters:
  5769. try:
  5770. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5771. except Exception as exc: # noqa: BLE001
  5772. # A printer that won't answer costs the card its K values, nothing
  5773. # more — never the connection this runs on the back of.
  5774. logging.getLogger(__name__).warning(
  5775. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5776. )
  5777. continue
  5778. primed += 1
  5779. logging.getLogger(__name__).info(
  5780. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5781. )
  5782. return primed
  5783. def _sd_files_in_use(state) -> set[str]:
  5784. """Names of the SD-card files the printer may be printing right now (#3009).
  5785. The post-print cleanup works out what to delete from the finished archive,
  5786. not from the printer. When reconciliation closes an old archive because the
  5787. printer has moved on to a new job, and that job is the same file reprinted
  5788. from the printer's screen, the cleanup would delete the file mid-print.
  5789. Empty unless the printer is busy: on an ordinary completion the state is
  5790. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  5791. name, a path or a URL depending on firmware, and some report only the
  5792. plate's G-code, so the job name is matched as well, in the same spellings
  5793. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  5794. ignores case.
  5795. """
  5796. def _text(value) -> str:
  5797. return value.strip() if isinstance(value, str) else ""
  5798. if state is None:
  5799. return set()
  5800. current_state = _text(getattr(state, "state", None)).upper()
  5801. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  5802. return set()
  5803. in_use: set[str] = set()
  5804. gcode_file = _text(getattr(state, "gcode_file", None))
  5805. if gcode_file:
  5806. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  5807. # both legal in a file name, and raises on some inputs.
  5808. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  5809. if name:
  5810. in_use.add(name.lower())
  5811. subtask_name = _text(getattr(state, "subtask_name", None))
  5812. if subtask_name:
  5813. for name in (subtask_name, subtask_name.replace(" ", "_")):
  5814. for ext in (".3mf", ".gcode"):
  5815. in_use.add(f"{name}{ext}".lower())
  5816. return in_use
  5817. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5818. """Synthesise ``on_print_complete`` for archives whose print can't be
  5819. running on the printer anymore.
  5820. Called once per MQTT (re)connection (from on_printer_status_change when
  5821. the connected edge flips False → True) and at Bambuddy startup (from
  5822. the FastAPI lifespan). Without this, a print that completes during a
  5823. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5824. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5825. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5826. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5827. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5828. closes the loop by faking the missed PRINT COMPLETE — the existing
  5829. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5830. and notifications.
  5831. Synthesised ``status="aborted"`` is the conservative label: we have no
  5832. proof the print finished successfully (and no progress evidence to
  5833. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5834. fires later, overwrites the status with the correct value.
  5835. Returns the number of archives reconciled.
  5836. """
  5837. state = printer_manager.get_status(printer_id)
  5838. if not state:
  5839. return 0
  5840. # Don't reconcile while disconnected — we'd be making a decision against
  5841. # stale cached state. The connected → reconcile edge handles this.
  5842. if not state.connected:
  5843. return 0
  5844. from backend.app.models.archive import PrintArchive
  5845. reconciled = 0
  5846. async with async_session() as db:
  5847. result = await db.execute(
  5848. select(PrintArchive).where(
  5849. PrintArchive.printer_id == printer_id,
  5850. PrintArchive.status == "printing",
  5851. )
  5852. )
  5853. active = list(result.scalars().all())
  5854. if not active:
  5855. return 0
  5856. logger = logging.getLogger(__name__)
  5857. for archive in active:
  5858. is_stale, reason = _is_active_archive_stale(archive, state)
  5859. if not is_stale:
  5860. continue
  5861. logger.info(
  5862. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5863. printer_id,
  5864. archive.id,
  5865. archive.filename,
  5866. reason,
  5867. )
  5868. # Synthesised payload: minimal fields the on_print_complete chain
  5869. # needs. `_reconciled` marker lets downstream code distinguish this
  5870. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5871. # metrics / debug logging). raw_data is the live printer state so
  5872. # the usage tracker can compare end-of-print remain% against the
  5873. # captured start values.
  5874. try:
  5875. await on_print_complete(
  5876. printer_id,
  5877. {
  5878. "status": "aborted",
  5879. "filename": archive.filename,
  5880. "subtask_name": archive.print_name or "",
  5881. "subtask_id": archive.subtask_id or "",
  5882. "raw_data": state.raw_data or {},
  5883. "_reconciled": True,
  5884. },
  5885. )
  5886. reconciled += 1
  5887. except Exception as e:
  5888. # Catch-all: a reconciliation failure must not block the
  5889. # printer's normal status flow. The archive stays in
  5890. # ``status="printing"`` and the next reconnect retries.
  5891. logger.warning(
  5892. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5893. archive.id,
  5894. e,
  5895. )
  5896. return reconciled
  5897. # #2547: clearance left between the nozzle and the top of the print when the
  5898. # plate is commanded back into camera framing. The nozzle is parked away from
  5899. # the part by then, so this is belt-and-braces against a max_z_height that
  5900. # under-reports (e.g. a slicer that excludes a final Z hop).
  5901. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5902. # How far below the restored position to drop the plate again afterwards, so
  5903. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5904. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5905. # on machines with less headroom.
  5906. _PLATE_PARK_DROP_MM = 100.0
  5907. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5908. # this axis, so it is a proven-safe speed for the full travel.
  5909. _PLATE_RESTORE_FEEDRATE = 600
  5910. # Time allowed for the plate to reach the restored position before the camera
  5911. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5912. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5913. # How long `_background_finish_photo` waits for this producer. Must cover the
  5914. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5915. # notification path's own photo wait so a slow producer degrades to a
  5916. # photo-less notification rather than a missed one. The chamber light's
  5917. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  5918. # camera_light.MAX_DELAY_SECONDS stays below it.
  5919. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5920. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  5921. """The ``_active_prints`` keys a finished print may be registered under.
  5922. Matching how they were registered in on_print_start. Shared by
  5923. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  5924. to find the same binding.
  5925. """
  5926. possible_keys = []
  5927. # Try subtask_name variations first (most reliable for matching)
  5928. if subtask_name:
  5929. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5930. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5931. possible_keys.append((printer_id, subtask_name))
  5932. # Try filename variations
  5933. if filename:
  5934. # Extract just the filename if it's a path
  5935. fname = filename.split("/")[-1] if "/" in filename else filename
  5936. if fname.endswith(".3mf"):
  5937. possible_keys.append((printer_id, fname))
  5938. elif fname.endswith(".gcode"):
  5939. base_name = fname.rsplit(".", 1)[0]
  5940. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5941. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5942. possible_keys.append((printer_id, fname))
  5943. else:
  5944. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5945. possible_keys.append((printer_id, f"{fname}.3mf"))
  5946. possible_keys.append((printer_id, fname))
  5947. # Also try full path versions
  5948. if filename.endswith(".3mf"):
  5949. possible_keys.append((printer_id, filename))
  5950. elif filename.endswith(".gcode"):
  5951. base_name = filename.rsplit(".", 1)[0]
  5952. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5953. possible_keys.append((printer_id, filename))
  5954. else:
  5955. possible_keys.append((printer_id, f"{filename}.3mf"))
  5956. possible_keys.append((printer_id, filename))
  5957. return possible_keys
  5958. def _archive_name_forms(archive) -> set[str]:
  5959. """The names an archive could be echoed back as, in normalised form (#3240).
  5960. Its print name, and its filename with and without the 3MF extension.
  5961. """
  5962. forms = set()
  5963. if archive.print_name:
  5964. forms.add(_normalise_subtask_name(archive.print_name))
  5965. if archive.filename:
  5966. forms.add(_normalise_subtask_name(archive.filename))
  5967. for suffix in (".gcode.3mf", ".3mf"):
  5968. if archive.filename.lower().endswith(suffix):
  5969. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  5970. forms.discard("")
  5971. return forms
  5972. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  5973. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  5974. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  5975. from the plate recorded when the job was dispatched. Neither is touched:
  5976. ``on_print_complete`` pops both, which is why the finish-photo producer
  5977. calls this before its first await, while they are still there.
  5978. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  5979. archive, or that it only knows by a name -- and on any error: the producer
  5980. calls this before the ``try`` that always releases the photo consumer, so
  5981. it must not raise.
  5982. """
  5983. try:
  5984. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  5985. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  5986. if archive_id is None:
  5987. return None, None
  5988. return archive_id, _print_plate_ids.get(archive_id)
  5989. except Exception:
  5990. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  5991. return None, None
  5992. async def _max_z_for_current_print(
  5993. printer_id: int,
  5994. data: dict,
  5995. logger,
  5996. archive_id: int | None,
  5997. plate_id: int | None = None,
  5998. ) -> float | None:
  5999. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6000. This number becomes the target of a real Z move, so every step here refuses
  6001. rather than guesses. A height belonging to some *other* print is the one
  6002. failure that could drive the nozzle into the model: 20 mm carried onto a
  6003. 200 mm print would command the plate up through the part.
  6004. Three independent things therefore have to agree before a height is
  6005. returned:
  6006. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6007. when it started (see ``_bound_print``), never one found by name. A name
  6008. is not an identity: every plate of a multi-plate file shares one, and a
  6009. reprint reuses its archive row, so the newest archive with the right
  6010. name can be another plate of the same file. Support bundles show the
  6011. old name lookup doing exactly that (archive 288 for a print bound to
  6012. 169, 313 layers against 125), stopped only by the layer check below.
  6013. No binding, no move.
  6014. 2. **Identity.** The bound archive's name still has to be the finished
  6015. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6016. because the printer echoes spaces as underscores (#3240). Exact: not a
  6017. substring, and not the completion check's tolerance for a truncated
  6018. echo.
  6019. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6020. match the layer count the printer itself reported over MQTT for the print
  6021. that just ended. These come from genuinely different sources, so a
  6022. mismatch means the row is not this print, whatever its name says.
  6023. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6024. plate of a multi-plate file reuses the archive row without updating its
  6025. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6026. ``on_print_complete`` may already have flipped the status by the time we
  6027. run.
  6028. """
  6029. subtask_name = (data.get("subtask_name") or "").strip()
  6030. if not subtask_name:
  6031. # Nothing to identify the print by — refuse rather than fall back to
  6032. # "whatever ran last on this printer".
  6033. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6034. return None
  6035. if archive_id is None:
  6036. logger.info(
  6037. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6038. printer_id,
  6039. subtask_name,
  6040. )
  6041. return None
  6042. try:
  6043. from backend.app.models.archive import PrintArchive
  6044. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6045. async with async_session() as db:
  6046. result = await db.execute(
  6047. select(PrintArchive).where(
  6048. PrintArchive.id == archive_id,
  6049. PrintArchive.printer_id == printer_id,
  6050. PrintArchive.status.in_(("printing", "completed")),
  6051. PrintArchive.deleted_at.is_(None),
  6052. )
  6053. )
  6054. archive = result.scalar_one_or_none()
  6055. if archive is None or not archive.file_path:
  6056. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6057. return None
  6058. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6059. logger.warning(
  6060. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6061. printer_id,
  6062. archive_id,
  6063. subtask_name,
  6064. )
  6065. return None
  6066. client = printer_manager.get_client(printer_id)
  6067. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6068. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6069. logger.warning(
  6070. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6071. "— refusing to move the plate on a height that may not be this print's",
  6072. printer_id,
  6073. archive.id,
  6074. archive.total_layers,
  6075. reported_layers,
  6076. )
  6077. return None
  6078. # Stored relative to the data directory, like every other archive path
  6079. # (#3240: this read a `data_dir` setting that does not exist).
  6080. path = app_settings.base_dir / archive.file_path
  6081. plate = plate_id or archive.plate_id or 1
  6082. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6083. except Exception as e:
  6084. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6085. return None
  6086. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6087. """Raise the plate back into camera framing before the finish photo (#2547).
  6088. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6089. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6090. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6091. This commands an absolute ``G1 Z`` back to just above the last printed
  6092. layer.
  6093. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6094. clearance`` is a height the toolhead was physically at seconds earlier, so
  6095. it is inside the travel limits by construction and leaves the nozzle above
  6096. the part. It is also unambiguous across model families: Z is the
  6097. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6098. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6099. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6100. (#2579).
  6101. Returns True if the move was sent and waited out, False if it was skipped.
  6102. """
  6103. client = printer_manager.get_client(printer_id)
  6104. if client is None:
  6105. return False
  6106. # Re-read state immediately before commanding motion. If the queue has
  6107. # already started the next print, the printer is no longer ours to move.
  6108. state = getattr(client, "state", None)
  6109. if state is None or state.state != "FINISH":
  6110. logger.info(
  6111. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6112. printer_id,
  6113. getattr(state, "state", "unknown"),
  6114. )
  6115. return False
  6116. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6117. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6118. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6119. return False
  6120. logger.info(
  6121. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6122. printer_id,
  6123. target_z,
  6124. max_z_height,
  6125. _PLATE_RESTORE_CLEARANCE_MM,
  6126. _PLATE_RESTORE_SETTLE_SECONDS,
  6127. )
  6128. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6129. return True
  6130. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6131. """Drop the plate again after the finish photo (#2547).
  6132. Without this the user walks up to a finished print sitting just under the
  6133. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6134. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6135. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6136. print homes anyway.
  6137. """
  6138. client = printer_manager.get_client(printer_id)
  6139. state = getattr(client, "state", None) if client else None
  6140. if client is None or state is None or state.state != "FINISH":
  6141. return
  6142. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6143. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6144. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6145. """True if a queue item is about to take this printer (#2547).
  6146. The scheduler dispatches the next job the moment a print completes, and a
  6147. plate move interleaved with a print start is not a race worth having. The
  6148. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6149. this window; this closes the head of it.
  6150. """
  6151. try:
  6152. from backend.app.models.print_queue import PrintQueueItem
  6153. async with async_session() as db:
  6154. result = await db.execute(
  6155. select(PrintQueueItem.id)
  6156. .where(
  6157. PrintQueueItem.printer_id == printer_id,
  6158. PrintQueueItem.status.in_(("pending", "printing")),
  6159. )
  6160. .limit(1)
  6161. )
  6162. return result.scalar_one_or_none() is not None
  6163. except Exception as e:
  6164. # Fail closed: if we can't tell, don't move the plate.
  6165. logging.getLogger(__name__).debug(
  6166. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6167. )
  6168. return True
  6169. async def on_finish_photo_moment(printer_id: int, data: dict):
  6170. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6171. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6172. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6173. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6174. HMS halt, firmware variants). Grabs one frame via the same
  6175. external-camera / RTSP path the post-completion fallback uses, stores
  6176. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6177. ``_background_finish_photo`` consume the cached bytes when it runs.
  6178. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6179. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6180. set to Smooth (#1721). No force-on now means the user's explicit
  6181. timelapse=off in the slicer send dialog is respected.
  6182. """
  6183. logger = logging.getLogger(__name__)
  6184. trigger = data.get("trigger", "unknown")
  6185. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6186. logger.info(
  6187. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6188. printer_id,
  6189. trigger,
  6190. timelapse_was_active,
  6191. )
  6192. # If a timelapse is actively recording, skip the pre-capture — the
  6193. # post-completion path will extract the last frame from the recorded
  6194. # video, which still provides the best framing (toolhead parked,
  6195. # before bed drop) without the per-layer parking side effects.
  6196. if timelapse_was_active:
  6197. logger.info(
  6198. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6199. printer_id,
  6200. )
  6201. return
  6202. # #1790: register the producer-done event BEFORE the first await so the
  6203. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6204. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6205. # The `finally` below guarantees `set()` runs on every exit, including
  6206. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6207. producer_done = asyncio.Event()
  6208. _stage22_finish_in_flight[printer_id] = producer_done
  6209. # #3240: also before the first await. On the FINISH-state path
  6210. # `on_print_complete` is dispatched right behind us and pops both the
  6211. # print's archive binding and its plate; read here, they are still there.
  6212. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6213. # #2547: set once the plate has actually been raised, and read by the
  6214. # `finally` below. Declared out here so a failure anywhere after the move —
  6215. # a camera timeout, a DB error — still lowers the plate again.
  6216. restore_max_z: float | None = None
  6217. try:
  6218. async with async_session() as db:
  6219. from backend.app.api.routes.settings import get_setting
  6220. from backend.app.models.printer import Printer
  6221. capture_setting = await get_setting(db, "capture_finish_photo")
  6222. if capture_setting is not None and capture_setting.lower() != "true":
  6223. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6224. return
  6225. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6226. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6227. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6228. printer = result.scalar_one_or_none()
  6229. if printer is None:
  6230. logger.warning(
  6231. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6232. printer_id,
  6233. )
  6234. return
  6235. frame_bytes: bytes | None = None
  6236. # #2708: the banked frame arrives already rotated — it comes from
  6237. # `_capture_snapshot_for_notification`, which rotates before returning.
  6238. # Every other source below is a raw grab. Tracking which lets us store
  6239. # exactly one rotation in `_stage22_finish_frames` either way.
  6240. frame_already_rotated = False
  6241. # On the FINISH-state path the End G-code has already run, and two very
  6242. # different situations arrive here needing opposite answers.
  6243. #
  6244. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6245. # snippet may have ejected the plate — the scene in front of the camera
  6246. # is no longer the finished print, and no amount of moving the plate
  6247. # brings it back. Use the banked in-print frame instead.
  6248. #
  6249. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6250. # than the camera frames well, and the toolhead is parked out of the
  6251. # way. That is the *best* moment available on firmware that never emits
  6252. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6253. # back. Preferring the bank here unconditionally, as this code used to,
  6254. # is what shipped a mid-print photo with the toolhead over the part.
  6255. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6256. banked = _inprint_frame_bank.get(printer_id)
  6257. if banked:
  6258. frame_bytes = banked
  6259. frame_already_rotated = True
  6260. logger.info(
  6261. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6262. "frame (%d bytes) instead of a post-swap live grab",
  6263. len(banked),
  6264. )
  6265. else:
  6266. logger.warning(
  6267. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6268. "in-print bank is empty — falling back to a live grab, which may show a "
  6269. "swapped or empty plate",
  6270. printer_id,
  6271. )
  6272. # `restore_max_z` is set only once the plate is actually up, because the
  6273. # `finally` reads it to decide whether it owes a move back down.
  6274. #
  6275. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6276. # came up empty above: that machine may have just ejected its plate, and
  6277. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6278. # taking for a photo of a bed we already know may be bare.
  6279. if (
  6280. frame_bytes is None
  6281. and trigger == "finish_state"
  6282. and restore_plate_enabled
  6283. and not print_dispatch_context.end_gcode_injected(printer_id)
  6284. ):
  6285. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6286. if wants_restore is None:
  6287. logger.info(
  6288. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6289. printer_id,
  6290. )
  6291. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6292. logger.info(
  6293. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6294. printer_id,
  6295. )
  6296. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6297. restore_max_z = wants_restore
  6298. # Chamber light for the live capture below (#1655). The banked frame
  6299. # above was taken without it, like every in-print bank.
  6300. async with camera_light(printer if frame_bytes is None else None):
  6301. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6302. from backend.app.api.routes.camera import live_frame_for_capture
  6303. from backend.app.services.external_camera import capture_frame
  6304. # #2707: this used to collide with the live view and fail, which is
  6305. # how finish-photo notifications went out with no image attached.
  6306. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6307. defer, buffered = live_frame_for_capture(printer_id)
  6308. if defer:
  6309. frame_bytes = buffered
  6310. else:
  6311. frame_bytes = await capture_frame(
  6312. printer.external_camera_url,
  6313. printer.external_camera_type or "mjpeg",
  6314. snapshot_url=printer.external_camera_snapshot_url,
  6315. )
  6316. if frame_bytes:
  6317. logger.info(
  6318. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6319. len(frame_bytes),
  6320. )
  6321. elif frame_bytes is None:
  6322. from backend.app.api.routes.camera import get_buffered_frame
  6323. buffered = get_buffered_frame(printer_id)
  6324. if buffered:
  6325. frame_bytes = buffered
  6326. logger.info(
  6327. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6328. len(frame_bytes),
  6329. )
  6330. else:
  6331. from backend.app.services.camera import capture_camera_frame_bytes
  6332. frame_bytes = await capture_camera_frame_bytes(
  6333. ip_address=printer.ip_address,
  6334. access_code=printer.access_code,
  6335. model=printer.model,
  6336. timeout=15,
  6337. )
  6338. if frame_bytes:
  6339. logger.info(
  6340. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6341. len(frame_bytes),
  6342. )
  6343. if frame_bytes:
  6344. if not frame_already_rotated:
  6345. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6346. _stage22_finish_frames[printer_id] = frame_bytes
  6347. else:
  6348. logger.warning(
  6349. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6350. printer_id,
  6351. )
  6352. except Exception as e:
  6353. logger.warning(
  6354. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6355. printer_id,
  6356. e,
  6357. )
  6358. finally:
  6359. # #2547: we raised the plate, so we own lowering it — including when the
  6360. # capture above failed or threw partway through.
  6361. if restore_max_z is not None:
  6362. try:
  6363. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6364. except Exception as e:
  6365. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6366. # #1790: always unblock the consumer's bounded wait — whether we stored
  6367. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6368. # dict entry by the consumer doesn't affect signalling.
  6369. producer_done.set()
  6370. def _subtask_name_from_filename(filename: str) -> str:
  6371. """Recover the subtask name a print command would have carried for *filename*.
  6372. The dispatcher derives the printer-facing subtask name from the archive's
  6373. file name, so stripping the extensions back off gives the value MQTT echoes
  6374. on completion. Only the two extensions Bambuddy actually stores are removed,
  6375. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6376. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6377. """
  6378. name = PurePosixPath(filename).name
  6379. for suffix in (".3mf", ".gcode"):
  6380. if name.lower().endswith(suffix):
  6381. name = name[: -len(suffix)]
  6382. return name
  6383. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6384. """Whether the subtask name is the printed 3MF's own file name.
  6385. A print started from the printer's screen reports the same full name, with
  6386. its extension, as both subtask and file (#3009). A dispatched print reports
  6387. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6388. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6389. """
  6390. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6391. return False
  6392. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6393. # How the printer marks a subtask name it had to cut short. Observed on real
  6394. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6395. # (a name with multibyte characters came back at 98), so match the marker
  6396. # rather than a length.
  6397. _SUBTASK_TRUNCATION_MARKER = "..."
  6398. def _normalise_subtask_name(name: str) -> str:
  6399. """Canonical form for comparing a dispatched name against MQTT's echo.
  6400. The printer does not echo the name back verbatim: it substitutes
  6401. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6402. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6403. The 3MF lookup in this module has always known that -- it builds
  6404. space-to-underscore variants of every candidate filename, and its
  6405. directory search normalises both sides before comparing. This exists so
  6406. the completion check reads the same rule from the same place instead of
  6407. growing its own, which is exactly how it came to disagree (#2829).
  6408. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6409. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6410. are dropped after the substitution so both sides agree (#3241).
  6411. """
  6412. return name.strip().replace(" ", "_").strip("_").casefold()
  6413. def _subtask_names_match(expected: str, observed: str) -> bool:
  6414. """Whether two subtask names describe the same print.
  6415. Beyond the space/underscore substitution, the printer truncates long names
  6416. and marks the cut with ``...``. A truncated echo has to count as a match or
  6417. every print with a long name strands its queue item the same way.
  6418. """
  6419. expected_n = _normalise_subtask_name(expected)
  6420. observed_n = _normalise_subtask_name(observed)
  6421. if expected_n == observed_n:
  6422. return True
  6423. # Either side can be the truncated one: the printer truncates what it
  6424. # echoes, and an archive whose own filename was recorded from a previous
  6425. # truncated echo carries the marker too.
  6426. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6427. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6428. continue
  6429. # The full side has lost its edge underscores; a cut that lands right
  6430. # after one keeps it, so drop it here too (#3241). Nothing left before
  6431. # the marker is no evidence of anything, and must not match every name.
  6432. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6433. if kept and full.startswith(kept):
  6434. return True
  6435. return False
  6436. async def _queue_item_dispatched_name(db, item) -> str:
  6437. """The subtask name *item* was dispatched under, or "" when unknowable.
  6438. A row with no archive, or an archive with no file name, is unverifiable
  6439. rather than wrong; every caller answers that with its permissive branch.
  6440. """
  6441. if item.archive_id is None:
  6442. return ""
  6443. from backend.app.models.archive import PrintArchive
  6444. archive = await db.get(PrintArchive, item.archive_id)
  6445. if archive is None or not archive.filename:
  6446. return ""
  6447. return _subtask_name_from_filename(archive.filename)
  6448. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6449. """Whether this completion event is plausibly about *item*'s print.
  6450. The caller finds its queue row by printer and ``status='printing'`` alone,
  6451. which is all a completion event gives it -- there is no run identifier in
  6452. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6453. completion delivered for this printer closes whichever row happens to be
  6454. printing, however unrelated. Comparing the subtask name against the archive
  6455. the row was dispatched with costs one primary-key load and rules that out.
  6456. Deliberately permissive: it answers False only on a positive disagreement
  6457. between two names we actually have. A row with no archive, an archive with
  6458. no file name, or an event with no subtask name is unverifiable rather than
  6459. wrong, and refusing those would strand the item in ``printing`` and wedge
  6460. the printer's queue -- a worse failure than the one being prevented.
  6461. """
  6462. observed = (data.get("subtask_name") or "").strip()
  6463. if not observed or item.archive_id is None:
  6464. return True
  6465. from backend.app.models.archive import PrintArchive
  6466. archive = await db.get(PrintArchive, item.archive_id)
  6467. if archive is None or not archive.filename:
  6468. return True
  6469. expected = _subtask_name_from_filename(archive.filename)
  6470. if not expected or _subtask_names_match(expected, observed):
  6471. return True
  6472. logging.getLogger(__name__).warning(
  6473. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6474. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6475. "printing rather than closing a run this event is not about.",
  6476. item.id,
  6477. expected,
  6478. archive.id,
  6479. archive.filename,
  6480. observed,
  6481. )
  6482. return False
  6483. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6484. """Spend the 3MF download cache on a still-empty fallback archive.
  6485. ``on_print_complete`` drops the cache as its first act, which deletes the
  6486. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6487. print ran and the archive never got one, this is the last moment those bytes
  6488. exist (#2957).
  6489. """
  6490. logger = logging.getLogger(__name__)
  6491. names = [
  6492. n
  6493. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6494. if n
  6495. ]
  6496. for name in names:
  6497. try:
  6498. cached = get_cached_3mf(printer_id, name)
  6499. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6500. return
  6501. except Exception as e:
  6502. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6503. async def _cleanup_sd_card_after_print(
  6504. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6505. ) -> None:
  6506. """Delete a finished print's file from the printer's SD card."""
  6507. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6508. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6509. # auto-start files found in root on power cycle, causing ghost prints.
  6510. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6511. try:
  6512. if subtask_name:
  6513. archive_filename: str | None = None
  6514. async with async_session() as db:
  6515. from backend.app.models.archive import PrintArchive
  6516. from backend.app.models.printer import Printer
  6517. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6518. printer = result.scalar_one_or_none()
  6519. if archive_id:
  6520. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6521. archive_filename = archive_row.scalar_one_or_none()
  6522. if printer:
  6523. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6524. from backend.app.utils.filename import derive_remote_filename
  6525. # Primary candidate: the exact path the dispatcher uploaded to
  6526. # (derived from archive.filename via the same rule as upload).
  6527. # Without it, a library row that ended up with a doubled
  6528. # .gcode.3mf (#1542) leaves the real file behind because the
  6529. # subtask_name + ext fallbacks below don't match what's on the
  6530. # SD card. Fallbacks remain for archive-less prints (subtask
  6531. # never resolved to an archive) and for older naming variants.
  6532. candidate_paths: list[str] = []
  6533. if archive_filename:
  6534. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6535. for ext in (".3mf", ".gcode"):
  6536. fallback = f"/{subtask_name}{ext}"
  6537. if fallback not in candidate_paths:
  6538. candidate_paths.append(fallback)
  6539. # Three outcomes track across all candidates so the final log
  6540. # line reflects what actually happened. The A1 in #1721 always
  6541. # ends here with ``any_not_found=True`` and the others False
  6542. # — its firmware auto-cleans the SD card before our cleanup
  6543. # runs, every candidate FTP-DELE returns 550, and the old
  6544. # code burned 3 retries × 2 s × 3 candidates per print
  6545. # logging a misleading "may linger" WARNING on a successful
  6546. # print.
  6547. any_deleted = False
  6548. any_real_failure = False
  6549. any_not_found = False
  6550. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6551. for remote_path in candidate_paths:
  6552. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6553. logger.info(
  6554. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6555. remote_path,
  6556. printer.name,
  6557. )
  6558. continue
  6559. # Retry only the FAILED case — 550 NOT_FOUND will never
  6560. # recover by waiting, so a "file isn't here" answer
  6561. # advances immediately to the next candidate without
  6562. # consuming the retry budget.
  6563. for attempt in range(1, 4):
  6564. try:
  6565. delete_result = await delete_file_async(
  6566. printer.ip_address,
  6567. printer.access_code,
  6568. remote_path,
  6569. printer_model=printer.model,
  6570. )
  6571. except Exception as e:
  6572. delete_result = DeleteResult.FAILED
  6573. logger.warning(
  6574. "SD card cleanup attempt %d/3 raised for %s: %s",
  6575. attempt,
  6576. remote_path,
  6577. e,
  6578. )
  6579. if delete_result == DeleteResult.DELETED:
  6580. any_deleted = True
  6581. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6582. break
  6583. if delete_result == DeleteResult.NOT_FOUND:
  6584. any_not_found = True
  6585. break # 550 will not recover; try next candidate
  6586. # FAILED: real error — retry with backoff, then give up
  6587. if attempt < 3:
  6588. await asyncio.sleep(2)
  6589. else:
  6590. any_real_failure = True
  6591. logger.warning(
  6592. "SD card cleanup failed after 3 attempts for %s "
  6593. "(network/auth/transient error — file may linger on SD card)",
  6594. remote_path,
  6595. )
  6596. if not any_deleted and not any_real_failure and any_not_found:
  6597. # Every candidate said "not here." Either the printer
  6598. # firmware swept the SD card itself (common on A1) or the
  6599. # dispatcher's upload path doesn't match our candidate
  6600. # rule. Either way: nothing to clean up, no warning.
  6601. logger.debug(
  6602. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6603. "(printer likely self-cleaned)",
  6604. printer.name,
  6605. )
  6606. except Exception as e:
  6607. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6608. async def on_print_complete(printer_id: int, data: dict):
  6609. """Handle print completion - update the archive status."""
  6610. import time
  6611. logger = logging.getLogger(__name__)
  6612. start_time = time.time()
  6613. def log_timing(section: str):
  6614. elapsed = time.time() - start_time
  6615. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6616. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6617. # A kill-switch stop sends its provider notification immediately. Keep the
  6618. # task so the later notification path can await it and avoid a duplicate;
  6619. # if that immediate attempt failed, the regular completion path retries.
  6620. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6621. # Last chance before the bytes go: if this print's archive is still an empty
  6622. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6623. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6624. # below deletes the file (#2957).
  6625. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6626. # A pending cool-off retry has nothing left to recover for — the cache is
  6627. # about to be dropped and the print is over.
  6628. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6629. if retry_task and not retry_task.done():
  6630. retry_task.cancel()
  6631. # Drop the 3MF download cache for this printer (#972). The print is over,
  6632. # nothing else legitimately needs the bytes; keeping them would only risk
  6633. # handing a stale file to the next print if it reuses the same name.
  6634. clear_3mf_cache(printer_id)
  6635. try:
  6636. ws_data = {
  6637. "status": data.get("status"),
  6638. "filename": data.get("filename"),
  6639. "subtask_name": data.get("subtask_name"),
  6640. "timelapse_was_active": data.get("timelapse_was_active"),
  6641. }
  6642. await ws_manager.send_print_complete(printer_id, ws_data)
  6643. log_timing("WebSocket send_print_complete")
  6644. except Exception as e:
  6645. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6646. # Capture user info before clearing (needed for print log entry)
  6647. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6648. # Clear current print user tracking (Issue #206)
  6649. printer_manager.clear_current_print_user(printer_id)
  6650. # If the user explicitly stopped this print from the queue UI the printer will
  6651. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6652. # correct "print stopped" notification/email is sent instead of a failure alert.
  6653. _raw_status = data.get("status", "completed")
  6654. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6655. logger.info(
  6656. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6657. _raw_status,
  6658. printer_id,
  6659. )
  6660. data = {**data, "status": "cancelled"}
  6661. _user_stopped_printers.discard(printer_id)
  6662. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6663. # may have left material on the bed: a user can cancel ten hours into a
  6664. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6665. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6666. # `_user_stopped_printers` is only populated when the user stops via the
  6667. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6668. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6669. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6670. # Auto Off power cycles and Bambuddy restarts.
  6671. try:
  6672. notify_live_activities.print_finished(printer_id, data)
  6673. except Exception:
  6674. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  6675. _final_status = data.get("status", "completed")
  6676. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6677. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6678. # MQTT relay - publish print complete
  6679. try:
  6680. printer_info = printer_manager.get_printer(printer_id)
  6681. if printer_info:
  6682. await mqtt_relay.on_print_complete(
  6683. printer_id,
  6684. printer_info.name,
  6685. printer_info.serial_number,
  6686. data.get("filename", ""),
  6687. data.get("subtask_name", ""),
  6688. data.get("status", "completed"),
  6689. )
  6690. except Exception:
  6691. pass # Don't fail print complete callback if MQTT fails
  6692. filename = data.get("filename", "")
  6693. subtask_name = data.get("subtask_name", "")
  6694. if not filename and not subtask_name:
  6695. logger.warning("Print complete without filename or subtask_name")
  6696. return
  6697. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6698. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6699. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6700. # Find the archive for this print
  6701. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6702. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6703. archive_id = None
  6704. for key in possible_keys:
  6705. archive_id = _active_prints.pop(key, None)
  6706. if archive_id:
  6707. logger.info("Found archive %s with key %s", archive_id, key)
  6708. # Also clean up any other keys pointing to this archive
  6709. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6710. for k in keys_to_remove:
  6711. _active_prints.pop(k, None)
  6712. break
  6713. # The archive bound when the print started, before the name search below.
  6714. # Only this one may give the finish-photo plate restore a height (#3240):
  6715. # the search matches names by substring.
  6716. bound_archive_id = archive_id
  6717. if not archive_id:
  6718. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6719. async with async_session() as db:
  6720. from backend.app.models.archive import PrintArchive
  6721. # Try matching by subtask_name (stored as print_name) first
  6722. if subtask_name:
  6723. result = await db.execute(
  6724. select(PrintArchive)
  6725. .where(PrintArchive.printer_id == printer_id)
  6726. .where(PrintArchive.status == "printing")
  6727. .where(
  6728. or_(
  6729. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6730. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6731. )
  6732. )
  6733. .order_by(PrintArchive.created_at.desc())
  6734. .limit(1)
  6735. )
  6736. archive = result.scalar_one_or_none()
  6737. if archive:
  6738. archive_id = archive.id
  6739. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6740. # Also try by filename
  6741. if not archive_id and filename:
  6742. result = await db.execute(
  6743. select(PrintArchive)
  6744. .where(PrintArchive.printer_id == printer_id)
  6745. .where(PrintArchive.filename == filename)
  6746. .where(PrintArchive.status == "printing")
  6747. .order_by(PrintArchive.created_at.desc())
  6748. .limit(1)
  6749. )
  6750. archive = result.scalar_one_or_none()
  6751. if archive:
  6752. archive_id = archive.id
  6753. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6754. log_timing("SD card cleanup")
  6755. # Update queue item status early — must run before the archive_id early-return
  6756. # so queue items don't get stuck in "printing" when archive lookup fails.
  6757. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6758. queue_item_id = None
  6759. billing_run_id: str | None = None
  6760. billing_user_id: int | None = None
  6761. billing_cost_center_id: int | None = None
  6762. billing_plate_id: int | None = None
  6763. queue_status = None
  6764. queue_auto_off = False
  6765. try:
  6766. from backend.app.core.database import run_with_retry
  6767. from backend.app.models.print_queue import PrintQueueItem
  6768. async def _update_queue_status(db):
  6769. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6770. nonlocal queue_item_id, queue_status, queue_auto_off
  6771. result = await db.execute(
  6772. select(PrintQueueItem)
  6773. .where(PrintQueueItem.printer_id == printer_id)
  6774. .where(PrintQueueItem.status == "printing")
  6775. )
  6776. printing_items = list(result.scalars().all())
  6777. if len(printing_items) > 1:
  6778. logger.warning(
  6779. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6780. printer_id,
  6781. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6782. )
  6783. item = printing_items[0] if printing_items else None
  6784. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6785. return
  6786. if item:
  6787. queue_status = data.get("status", "completed")
  6788. # MQTT sends "aborted" for cancelled prints; normalise to
  6789. # "cancelled" so it matches the queue schema Literal.
  6790. if queue_status == "aborted":
  6791. queue_status = "cancelled"
  6792. item.status = queue_status
  6793. item.completed_at = datetime.now(timezone.utc)
  6794. if queue_status == "failed" and not item.error_message:
  6795. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6796. # Bump usage counters on the source library file so admins can
  6797. # sort by "last printed" and (eventually) auto-purge stale
  6798. # files — #1008.
  6799. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6800. await db.commit()
  6801. queue_item_id = item.id
  6802. billing_run_id = item.billing_run_id
  6803. billing_user_id = item.created_by_id
  6804. billing_cost_center_id = item.cost_center_id
  6805. billing_plate_id = item.plate_id
  6806. queue_auto_off = item.auto_off_after
  6807. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6808. await run_with_retry(_update_queue_status, label="queue status update")
  6809. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6810. # their own sessions and have their own error handling — no retry needed.
  6811. if queue_item_id is not None:
  6812. # Batch orders (#342): this run may have been the last one an order
  6813. # owed. Re-evaluate here rather than lazily on read, so a finished
  6814. # order reports itself complete without someone opening the page.
  6815. try:
  6816. from backend.app.services.print_batch import refresh_batch_status_for_item
  6817. async with async_session() as db:
  6818. await refresh_batch_status_for_item(db, queue_item_id)
  6819. await db.commit()
  6820. except Exception as e:
  6821. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6822. # MQTT relay - publish queue job completed
  6823. try:
  6824. printer_info = printer_manager.get_printer(printer_id)
  6825. await mqtt_relay.on_queue_job_completed(
  6826. job_id=queue_item_id,
  6827. filename=filename or subtask_name,
  6828. printer_id=printer_id,
  6829. printer_name=printer_info.name if printer_info else "Unknown",
  6830. status=queue_status,
  6831. )
  6832. except Exception:
  6833. pass # Don't fail if MQTT fails
  6834. # Check if queue is now empty and send notification
  6835. try:
  6836. from sqlalchemy import func as sa_func
  6837. async with async_session() as db:
  6838. count_result = await db.execute(
  6839. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6840. )
  6841. pending_count = count_result.scalar() or 0
  6842. if pending_count == 0:
  6843. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6844. completed_result = await db.execute(
  6845. select(sa_func.count(PrintQueueItem.id)).where(
  6846. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6847. PrintQueueItem.completed_at >= today_start,
  6848. )
  6849. )
  6850. completed_count = completed_result.scalar() or 1
  6851. await notification_service.on_queue_completed(
  6852. completed_count=completed_count,
  6853. db=db,
  6854. )
  6855. except Exception:
  6856. pass # Don't fail if notification fails
  6857. # Handle auto_off_after - power off printer if the queue item opted
  6858. # in. Delegates to the smart-plug manager so the off honours each
  6859. # plug's configured strategy (time delay or temperature threshold),
  6860. # is cancelled if the printer starts printing again, and never cuts
  6861. # power on a loaded print (#1890). Previously an inline block here
  6862. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6863. # timeout regardless of print state — cutting a touchscreen reprint.
  6864. if queue_auto_off:
  6865. try:
  6866. async with async_session() as db:
  6867. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6868. except Exception as e:
  6869. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6870. except Exception as e:
  6871. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6872. log_timing("Queue item update")
  6873. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6874. # Must run before archive_id early-return so it fires for all prints (including
  6875. # prints started from BambuStudio/touchscreen that have no archive).
  6876. if data.get("status") == "completed":
  6877. try:
  6878. from backend.app.api.routes.settings import get_setting
  6879. async with async_session() as db:
  6880. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6881. threshold = float(threshold_str) if threshold_str else 35.0
  6882. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6883. async with async_session() as db:
  6884. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6885. if providers:
  6886. _bed_cool_waiters[printer_id] = {
  6887. "threshold": threshold,
  6888. "filename": filename or subtask_name or "",
  6889. "registered_at": time.time(),
  6890. }
  6891. logger.info(
  6892. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6893. printer_id,
  6894. threshold,
  6895. )
  6896. else:
  6897. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6898. except Exception as e:
  6899. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6900. # Capture the slicer estimate before usage tracking runs. The tracker may
  6901. # update archive.cost with this run's measured cost; billing partial runs
  6902. # against that already-partial value would discount the charge twice.
  6903. billing_planned_grams: float | None = None
  6904. billing_base_cost: float | None = None
  6905. if archive_id:
  6906. try:
  6907. async with async_session() as db:
  6908. from backend.app.models.archive import PrintArchive
  6909. billing_archive = await db.get(PrintArchive, archive_id)
  6910. if billing_archive:
  6911. billing_path = (
  6912. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6913. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6914. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6915. billing_archive,
  6916. billing_path,
  6917. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6918. )
  6919. except Exception as e:
  6920. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6921. # --- Track filament consumption (must run before archive_id early-return so usage
  6922. # is recorded even when auto-archive is disabled) ---
  6923. usage_results: list[dict] = []
  6924. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6925. stored_ams_mapping = data.get("ams_mapping")
  6926. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6927. if not stored_ams_mapping and archive_id:
  6928. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6929. # Always drain the plate_id register on completion — the session already
  6930. # consumed it at print-start injection; leaving it would leak into the next
  6931. # print on the same archive_id (rare but possible with reprints) (#1697).
  6932. # Capture the popped value so the completion notification can scope the
  6933. # archive-level (summed-across-plates per #1593) filament + time totals
  6934. # down to the single plate that was actually printed (#1785).
  6935. notify_plate_id: int | None = None
  6936. if archive_id:
  6937. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6938. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6939. try:
  6940. async with async_session() as db:
  6941. from backend.app.api.routes.settings import get_setting
  6942. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6943. if not _spoolman_on or _spoolman_on.lower() != "true":
  6944. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6945. async with async_session() as db:
  6946. usage_results = await usage_on_print_complete(
  6947. printer_id,
  6948. data,
  6949. printer_manager,
  6950. db,
  6951. archive_id=archive_id,
  6952. ams_mapping=stored_ams_mapping,
  6953. )
  6954. if usage_results:
  6955. await ws_manager.broadcast(
  6956. {
  6957. "type": "spool_usage_logged",
  6958. "printer_id": printer_id,
  6959. "usage": usage_results,
  6960. }
  6961. )
  6962. log_timing("Usage tracker")
  6963. except Exception as e:
  6964. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6965. # Drop the print-start context unconditionally — the Spoolman branch above
  6966. # skips the internal tracker entirely, so nothing else would clear what
  6967. # print start captured, and a row surviving its print would be restored
  6968. # onto the next one after a restart.
  6969. try:
  6970. from backend.app.services.usage_tracker import discard_session
  6971. async with async_session() as db:
  6972. await discard_session(db, printer_id)
  6973. except Exception as e:
  6974. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6975. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6976. if archive_id:
  6977. if data.get("status") == "completed":
  6978. try:
  6979. await _report_spoolman_usage(printer_id, archive_id)
  6980. log_timing("Spoolman usage report")
  6981. except Exception as e:
  6982. logger.warning("Spoolman usage reporting failed: %s", e)
  6983. else:
  6984. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6985. try:
  6986. async with async_session() as db:
  6987. await _cleanup_spoolman_tracking(
  6988. printer_id,
  6989. archive_id,
  6990. db,
  6991. last_layer_num=data.get("last_layer_num"),
  6992. last_progress=data.get("last_progress"),
  6993. )
  6994. except Exception as e:
  6995. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6996. log_timing("Filament usage tracking")
  6997. if not archive_id:
  6998. # The printer's own calibration run has no archive by design, so this
  6999. # arrives here every time one finishes. Returning before the no-archive
  7000. # notification keeps a calibration from being announced as a finished
  7001. # print. Everything above this point has already run — the plate-clear
  7002. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7003. # notification is skipped.
  7004. if is_internal_printer_job(filename, subtask_name):
  7005. logger.info(
  7006. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7007. filename,
  7008. subtask_name,
  7009. )
  7010. return
  7011. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7012. # Still send print-complete/failed/stopped notifications even without an archive.
  7013. # Try to enrich with queue/library-file data so user-specific emails work too.
  7014. async def _notify_no_archive():
  7015. try:
  7016. async with async_session() as db:
  7017. from backend.app.models.library import LibraryFile
  7018. from backend.app.models.print_queue import PrintQueueItem
  7019. from backend.app.models.printer import Printer
  7020. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7021. printer_obj = result.scalar_one_or_none()
  7022. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7023. # Only the queue item this completion itself closed (the
  7024. # reconciliation above, which checks the run belongs to it).
  7025. # A print started outside Bambuddy closed none, and must not
  7026. # borrow an earlier job's owner, email or times.
  7027. no_archive_data: dict | None = None
  7028. try:
  7029. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7030. if queue_item:
  7031. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7032. # How long it really ran, as the archive path reports it (#1198).
  7033. started = to_naive_utc(queue_item.started_at)
  7034. ended = to_naive_utc(queue_item.completed_at)
  7035. if started and ended and (ended - started).total_seconds() > 0:
  7036. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7037. # Estimated time: the queue item caches it from its
  7038. # archive or library file; otherwise read the library
  7039. # file's metadata (LibraryFile has no column for it).
  7040. if queue_item.print_time_seconds:
  7041. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7042. elif queue_item.library_file_id:
  7043. lib_result = await db.execute(
  7044. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7045. )
  7046. lib_file = lib_result.scalar_one_or_none()
  7047. estimate = (
  7048. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7049. )
  7050. if estimate:
  7051. no_archive_data["print_time_seconds"] = estimate
  7052. except Exception as lookup_err:
  7053. logger.debug(
  7054. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7055. )
  7056. # Enrich with usage tracker results (captured in enclosing scope)
  7057. if usage_results:
  7058. if no_archive_data is None:
  7059. no_archive_data = {}
  7060. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7061. if total_from_usage > 0:
  7062. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7063. no_archive_data["usage_results"] = usage_results
  7064. # Try MQTT remaining_time for print duration when no queue/library data
  7065. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7066. mqtt_remaining = data.get("remaining_time")
  7067. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7068. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7069. ps = data.get("status", "completed")
  7070. logger.info(
  7071. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7072. )
  7073. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7074. await notification_service.on_print_complete(
  7075. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7076. )
  7077. else:
  7078. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7079. # Send user-specific email if we have a created_by_id
  7080. if no_archive_data and no_archive_data.get("created_by_id"):
  7081. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7082. await _dispatch_user_print_email(
  7083. ps,
  7084. no_archive_data["created_by_id"],
  7085. p_name,
  7086. raw_filename,
  7087. db,
  7088. )
  7089. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7090. except Exception as e:
  7091. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7092. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7093. return
  7094. log_timing("Archive lookup")
  7095. # Update archive status
  7096. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7097. try:
  7098. async with async_session() as db:
  7099. service = ArchiveService(db)
  7100. status = data.get("status", "completed")
  7101. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7102. if hms_errors:
  7103. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7104. failure_reason = derive_failure_reason(status, hms_errors)
  7105. if data.get("_reconciled"):
  7106. # A reconciled completion closes out a stale archive at
  7107. # reconnect — it is not a user action, so don't mislabel it
  7108. # "userCancelled". It shares the stale-cleanup path's key
  7109. # (issue #2974) and records that the real end time is unknown,
  7110. # which is also why its logged duration is 0 (#2592).
  7111. failure_reason = "noStatusUpdate"
  7112. if failure_reason:
  7113. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7114. elif status == "failed" and hms_errors:
  7115. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7116. await service.update_archive_status(
  7117. archive_id,
  7118. status=status,
  7119. completed_at=(
  7120. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7121. ),
  7122. failure_reason=failure_reason,
  7123. )
  7124. logger.info(
  7125. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7126. )
  7127. await ws_manager.send_archive_updated(
  7128. {
  7129. "id": archive_id,
  7130. "status": status,
  7131. }
  7132. )
  7133. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7134. # MQTT relay - publish archive updated
  7135. try:
  7136. await mqtt_relay.on_archive_updated(
  7137. archive_id=archive_id,
  7138. print_name=filename or subtask_name,
  7139. status=status,
  7140. )
  7141. except Exception:
  7142. pass # Don't fail if MQTT fails
  7143. except Exception as e:
  7144. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7145. # Continue with other operations even if archive update fails
  7146. log_timing("Archive status update")
  7147. # Apply finance wallet charge or release reservations once. For all partial
  7148. # terminal states (failed, aborted at the printer display, or cancelled via
  7149. # Bambuddy) use this run's measured spool delta, falling back to the last
  7150. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7151. # estimate and therefore cannot represent an interrupted run.
  7152. try:
  7153. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7154. async with async_session() as db:
  7155. from backend.app.models.archive import PrintArchive
  7156. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7157. archive = await db.get(PrintArchive, archive_id)
  7158. if archive and billing_run_id is None:
  7159. billing_run_id = getattr(archive, "billing_run_id", None)
  7160. if archive and archive.created_by_id is None and _print_user_info:
  7161. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7162. await db.flush()
  7163. run_status = data.get("status", "completed")
  7164. last_progress = data.get("last_progress")
  7165. if last_progress is None:
  7166. last_progress = data.get("progress")
  7167. actual_run_grams = _compute_run_filament_grams(
  7168. run_status,
  7169. billing_planned_grams,
  7170. last_progress,
  7171. usage_results,
  7172. )
  7173. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7174. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7175. charged = await apply_print_charge_for_archive(
  7176. db,
  7177. archive_id,
  7178. charged_user_id=billing_user_id,
  7179. cost_center_id=(
  7180. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7181. ),
  7182. print_queue_id=queue_item_id,
  7183. print_run_id=billing_run_id,
  7184. base_cost_override=billing_base_cost,
  7185. filament_usage=filament_usage,
  7186. )
  7187. await db.commit()
  7188. if charged:
  7189. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7190. except Exception as e:
  7191. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7192. printer_info = printer_manager.get_printer(printer_id)
  7193. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7194. billing_filename = filename or subtask_name or "Unknown"
  7195. billing_error = str(e)
  7196. try:
  7197. await ws_manager.broadcast(
  7198. {
  7199. "type": "billing_charge_failed",
  7200. "printer_id": printer_id,
  7201. "printer_name": billing_printer_name,
  7202. "filename": billing_filename,
  7203. "archive_id": archive_id,
  7204. }
  7205. )
  7206. except Exception as notification_error:
  7207. logger.error(
  7208. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7209. archive_id,
  7210. notification_error,
  7211. )
  7212. async def _notify_billing_charge_failed() -> None:
  7213. try:
  7214. async with async_session() as notification_db:
  7215. await notification_service.on_billing_charge_failed(
  7216. printer_id,
  7217. billing_printer_name,
  7218. billing_filename,
  7219. archive_id,
  7220. billing_error,
  7221. notification_db,
  7222. )
  7223. except Exception as provider_error:
  7224. logger.error(
  7225. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7226. archive_id,
  7227. provider_error,
  7228. exc_info=True,
  7229. )
  7230. spawn_background_task(
  7231. _notify_billing_charge_failed(),
  7232. name=f"billing-charge-failed-{archive_id}",
  7233. )
  7234. log_timing("Finance charge update")
  7235. # Write independent print log entry (separate table, never touches archives)
  7236. try:
  7237. async with async_session() as db:
  7238. from backend.app.models.archive import PrintArchive
  7239. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7240. archive = await db.get(PrintArchive, archive_id)
  7241. if archive:
  7242. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7243. # source archive row rather than creating a new one, so an
  7244. # archive that was auto-created from a printer-initiated
  7245. # print (created_by_id=NULL) would otherwise stay unattributed
  7246. # forever. When we have a print-session user AND the archive
  7247. # has no attribution yet, credit the current user. Never
  7248. # overwrite an existing attribution — the original uploader
  7249. # keeps ownership.
  7250. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7251. if archive.created_by_id is None and _print_user_id is not None:
  7252. archive.created_by_id = _print_user_id
  7253. p_info = printer_manager.get_printer(printer_id)
  7254. # Per-run actuals — written to PrintLogEntry so stats reflect
  7255. # what THIS print actually used, not the source archive's
  7256. # first-run values (#1378). Helper handles the partial-print
  7257. # math (failed / cancelled / stopped get scaled to progress
  7258. # or to tracked spool deltas).
  7259. _run_status = data.get("status", "completed")
  7260. # #2614: scope the per-run estimate to the printed plate. For a
  7261. # multi-plate 3MF dispatched one plate at a time, the archive's
  7262. # filament/cost are the whole-file totals; the PrintLogEntry must
  7263. # reflect only this plate. No effect on single-plate archives (the
  7264. # plate estimate equals the whole-file value) or on the tracker
  7265. # path (measured spool deltas win in _compute_run_filament_grams).
  7266. _est_full_path = (
  7267. app_settings.base_dir / archive.file_path if archive.file_path else None
  7268. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7269. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7270. _run_grams = _compute_run_filament_grams(
  7271. _run_status,
  7272. _est_grams,
  7273. data.get("last_progress", data.get("progress")),
  7274. usage_results,
  7275. )
  7276. # Per-run cost — prefer usage_results sum. For partial prints
  7277. # we deliberately skip the topup-to-estimate logic in
  7278. # usage_tracker (which assumes the print completed); the raw
  7279. # tracked-spool sum is closer to what THIS run actually cost.
  7280. _run_cost: float | None = None
  7281. if usage_results:
  7282. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7283. if _run_cost is None and _run_status == "completed":
  7284. _run_cost = _est_cost
  7285. from backend.app.models.printer import Printer as _Printer
  7286. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7287. run_entry = await write_log_entry(
  7288. db,
  7289. archive_id=archive.id,
  7290. # Captured by _update_queue_status above; None for
  7291. # printer-initiated prints with no queue row. Batch
  7292. # cost/energy roll-up joins on it (#342).
  7293. queue_item_id=queue_item_id,
  7294. status=_run_status,
  7295. print_name=archive.print_name,
  7296. printer_name=p_info.name if p_info else None,
  7297. printer_id=printer_id,
  7298. started_at=archive.started_at,
  7299. completed_at=archive.completed_at,
  7300. filament_type=archive.filament_type,
  7301. filament_color=archive.filament_color,
  7302. filament_used_grams=_run_grams,
  7303. cost=_run_cost,
  7304. wear_cost_per_hour=_wear_rate,
  7305. failure_reason=archive.failure_reason,
  7306. thumbnail_path=archive.thumbnail_path,
  7307. created_by_id=archive.created_by_id,
  7308. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7309. # Reconciled completions have an unknown real end time —
  7310. # log 0 duration instead of the whole disconnect gap (#2592).
  7311. reconciled=bool(data.get("_reconciled")),
  7312. )
  7313. await record_archive_wear(db, archive, run_entry)
  7314. await db.commit()
  7315. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7316. except Exception as e:
  7317. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7318. log_timing("Print log entry")
  7319. # Run slow operations as background tasks to avoid blocking the event loop
  7320. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7321. async def _background_energy_calculation():
  7322. """Calculate and save energy usage in background.
  7323. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7324. backend restart no longer loses per-print energy data).
  7325. """
  7326. try:
  7327. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7328. async with async_session() as db:
  7329. from backend.app.models.archive import PrintArchive
  7330. archive = await db.get(PrintArchive, archive_id)
  7331. if archive is None:
  7332. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7333. return
  7334. starting_kwh = archive.energy_start_kwh
  7335. if starting_kwh is None:
  7336. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7337. return
  7338. candidates = await energy_plug_candidates(db, printer_id)
  7339. if not candidates:
  7340. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7341. return
  7342. # Same ordering as the start reading, so the delta below is
  7343. # against the counter that produced `starting_kwh` (#2859).
  7344. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7345. if selected is None:
  7346. logger.warning(
  7347. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7348. printer_id,
  7349. ", ".join(plug.name for plug in candidates),
  7350. )
  7351. return
  7352. plug, energy = selected
  7353. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7354. energy_used = round(energy["total"] - starting_kwh, 4)
  7355. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7356. if energy_used < 0:
  7357. logger.warning(
  7358. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7359. archive_id,
  7360. starting_kwh,
  7361. energy["total"],
  7362. )
  7363. return
  7364. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7365. # Each hour of the print at the price of that hour (#1251). If
  7366. # that fails, the last price known, as before, rather than no
  7367. # energy at all. Read first: the session may be unusable after.
  7368. last_price = await stored_price(db)
  7369. try:
  7370. energy_cost_value = round(
  7371. await print_energy_cost(
  7372. db,
  7373. plug_id=archive.energy_start_plug_id,
  7374. start_at=archive.energy_start_at,
  7375. start_kwh=starting_kwh,
  7376. start_price=archive.energy_start_price,
  7377. end_kwh=energy["total"],
  7378. end_plug_id=plug.id,
  7379. price_now=await current_price(db),
  7380. ),
  7381. 3,
  7382. )
  7383. except Exception as e:
  7384. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7385. energy_cost_value = round(energy_used * last_price, 3)
  7386. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7387. # reprint doesn't visually clobber the source archive's energy data
  7388. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7389. from sqlalchemy import func
  7390. from backend.app.models.print_log import PrintLogEntry
  7391. existing_runs = await db.scalar(
  7392. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7393. )
  7394. if (existing_runs or 0) <= 1:
  7395. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7396. # we just wrote for THIS print. Either way it's the first run.
  7397. archive.energy_kwh = energy_used
  7398. archive.energy_cost = energy_cost_value
  7399. # Backfill the latest PrintLogEntry for this archive with energy
  7400. # (write_log_entry above ran before this background task completed,
  7401. # so energy fields are still NULL on that row).
  7402. latest_run = await db.execute(
  7403. select(PrintLogEntry)
  7404. .where(PrintLogEntry.archive_id == archive_id)
  7405. .order_by(PrintLogEntry.id.desc())
  7406. .limit(1)
  7407. )
  7408. run_row = latest_run.scalar_one_or_none()
  7409. if run_row is not None:
  7410. run_row.energy_kwh = energy_used
  7411. run_row.energy_cost = energy_cost_value
  7412. await db.commit()
  7413. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7414. except Exception as e:
  7415. logger.warning("[ENERGY-BG] Failed: %s", e)
  7416. async def _background_finish_photo() -> str | None:
  7417. """Capture finish photo in background. Returns photo filename if captured."""
  7418. # #2547: set once this function has raised the plate itself (the
  7419. # timelapse path, where the moment producer returned without doing it).
  7420. # Declared out here so the `finally` can lower it again no matter where
  7421. # the capture below fails.
  7422. plate_restored_z: float | None = None
  7423. try:
  7424. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7425. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7426. # Read phase: settings + printer + archive in a short session, released
  7427. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7428. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7429. # tens of seconds; holding this session across it pinned one pooled
  7430. # connection idle-in-transaction per finishing print (issue #2572).
  7431. async with async_session() as db:
  7432. from backend.app.api.routes.settings import get_setting
  7433. from backend.app.models.archive import PrintArchive
  7434. from backend.app.models.printer import Printer
  7435. capture_enabled = await get_setting(db, "capture_finish_photo")
  7436. if capture_enabled is not None and capture_enabled.lower() != "true":
  7437. return None
  7438. if not archive_id:
  7439. return None
  7440. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7441. archive = (
  7442. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7443. ).scalar_one_or_none()
  7444. if not printer or not archive:
  7445. return None
  7446. import uuid
  7447. from datetime import datetime
  7448. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7449. if not archive.file_path:
  7450. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7451. archive_dir = resolve_archive_dir(archive)
  7452. photo_filename = None
  7453. # Prefer the timelapse last-frame source when a timelapse was
  7454. # recording — it captures the moment after the toolhead parks
  7455. # but before the bed drops, which the live-camera grab below
  7456. # would miss (#1397). Skipped for external cameras (those have
  7457. # their own framing and don't see a Bambu timelapse). Only
  7458. # runs when the USER explicitly enabled timelapse for this
  7459. # print — #1721 removed Bambuddy's force-on at dispatch
  7460. # because it caused per-layer nozzle parking on Smooth-mode
  7461. # slicer profiles.
  7462. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7463. printer.external_camera_enabled and printer.external_camera_url
  7464. )
  7465. timelapse_still_pending = False
  7466. if prefer_timelapse_source:
  7467. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7468. archive_id=archive_id,
  7469. archive_dir=archive_dir,
  7470. rotation=getattr(printer, "camera_rotation", 0),
  7471. )
  7472. # #1721: replacement framing path — on_finish_photo_moment
  7473. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7474. # parked, bed not yet dropped) and cached the JPEG bytes in
  7475. # _stage22_finish_frames. Consume them now so the saved photo
  7476. # has the better framing instead of the post-bed-drop angle
  7477. # the live-camera fallback below would give.
  7478. if not photo_filename:
  7479. # #1790: on the FINISH-state fallback path the producer
  7480. # task is dispatched back-to-back with this consumer, so
  7481. # a bare pop would race past with an empty result and
  7482. # the RTSP fallback below would collide with the
  7483. # producer's still-in-flight grab (single-client RTSP
  7484. # on Bambu printers). Wait for the producer to finish
  7485. # or give up before touching the cache.
  7486. #
  7487. # #2547: 20s was enough when the producer only ever grabbed a
  7488. # frame. It now also raises the plate first, which costs the
  7489. # settle window before the grab even starts — so the budget has
  7490. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7491. # under the notification's own photo wait below.
  7492. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7493. if in_flight is not None:
  7494. try:
  7495. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7496. except TimeoutError:
  7497. logger.warning(
  7498. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7499. printer_id,
  7500. )
  7501. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7502. if cached_frame:
  7503. # Already rotated by the producer (#2708) — rotating again
  7504. # here would undo the fix on the banked-frame path, whose
  7505. # bytes reach the cache having been rotated once already.
  7506. photos_dir = archive_dir / "photos"
  7507. photos_dir.mkdir(parents=True, exist_ok=True)
  7508. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7509. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7510. photo_path = photos_dir / photo_filename
  7511. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7512. logger.info(
  7513. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7514. photo_filename,
  7515. len(cached_frame),
  7516. )
  7517. # #2547: the timelapse path reaches the live grab below whenever the
  7518. # video hasn't landed in time — the documented usual outcome on
  7519. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7520. # returned early for those prints without raising the plate, so
  7521. # without this the photo that actually ships in the notification is
  7522. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7523. # asked us to fix. The archive still gets the better video frame
  7524. # later; this is about the image the user is sent.
  7525. #
  7526. # Gated on `timelapse_was_active` precisely because that is the
  7527. # condition under which the producer skipped. On every other path it
  7528. # has already raised and lowered the plate, and repeating that here
  7529. # would be a second pointless round trip.
  7530. if (
  7531. not photo_filename
  7532. and data.get("timelapse_was_active")
  7533. and not print_dispatch_context.end_gcode_injected(printer_id)
  7534. ):
  7535. try:
  7536. async with async_session() as db:
  7537. from backend.app.api.routes.settings import get_setting
  7538. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7539. if restore_setting is None or restore_setting.lower() == "true":
  7540. max_z = await _max_z_for_current_print(
  7541. printer_id, data, logger, bound_archive_id, notify_plate_id
  7542. )
  7543. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7544. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7545. plate_restored_z = max_z
  7546. except Exception as e:
  7547. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7548. # Fallback chain: external camera → buffered live frame →
  7549. # fresh RTSP capture. Only runs if the timelapse path above
  7550. # didn't already produce a photo.
  7551. # Chamber light for the live capture below (#1655).
  7552. async with camera_light(printer if not photo_filename else None):
  7553. if not photo_filename:
  7554. if printer.external_camera_enabled and printer.external_camera_url:
  7555. logger.info("[PHOTO-BG] Using external camera")
  7556. from backend.app.api.routes.camera import live_frame_for_capture
  7557. from backend.app.services.external_camera import capture_frame
  7558. # #2707: the second half of the finish-photo failure — the
  7559. # pre-capture and this fallback both collided with the live
  7560. # view. None here continues down the fallback chain.
  7561. defer, buffered = live_frame_for_capture(printer_id)
  7562. if defer:
  7563. frame_data = buffered
  7564. else:
  7565. frame_data = await capture_frame(
  7566. printer.external_camera_url,
  7567. printer.external_camera_type or "mjpeg",
  7568. snapshot_url=printer.external_camera_snapshot_url,
  7569. )
  7570. if frame_data:
  7571. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7572. photos_dir = archive_dir / "photos"
  7573. photos_dir.mkdir(parents=True, exist_ok=True)
  7574. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7575. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7576. photo_path = photos_dir / photo_filename
  7577. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7578. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7579. else:
  7580. # Check if camera stream is active - use buffered frame to avoid freeze
  7581. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7582. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7583. active_chamber_for_printer = [
  7584. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7585. ]
  7586. buffered_frame = get_buffered_frame(printer_id)
  7587. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7588. # Use frame from active stream
  7589. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7590. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7591. photos_dir = archive_dir / "photos"
  7592. photos_dir.mkdir(parents=True, exist_ok=True)
  7593. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7594. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7595. photo_path = photos_dir / photo_filename
  7596. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7597. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7598. else:
  7599. # No active stream - capture new frame
  7600. from backend.app.services.camera import capture_finish_photo
  7601. photo_filename = await capture_finish_photo(
  7602. printer_id=printer_id,
  7603. ip_address=printer.ip_address,
  7604. access_code=printer.access_code,
  7605. model=printer.model,
  7606. archive_dir=archive_dir,
  7607. rotation=getattr(printer, "camera_rotation", 0),
  7608. )
  7609. # Write phase: attach the photo in a fresh short-lived session.
  7610. if photo_filename:
  7611. async with async_session() as db:
  7612. from backend.app.models.archive import PrintArchive
  7613. arch = await db.get(PrintArchive, archive_id)
  7614. if arch is not None:
  7615. photos = arch.photos or []
  7616. photos.append(photo_filename)
  7617. arch.photos = photos
  7618. await db.commit()
  7619. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7620. # The short wait above is bounded so a slow printer can't hold up
  7621. # the print-complete notification, which is what the caller is
  7622. # blocking on. When it ran out with the video still on its way,
  7623. # keep waiting off to the side and add the better frame to the
  7624. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7625. # users, whose videos routinely take minutes to transfer, never get
  7626. # the pre-bed-drop framing this path exists to provide.
  7627. #
  7628. # Spawned here rather than at the point the wait gave up: both this
  7629. # function and the upgrade do a read-modify-write on `photos`, and
  7630. # the live-camera fallback above can take tens of seconds. Starting
  7631. # the upgrade before that write means the two can interleave and one
  7632. # silently drops the other's entry, leaving a JPEG on disk that the
  7633. # gallery never lists.
  7634. if timelapse_still_pending:
  7635. spawn_background_task(
  7636. _upgrade_finish_photo_from_timelapse(
  7637. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7638. ),
  7639. name=f"finish-photo-upgrade-{archive_id}",
  7640. )
  7641. return photo_filename
  7642. except Exception as e:
  7643. logger.warning("[PHOTO-BG] Failed: %s", e)
  7644. return None
  7645. finally:
  7646. # #2547: we raised the plate, so we owe the move back down — even if
  7647. # the capture in between threw. Otherwise the user finds the print
  7648. # pinned under the nozzle.
  7649. if plate_restored_z is not None:
  7650. try:
  7651. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7652. except Exception as e:
  7653. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7654. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7655. # Photo capture task - result will be used by notifications
  7656. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7657. log_timing("Background tasks scheduled (energy, photo)")
  7658. # Also run smart plug, notifications, and maintenance as background tasks
  7659. print_status = data.get("status", "completed")
  7660. async def _background_smart_plug():
  7661. """Handle smart plug automation in background."""
  7662. try:
  7663. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7664. async with async_session() as db:
  7665. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7666. logger.info("[AUTO-OFF-BG] Completed")
  7667. except Exception as e:
  7668. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7669. async def _background_notifications(finish_photo_filename: str | None = None):
  7670. """Send print complete notifications in background."""
  7671. try:
  7672. logger.info(
  7673. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7674. )
  7675. async with async_session() as db:
  7676. from backend.app.models.archive import PrintArchive
  7677. from backend.app.models.printer import Printer
  7678. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7679. printer = result.scalar_one_or_none()
  7680. printer_name = printer.name if printer else f"Printer {printer_id}"
  7681. archive_data = None
  7682. if archive_id:
  7683. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7684. archive = archive_result.scalar_one_or_none()
  7685. if archive:
  7686. # Actual elapsed time from started_at/completed_at when both are
  7687. # populated (every terminal status sets completed_at after #1198).
  7688. # Falls back to None so the notification path can decide whether to
  7689. # render the slicer estimate as a last resort.
  7690. actual_time_seconds = None
  7691. if archive.started_at and archive.completed_at:
  7692. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7693. if elapsed > 0:
  7694. actual_time_seconds = int(elapsed)
  7695. archive_data = {
  7696. "print_time_seconds": archive.print_time_seconds,
  7697. "actual_time_seconds": actual_time_seconds,
  7698. "actual_filament_grams": archive.filament_used_grams,
  7699. "failure_reason": archive.failure_reason,
  7700. "created_by_id": archive.created_by_id,
  7701. }
  7702. # Scale filament usage for partial prints
  7703. if print_status != "completed" and archive.filament_used_grams:
  7704. progress = data.get("progress") or 0
  7705. scale = _partial_progress_scale(progress)
  7706. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7707. archive_data["progress"] = progress
  7708. # Pass per-slot data from archive.extra_data
  7709. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7710. slots = archive.extra_data["filament_slots"]
  7711. if print_status != "completed":
  7712. scale = _partial_progress_scale(data.get("progress"))
  7713. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7714. archive_data["filament_slots"] = slots
  7715. # Scope project-summed totals down to the plate that was
  7716. # actually printed — see _scope_notification_archive_data_to_plate
  7717. # for the why (#1785).
  7718. archive_data = _scope_notification_archive_data_to_plate(
  7719. archive_data,
  7720. archive.file_path,
  7721. notify_plate_id,
  7722. print_status,
  7723. data.get("progress"),
  7724. app_settings.base_dir,
  7725. )
  7726. # Enrich filament_grams from usage_results when archive has no 3MF data
  7727. if not archive_data.get("actual_filament_grams") and usage_results:
  7728. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7729. if total_from_usage > 0:
  7730. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7731. # Pass usage tracker results for AMS slot info in notifications
  7732. if usage_results:
  7733. archive_data["usage_results"] = usage_results
  7734. # Add finish photo URL and image bytes if available
  7735. if finish_photo_filename:
  7736. photo_url, photo_bytes = await _finish_photo_for_notification(
  7737. db, archive, archive_id, finish_photo_filename
  7738. )
  7739. if photo_url:
  7740. archive_data["finish_photo_url"] = photo_url
  7741. if photo_bytes:
  7742. archive_data["image_data"] = photo_bytes
  7743. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7744. await notification_service.on_print_complete(
  7745. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7746. )
  7747. else:
  7748. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7749. # Post-print outcome confirmation (#1898). Runs in this
  7750. # background task so the finish photo fetched above rides
  7751. # along with the prompt.
  7752. if print_status == "completed" and archive_id:
  7753. await _dispatch_outcome_confirmation_safely(
  7754. db, printer_id, printer_name, data, archive_id, archive_data
  7755. )
  7756. # Send user-specific email notification
  7757. if archive_data:
  7758. created_by_id = archive_data.get("created_by_id")
  7759. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7760. await _dispatch_user_print_email(
  7761. print_status,
  7762. created_by_id,
  7763. printer_name,
  7764. raw_filename,
  7765. db,
  7766. image_data=archive_data.get("image_data"),
  7767. finish_photo_url=archive_data.get("finish_photo_url"),
  7768. )
  7769. logger.info("[NOTIFY-BG] Completed")
  7770. except Exception as e:
  7771. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7772. async def _background_maintenance_check():
  7773. """Check for maintenance due in background."""
  7774. if print_status != "completed":
  7775. return
  7776. try:
  7777. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7778. async with async_session() as db:
  7779. from backend.app.models.printer import Printer
  7780. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7781. printer = result.scalar_one_or_none()
  7782. printer_name = printer.name if printer else f"Printer {printer_id}"
  7783. await ensure_default_types(db)
  7784. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7785. attention = [
  7786. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  7787. ]
  7788. items_needing_attention = [
  7789. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7790. for item in attention
  7791. ]
  7792. if items_needing_attention:
  7793. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7794. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7795. # MQTT relay - publish maintenance alerts
  7796. for item in attention:
  7797. current_value, threshold, unit = maintenance_alert_values(item)
  7798. try:
  7799. await mqtt_relay.on_maintenance_alert(
  7800. printer_id=printer_id,
  7801. printer_name=printer_name,
  7802. maintenance_type=item.maintenance_type_name,
  7803. current_value=current_value,
  7804. threshold=threshold,
  7805. unit=unit,
  7806. )
  7807. except Exception:
  7808. pass # Don't fail if MQTT fails
  7809. else:
  7810. logger.info("[MAINT-BG] Completed (no items need attention)")
  7811. except Exception as e:
  7812. logger.warning("[MAINT-BG] Failed: %s", e)
  7813. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7814. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7815. # Notification task waits for photo capture to complete first (with timeout).
  7816. # When a timelapse was recording, photo sourcing polls the per-print
  7817. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7818. # carries the correct bed-up photo instead of falling through to the
  7819. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7820. #
  7821. # #2547: both budgets now have to cover a plate restore as well.
  7822. #
  7823. # Without timelapse, the wait is on the moment producer, which raises the
  7824. # plate before its grab — so this has to outlast that producer's own budget.
  7825. #
  7826. # With timelapse, the capture polls up to
  7827. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7828. # falls back to a live grab, which is the case that raises the plate. At the
  7829. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7830. # restore would have moved the plate for a photo nobody waited for.
  7831. photo_wait_timeout = (
  7832. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7833. if data.get("timelapse_was_active")
  7834. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7835. )
  7836. async def _photo_then_notify():
  7837. """Wait for photo capture, then send notification with photo URL."""
  7838. finish_photo = None
  7839. try:
  7840. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7841. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7842. except TimeoutError:
  7843. logger.warning(
  7844. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7845. photo_wait_timeout,
  7846. )
  7847. except Exception as e:
  7848. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7849. try:
  7850. await _background_notifications(finish_photo)
  7851. except Exception as e:
  7852. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7853. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7854. # Stitch external camera layer timelapse if session was active
  7855. print_status = data.get("status", "completed")
  7856. async def _background_layer_timelapse():
  7857. """Stitch layer timelapse and attach to archive."""
  7858. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7859. try:
  7860. if print_status == "completed":
  7861. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7862. timelapse_path = await tl_complete(printer_id)
  7863. if timelapse_path and archive_id:
  7864. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7865. async with async_session() as db:
  7866. service = ArchiveService(db)
  7867. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7868. await service.attach_timelapse(
  7869. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  7870. )
  7871. # Clean up the temp file
  7872. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7873. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7874. elif timelapse_path:
  7875. # Timelapse created but no archive - just clean up
  7876. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7877. else:
  7878. # Print failed or cancelled - cancel timelapse session
  7879. cancel_session(printer_id)
  7880. logger.info(
  7881. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7882. )
  7883. except Exception as e:
  7884. logger.warning("[LAYER-TL] Failed: %s", e)
  7885. # Try to cancel session on error
  7886. try:
  7887. cancel_session(printer_id)
  7888. except Exception:
  7889. pass # Best-effort timelapse session cancellation on error
  7890. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7891. log_timing("All background tasks scheduled")
  7892. # Auto-scan for timelapse if recording was active during the print
  7893. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7894. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7895. # Schedule timelapse scan as background task with retries
  7896. # The printer needs time to encode the video after print completion
  7897. baseline = _timelapse_baselines.pop(printer_id, None)
  7898. spawn_background_task(
  7899. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  7900. name=f"scan-timelapse-{archive_id}",
  7901. )
  7902. log_timing("Timelapse scan scheduled")
  7903. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7904. # AMS sensor history recording
  7905. _ams_history_task: asyncio.Task | None = None
  7906. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7907. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7908. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7909. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7910. _ams_alarm_cooldown: dict[str, datetime] = {}
  7911. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7912. # (printer_id, ams_id) already reported as sending the drop index and no
  7913. # percentage. Logged once each so a supported printer that turns out to do this
  7914. # shows up in a support bundle rather than as a user wondering where the
  7915. # humidity reading went -- see the note at the read site below (#3140).
  7916. _ams_index_only_logged: set[tuple[int, int]] = set()
  7917. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7918. """Temperature at which the AMS alarm fires, falling back to the display band.
  7919. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7920. when a notification was sent as well, which is why a room above it made the
  7921. alarm fire once an hour for as long as the weather lasted -- and the only way
  7922. to stop that was to raise the display band and lose the colour that says the
  7923. unit is warm (#2905).
  7924. Unset resolves to the fair threshold, so an install that never sets one is
  7925. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7926. so that arrives here as a string and is handled by the same branch as any
  7927. other unparseable value -- there is no separate sentinel to keep in sync.
  7928. A non-positive value is refused rather than honoured: zero would alarm
  7929. permanently, and it is far more likely to be a cleared field than a
  7930. deliberate choice.
  7931. """
  7932. if raw_alarm_value is None:
  7933. return fair_threshold
  7934. try:
  7935. value = float(raw_alarm_value)
  7936. except (TypeError, ValueError):
  7937. return fair_threshold
  7938. if not math.isfinite(value) or value <= 0:
  7939. return fair_threshold
  7940. return value
  7941. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7942. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7943. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7944. # partway through a cool-down would otherwise resume alarming about heat the
  7945. # user asked for — the same internal-timestamp-row pattern as
  7946. # support.py's debug_logging_enabled_at.
  7947. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7948. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7949. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7950. # matters when it never does.
  7951. AMS_DRYING_GRACE_MINUTES = 120
  7952. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7953. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7954. Anything older than the grace cap would expire on its next visit anyway, so
  7955. discarding it here costs nothing and stops rows for deleted printers from
  7956. accumulating.
  7957. Stamps ahead of now get two defences, because a box whose clock jumps
  7958. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7959. ones are discarded outright, and the rest are clamped to now. Without the
  7960. clamp the cap would measure from a moment that has not happened yet and hold
  7961. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7962. after a clock jump is a far better failure than an alarm silently disabled
  7963. for hours.
  7964. """
  7965. from backend.app.models.settings import Settings
  7966. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7967. setting = result.scalar_one_or_none()
  7968. if not setting or not setting.value:
  7969. return {}
  7970. try:
  7971. raw = json.loads(setting.value)
  7972. except (ValueError, TypeError):
  7973. return {} # Corrupted row → no latch, alarms behave as they did before
  7974. if not isinstance(raw, dict):
  7975. return {}
  7976. now = datetime.now(timezone.utc)
  7977. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7978. latch: dict[str, datetime] = {}
  7979. for key, value in raw.items():
  7980. try:
  7981. stamp = datetime.fromisoformat(str(value))
  7982. except (ValueError, TypeError):
  7983. continue
  7984. if stamp.tzinfo is None:
  7985. stamp = stamp.replace(tzinfo=timezone.utc)
  7986. if not (now - window <= stamp <= now + window):
  7987. continue
  7988. # Nothing may sit in the future: suppression is measured as now minus
  7989. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7990. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7991. latch[str(key)] = min(stamp, now)
  7992. return latch
  7993. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7994. """Persist the latch, writing only when it actually changed.
  7995. Adds the session change but does not commit — the caller's own commit
  7996. carries it, so the latch lands in the same transaction as the sensor rows
  7997. that produced it.
  7998. """
  7999. from backend.app.models.settings import Settings
  8000. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8001. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8002. setting = result.scalar_one_or_none()
  8003. if setting is None:
  8004. # Don't create the row on installs that never dry anything.
  8005. if payload != "{}":
  8006. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8007. elif setting.value != payload:
  8008. setting.value = payload
  8009. def _ams_has_filament(ams_data: dict) -> bool:
  8010. """True if this AMS unit has at least one tray slot holding filament.
  8011. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8012. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8013. still report sensor readings, but those readings are ambient and not
  8014. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8015. humidity/temperature alarms on this check so empty units don't generate
  8016. hourly noise. Sensor history still records regardless so the UI charts
  8017. stay continuous.
  8018. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8019. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8020. """
  8021. bits = ams_data.get("tray_exist_bits")
  8022. if isinstance(bits, str) and bits.strip():
  8023. try:
  8024. return int(bits, 16) > 0
  8025. except ValueError:
  8026. pass
  8027. trays = ams_data.get("tray")
  8028. if isinstance(trays, list):
  8029. return any(
  8030. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8031. )
  8032. return False
  8033. async def record_ams_history():
  8034. """Background task to record AMS humidity and temperature data."""
  8035. logger = logging.getLogger(__name__)
  8036. # Wait a short time for MQTT connections to establish on startup
  8037. await asyncio.sleep(10)
  8038. while True:
  8039. try:
  8040. from backend.app.models.ams_history import AMSSensorHistory
  8041. from backend.app.models.printer import Printer
  8042. from backend.app.models.settings import Settings
  8043. async with async_session() as db:
  8044. # Get all active printers
  8045. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8046. printers = result.scalars().all()
  8047. # Get alarm thresholds from settings
  8048. humidity_threshold = 60.0 # Default: fair threshold
  8049. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8050. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8051. setting = result.scalar_one_or_none()
  8052. if setting:
  8053. try:
  8054. humidity_threshold = float(setting.value)
  8055. except (ValueError, TypeError):
  8056. pass # Keep default threshold if stored value is invalid
  8057. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8058. setting = result.scalar_one_or_none()
  8059. if setting:
  8060. try:
  8061. temp_fair_threshold = float(setting.value)
  8062. except (ValueError, TypeError):
  8063. pass # Keep default threshold if stored value is invalid
  8064. # The alarm gets its own threshold, seeded from the resolved fair
  8065. # value so an install that has never set one behaves exactly as
  8066. # it did before (#2905). ams_temp_fair decides when the card turns
  8067. # amber; 35 C is a reasonable place to change a colour and not a
  8068. # reasonable place to page someone. A room above it makes the
  8069. # alarm fire once an hour for as long as the weather lasts, and
  8070. # the only way to stop it was to raise the display band and lose
  8071. # the colour that says the unit is warm.
  8072. #
  8073. # An unset value is stored as the literal "None", which the except
  8074. # below swallows the same way it swallows garbage -- so the
  8075. # fallback costs nothing and needs no sentinel of its own.
  8076. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8077. setting = result.scalar_one_or_none()
  8078. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8079. temp_fair_threshold, setting.value if setting else None
  8080. )
  8081. # Per-filament humidity threshold overrides (#1605) — resolved
  8082. # per-AMS below from the loaded tray types. Reuses the same
  8083. # resolver as the auto-drying scheduler so behavior stays in
  8084. # lockstep across both consumers.
  8085. from backend.app.services.print_scheduler import PrintScheduler
  8086. per_type_humidity_thresholds: dict[str, int] = {}
  8087. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8088. setting = result.scalar_one_or_none()
  8089. if setting and setting.value:
  8090. try:
  8091. raw = json.loads(setting.value)
  8092. if isinstance(raw, dict):
  8093. for k, v in raw.items():
  8094. try:
  8095. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8096. v
  8097. )
  8098. except (TypeError, ValueError):
  8099. continue
  8100. except (ValueError, TypeError):
  8101. pass # Invalid JSON → no overrides, fall through to global threshold
  8102. # Per-AMS drying latch (#1802), loaded once per pass and written
  8103. # back below only if a unit changed it.
  8104. drying_latch = await _load_ams_drying_latch(db)
  8105. drying_latch_before = dict(drying_latch)
  8106. recorded_count = 0
  8107. for printer in printers:
  8108. # Get current state from printer manager
  8109. state = printer_manager.get_status(printer.id)
  8110. if not state or not state.connected or not state.raw_data:
  8111. continue # Skip disconnected printers - don't use stale data
  8112. raw_data = state.raw_data
  8113. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8114. continue
  8115. # Record data for each AMS unit
  8116. for ams_data in raw_data["ams"]:
  8117. ams_id = int(ams_data.get("id", 0))
  8118. # Percentage only. The 1-5 index is inverted, so
  8119. # charting it as a percentage drew the wettest units as
  8120. # the driest (#3140); a unit that reports no percentage
  8121. # leaves a gap in the chart instead. See
  8122. # utils/ams_humidity.
  8123. humidity = ams_humidity_percent(ams_data)
  8124. # No supported printer is known to send the index
  8125. # alone -- the report came from unsupported firmware,
  8126. # and no install has been seen using the old fallback.
  8127. # "Known" is doing work there, so say so once per unit:
  8128. # the alternative is a silent blank card.
  8129. if humidity is None and ams_data.get("humidity") is not None:
  8130. unit_key = (printer.id, ams_id)
  8131. if unit_key not in _ams_index_only_logged:
  8132. _ams_index_only_logged.add(unit_key)
  8133. logger.info(
  8134. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8135. "percentage. The index is inverted and is not shown as a percentage "
  8136. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8137. "Please report this with the printer and AMS firmware versions.",
  8138. printer.name,
  8139. ams_id,
  8140. )
  8141. # Get temperature
  8142. temperature = None
  8143. temp_str = ams_data.get("temp")
  8144. if temp_str is not None:
  8145. try:
  8146. temperature = float(temp_str)
  8147. except (ValueError, TypeError):
  8148. pass # Skip unparseable temperature value
  8149. # Skip if no data
  8150. if humidity is None and temperature is None:
  8151. continue
  8152. # Record the data point
  8153. history = AMSSensorHistory(
  8154. printer_id=printer.id,
  8155. ams_id=ams_id,
  8156. humidity=humidity,
  8157. # Both columns hold the same reading now that the
  8158. # index can no longer reach ``humidity``. Writing it
  8159. # through the same value also stops a genuine 0%
  8160. # from being stored as NULL, which the old truthiness
  8161. # test did.
  8162. humidity_raw=humidity,
  8163. temperature=temperature,
  8164. )
  8165. db.add(history)
  8166. recorded_count += 1
  8167. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8168. is_ams_ht = ams_id >= 128
  8169. if is_ams_ht:
  8170. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8171. else:
  8172. ams_label = f"AMS-{chr(65 + ams_id)}"
  8173. # Skip alarm dispatch for empty AMS units — humidity /
  8174. # temperature readings are ambient with no filament to
  8175. # protect, and the hourly notification just becomes
  8176. # noise. Sensor history was already recorded above so
  8177. # the UI charts stay continuous (#1619). Per-AMS check
  8178. # so a multi-AMS setup with one loaded + one empty
  8179. # still alarms on the loaded unit.
  8180. if not _ams_has_filament(ams_data):
  8181. continue
  8182. # Resolve per-filament humidity threshold for this AMS
  8183. # unit (#1605). Falls back to the global ams_humidity_fair
  8184. # when no per-type overrides are configured.
  8185. trays = ams_data.get("tray", []) or []
  8186. effective_humidity_threshold = float(
  8187. PrintScheduler.resolve_humidity_threshold(
  8188. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8189. )
  8190. )
  8191. # Check humidity alarm (only if above threshold)
  8192. if humidity is not None and humidity > effective_humidity_threshold:
  8193. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8194. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8195. now = datetime.now(timezone.utc)
  8196. if (
  8197. last_alarm is None
  8198. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8199. ):
  8200. _ams_alarm_cooldown[cooldown_key] = now
  8201. logger.info(
  8202. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8203. )
  8204. try:
  8205. # Call different notification method based on AMS type
  8206. if is_ams_ht:
  8207. await notification_service.on_ams_ht_humidity_high(
  8208. printer.id,
  8209. printer.name,
  8210. ams_label,
  8211. humidity,
  8212. effective_humidity_threshold,
  8213. db,
  8214. )
  8215. else:
  8216. await notification_service.on_ams_humidity_high(
  8217. printer.id,
  8218. printer.name,
  8219. ams_label,
  8220. humidity,
  8221. effective_humidity_threshold,
  8222. db,
  8223. )
  8224. except Exception as e:
  8225. logger.warning("Failed to send humidity alarm: %s", e)
  8226. # A drying cycle heats the unit far past ams_temp_fair on
  8227. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8228. # AMS-HT, against a 35 C default — so the alarm fired
  8229. # once an hour for the whole cycle and kept firing while
  8230. # the unit cooled back down (#1802). Latch on the
  8231. # firmware's own drying state and hold until the reading
  8232. # returns to normal. Humidity is deliberately left alone:
  8233. # it falls during drying, which is the whole point.
  8234. latch_key = f"{printer.id}:{ams_id}"
  8235. # The latch releases at `threshold`, so it takes the alarm
  8236. # number too. Handing it the display band would strand the
  8237. # latch on any unit that settles back above it -- a room
  8238. # where the AMS rests at 37.7 C never returns under a 35 C
  8239. # band, so the latch could only expire on the grace cap
  8240. # rather than releasing when the unit had actually cooled.
  8241. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8242. drying_active=is_drying_active(ams_data),
  8243. temperature=temperature,
  8244. threshold=temp_alarm_threshold,
  8245. latched_at=drying_latch.get(latch_key),
  8246. now=datetime.now(timezone.utc),
  8247. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8248. )
  8249. if new_latch is None:
  8250. drying_latch.pop(latch_key, None)
  8251. else:
  8252. drying_latch[latch_key] = new_latch
  8253. # Check temperature alarm (only if above threshold)
  8254. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8255. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8256. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8257. now = datetime.now(timezone.utc)
  8258. if (
  8259. last_alarm is None
  8260. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8261. ):
  8262. _ams_alarm_cooldown[cooldown_key] = now
  8263. logger.info(
  8264. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8265. f"{temperature}°C > {temp_alarm_threshold}°C"
  8266. )
  8267. try:
  8268. # Call different notification method based on AMS type
  8269. if is_ams_ht:
  8270. # The reported threshold has to be the one
  8271. # that fired, or the message says "> 35 °C"
  8272. # while firing at 45.
  8273. await notification_service.on_ams_ht_temperature_high(
  8274. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8275. )
  8276. else:
  8277. await notification_service.on_ams_temperature_high(
  8278. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8279. )
  8280. except Exception as e:
  8281. logger.warning("Failed to send temperature alarm: %s", e)
  8282. if drying_latch != drying_latch_before:
  8283. await _save_ams_drying_latch(db, drying_latch)
  8284. await db.commit()
  8285. if recorded_count > 0:
  8286. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8287. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8288. global _ams_cleanup_counter
  8289. _ams_cleanup_counter += 1
  8290. if _ams_cleanup_counter >= 288:
  8291. _ams_cleanup_counter = 0
  8292. # Get retention days from settings
  8293. from backend.app.models.settings import Settings
  8294. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8295. setting = result.scalar_one_or_none()
  8296. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8297. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8298. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8299. await db.commit()
  8300. if result.rowcount > 0:
  8301. logger.info(
  8302. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8303. )
  8304. # Wait until next recording interval
  8305. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8306. except asyncio.CancelledError:
  8307. break
  8308. except Exception as e:
  8309. logger.warning("AMS history recording failed: %s", e)
  8310. await asyncio.sleep(60) # Wait a bit before retrying
  8311. def start_ams_history_recording():
  8312. """Start the AMS history recording background task."""
  8313. global _ams_history_task
  8314. if _ams_history_task is None:
  8315. _ams_history_task = asyncio.create_task(record_ams_history())
  8316. logging.getLogger(__name__).info("AMS history recording started")
  8317. def stop_ams_history_recording():
  8318. """Stop the AMS history recording background task."""
  8319. global _ams_history_task
  8320. if _ams_history_task:
  8321. _ams_history_task.cancel()
  8322. _ams_history_task = None
  8323. logging.getLogger(__name__).info("AMS history recording stopped")
  8324. # Printer sensor history recording (nozzle / bed / chamber)
  8325. _printer_sensor_history_task: asyncio.Task | None = None
  8326. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8327. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8328. _printer_sensor_cleanup_counter = 0
  8329. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8330. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8331. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8332. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8333. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8334. _SENSOR_TARGET_KEYS = {
  8335. "nozzle": "nozzle_target",
  8336. "nozzle_2": "nozzle_2_target",
  8337. "bed": "bed_target",
  8338. "chamber": "chamber_target",
  8339. }
  8340. async def record_printer_sensor_history():
  8341. """Background task to record nozzle / bed / chamber readings.
  8342. Pulls from `state.temperatures` (already normalised across all printer
  8343. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8344. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8345. """
  8346. logger = logging.getLogger(__name__)
  8347. await asyncio.sleep(10)
  8348. while True:
  8349. try:
  8350. from backend.app.models.printer import Printer
  8351. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8352. from backend.app.models.settings import Settings
  8353. async with async_session() as db:
  8354. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8355. printers = result.scalars().all()
  8356. recorded_count = 0
  8357. for printer in printers:
  8358. state = printer_manager.get_status(printer.id)
  8359. if not state or not state.connected:
  8360. continue
  8361. temps = getattr(state, "temperatures", None) or {}
  8362. if not isinstance(temps, dict):
  8363. continue
  8364. for kind in _SENSOR_KINDS:
  8365. if kind not in temps:
  8366. continue
  8367. try:
  8368. value = float(temps[kind])
  8369. except (ValueError, TypeError):
  8370. continue
  8371. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8372. target_val: float | None = None
  8373. if target_raw is not None:
  8374. try:
  8375. target_val = float(target_raw)
  8376. except (ValueError, TypeError):
  8377. target_val = None
  8378. db.add(
  8379. PrinterSensorHistory(
  8380. printer_id=printer.id,
  8381. sensor_kind=kind,
  8382. value=value,
  8383. target=target_val,
  8384. )
  8385. )
  8386. recorded_count += 1
  8387. await db.commit()
  8388. if recorded_count > 0:
  8389. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8390. # Periodic cleanup — once every ~24h at this interval.
  8391. global _printer_sensor_cleanup_counter
  8392. _printer_sensor_cleanup_counter += 1
  8393. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8394. if _printer_sensor_cleanup_counter >= cleanup_every:
  8395. _printer_sensor_cleanup_counter = 0
  8396. result = await db.execute(
  8397. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8398. )
  8399. setting = result.scalar_one_or_none()
  8400. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8401. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8402. cleanup = await db.execute(
  8403. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8404. )
  8405. await db.commit()
  8406. if cleanup.rowcount > 0:
  8407. logger.info(
  8408. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8409. cleanup.rowcount,
  8410. retention_days,
  8411. )
  8412. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8413. except asyncio.CancelledError:
  8414. break
  8415. except Exception as e:
  8416. logger.warning("Printer sensor history recording failed: %s", e)
  8417. await asyncio.sleep(60)
  8418. def start_printer_sensor_history_recording():
  8419. global _printer_sensor_history_task
  8420. if _printer_sensor_history_task is None:
  8421. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8422. logging.getLogger(__name__).info("Printer sensor history recording started")
  8423. def stop_printer_sensor_history_recording():
  8424. global _printer_sensor_history_task
  8425. if _printer_sensor_history_task:
  8426. _printer_sensor_history_task.cancel()
  8427. _printer_sensor_history_task = None
  8428. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8429. # Printer runtime tracking
  8430. _runtime_tracking_task: asyncio.Task | None = None
  8431. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8432. async def track_printer_runtime():
  8433. """Background task to track printer active runtime (RUNNING state only).
  8434. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8435. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8436. which track mechanical wear. Pause time has no motion and no wear, so
  8437. counting it inflates maintenance warnings (#1521).
  8438. """
  8439. logger = logging.getLogger(__name__)
  8440. # Wait for MQTT connections to establish on startup
  8441. await asyncio.sleep(15)
  8442. while True:
  8443. try:
  8444. from backend.app.models.printer import Printer
  8445. # Fetch printer IDs in a short-lived read-only session
  8446. async with async_session() as db:
  8447. result = await db.execute(
  8448. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8449. Printer.is_active.is_(True)
  8450. )
  8451. )
  8452. printer_rows = result.all()
  8453. now = datetime.now(timezone.utc)
  8454. updated_count = 0
  8455. # Update each printer in its own short session to minimise write-lock
  8456. # hold time and avoid blocking critical commits like queue status
  8457. # updates (#897).
  8458. for pid, pname, runtime_secs, last_update in printer_rows:
  8459. state = printer_manager.get_status(pid)
  8460. if not state:
  8461. logger.debug("[%s] Runtime tracking: no state available", pname)
  8462. continue
  8463. if not state.connected:
  8464. logger.debug("[%s] Runtime tracking: not connected", pname)
  8465. continue
  8466. needs_commit = False
  8467. new_runtime = runtime_secs
  8468. new_last_update = last_update
  8469. if state.state == "RUNNING":
  8470. if last_update:
  8471. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8472. elapsed = (now - lu).total_seconds()
  8473. if elapsed > 0:
  8474. new_runtime = runtime_secs + int(elapsed)
  8475. updated_count += 1
  8476. needs_commit = True
  8477. logger.debug(
  8478. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8479. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8480. )
  8481. else:
  8482. needs_commit = True
  8483. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8484. new_last_update = now
  8485. else:
  8486. if last_update is not None:
  8487. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8488. new_last_update = None
  8489. needs_commit = True
  8490. if needs_commit:
  8491. try:
  8492. async with async_session() as db:
  8493. result = await db.execute(select(Printer).where(Printer.id == pid))
  8494. printer = result.scalar_one_or_none()
  8495. if printer:
  8496. printer.runtime_seconds = new_runtime
  8497. printer.last_runtime_update = new_last_update
  8498. await db.commit()
  8499. except Exception as e:
  8500. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8501. if updated_count > 0:
  8502. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8503. except asyncio.CancelledError:
  8504. logger.info("Runtime tracking cancelled")
  8505. break
  8506. except Exception as e:
  8507. logger.warning("Runtime tracking failed: %s", e)
  8508. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8509. def start_runtime_tracking():
  8510. """Start the printer runtime tracking background task."""
  8511. global _runtime_tracking_task
  8512. if _runtime_tracking_task is None:
  8513. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8514. logging.getLogger(__name__).info("Printer runtime tracking started")
  8515. def stop_runtime_tracking():
  8516. """Stop the printer runtime tracking background task."""
  8517. global _runtime_tracking_task
  8518. if _runtime_tracking_task:
  8519. _runtime_tracking_task.cancel()
  8520. _runtime_tracking_task = None
  8521. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8522. # SpoolBuddy device watchdog
  8523. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8524. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8525. async def _spoolbuddy_watchdog_loop():
  8526. """Periodic check for SpoolBuddy devices that have gone offline."""
  8527. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8528. while True:
  8529. try:
  8530. await spoolbuddy_watchdog()
  8531. except asyncio.CancelledError:
  8532. break
  8533. except Exception as e:
  8534. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8535. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8536. def start_spoolbuddy_watchdog():
  8537. global _spoolbuddy_watchdog_task
  8538. if _spoolbuddy_watchdog_task is None:
  8539. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8540. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8541. def stop_spoolbuddy_watchdog():
  8542. global _spoolbuddy_watchdog_task
  8543. if _spoolbuddy_watchdog_task:
  8544. _spoolbuddy_watchdog_task.cancel()
  8545. _spoolbuddy_watchdog_task = None
  8546. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8547. # Dead-MQTT-session recovery
  8548. #
  8549. # check_staleness() covers the "connected but silent" half-broken session. It
  8550. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8551. # is the only thing left watching at that point. When paho stops making
  8552. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8553. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8554. # offline with the UI open the whole time, recovered only when something
  8555. # happened to nudge it.
  8556. #
  8557. # This loop is that backstop. It only touches printers that had a working
  8558. # session and lost it, and only when the MQTT port still answers — a printer
  8559. # that is simply switched off is left to paho, since rebuilding a client
  8560. # against an unreachable host achieves nothing and would fill the log every
  8561. # night.
  8562. _connection_watchdog_task: asyncio.Task | None = None
  8563. CONNECTION_WATCHDOG_INTERVAL = 60
  8564. # How long a printer must have been silent before we stop trusting paho.
  8565. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8566. # so a session that is recovering on its own is never interrupted.
  8567. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8568. # Per-printer floor between rebuild attempts.
  8569. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8570. _connection_watchdog_last_attempt: dict[int, float] = {}
  8571. async def _recover_dead_printer_sessions() -> int:
  8572. """Rebuild MQTT clients that have been offline too long to still be trying.
  8573. Returns the number of printers a rebuild was attempted for (for tests and
  8574. for the caller's logging). Never raises: one unreachable printer must not
  8575. stop the sweep for the rest of the farm.
  8576. """
  8577. logger = logging.getLogger(__name__)
  8578. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8579. now = time.monotonic()
  8580. recovered = 0
  8581. for printer_id, client in list(printer_manager._clients.items()):
  8582. try:
  8583. if client.state.connected:
  8584. _connection_watchdog_last_attempt.pop(printer_id, None)
  8585. continue
  8586. # Time since the last inbound message is the age of the last known
  8587. # good session — no extra bookkeeping needed, and it is the same
  8588. # clock is_stale() reads. 0 means this client has never had one:
  8589. # that is the initial-connect path, where paho retrying is the
  8590. # correct and only behaviour, so leave it be.
  8591. last_msg = client._last_message_time
  8592. if not last_msg:
  8593. continue
  8594. offline_for = time.time() - last_msg
  8595. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8596. continue
  8597. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8598. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8599. continue
  8600. if not await check_port(client.ip_address, PORT_MQTT):
  8601. # Switched off, unplugged, or off the network. Paho's retry is
  8602. # the right handler; say so at debug level and move on.
  8603. logger.debug(
  8604. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8605. "— leaving the reconnect to paho",
  8606. printer_id,
  8607. offline_for,
  8608. )
  8609. _connection_watchdog_last_attempt[printer_id] = now
  8610. continue
  8611. _connection_watchdog_last_attempt[printer_id] = now
  8612. recovered += 1
  8613. logger.warning(
  8614. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8615. "rebuilding the client with a fresh session (last connect error: %s)",
  8616. printer_id,
  8617. offline_for,
  8618. PORT_MQTT,
  8619. client.last_connect_error or "none recorded",
  8620. )
  8621. # Async context, so this takes the hard-reset path: fresh client_id,
  8622. # paho's QoS 1 queue dropped. That matters — a project_file left
  8623. # unacked on the dead session would otherwise replay into the new
  8624. # one and trip 0500_4003 on the printer (#1136).
  8625. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8626. except Exception as e:
  8627. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8628. return recovered
  8629. async def _connection_watchdog_loop():
  8630. logger = logging.getLogger(__name__)
  8631. # Let the initial connects settle before judging anyone offline.
  8632. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8633. while True:
  8634. try:
  8635. await _recover_dead_printer_sessions()
  8636. except asyncio.CancelledError:
  8637. break
  8638. except Exception as e:
  8639. logger.warning("Connection watchdog sweep failed: %s", e)
  8640. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8641. def start_connection_watchdog():
  8642. global _connection_watchdog_task
  8643. if _connection_watchdog_task is None:
  8644. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8645. logging.getLogger(__name__).info("Printer connection watchdog started")
  8646. def stop_connection_watchdog():
  8647. global _connection_watchdog_task
  8648. if _connection_watchdog_task:
  8649. _connection_watchdog_task.cancel()
  8650. _connection_watchdog_task = None
  8651. _connection_watchdog_last_attempt.clear()
  8652. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8653. # Camera stream orphan cleanup
  8654. _camera_cleanup_task: asyncio.Task | None = None
  8655. CAMERA_CLEANUP_INTERVAL = 60
  8656. async def _camera_cleanup_loop():
  8657. """Periodically clean up orphaned ffmpeg processes."""
  8658. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8659. while True:
  8660. try:
  8661. await cleanup_orphaned_streams()
  8662. except asyncio.CancelledError:
  8663. break
  8664. except Exception as e:
  8665. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8666. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8667. def start_camera_cleanup():
  8668. global _camera_cleanup_task
  8669. if _camera_cleanup_task is None:
  8670. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8671. logging.getLogger(__name__).info("Camera stream cleanup started")
  8672. def stop_camera_cleanup():
  8673. global _camera_cleanup_task
  8674. if _camera_cleanup_task:
  8675. _camera_cleanup_task.cancel()
  8676. _camera_cleanup_task = None
  8677. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8678. # ---------------------------------------------------------------------------
  8679. # Expected-print TTL eviction
  8680. # ---------------------------------------------------------------------------
  8681. def _evict_stale_expected_prints() -> None:
  8682. """Remove entries from _expected_prints / _expected_print_creators that are
  8683. older than _EXPECTED_PRINT_TTL_SECONDS.
  8684. This prevents unbounded growth when a print is registered (via
  8685. register_expected_print) but on_print_start never fires — e.g. because the
  8686. printer disconnects, the app restarts, or the print is started directly from
  8687. the printer panel without going through the queue.
  8688. """
  8689. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8690. # (e.g. NTP sync, DST changes).
  8691. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8692. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8693. if not stale_keys:
  8694. return
  8695. evicted_archive_ids: set[int] = set()
  8696. for key in stale_keys:
  8697. archive_id = _expected_prints.pop(key, None)
  8698. if archive_id is not None:
  8699. evicted_archive_ids.add(archive_id)
  8700. _expected_print_creators.pop(key, None)
  8701. _expected_print_registered_at.pop(key, None)
  8702. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8703. # that have no remaining live keys in _expected_prints (all variants
  8704. # were just evicted) and are not printing right now. Print start pops
  8705. # only the names the printer reported, so the "<base>.gcode" variant
  8706. # outlives it; without the printing check its eviction two hours after
  8707. # dispatch threw away a running print's plate, AMS mapping and cost
  8708. # centre, which completion still reads (#3275).
  8709. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  8710. for archive_id in evicted_archive_ids:
  8711. if archive_id not in live_archive_ids:
  8712. _print_ams_mappings.pop(archive_id, None)
  8713. _print_cost_center_ids.pop(archive_id, None)
  8714. _print_plate_ids.pop(archive_id, None)
  8715. logging.getLogger(__name__).info(
  8716. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8717. )
  8718. async def _expected_prints_cleanup_loop() -> None:
  8719. """Background task: periodically evict stale expected-print entries."""
  8720. while True:
  8721. try:
  8722. _evict_stale_expected_prints()
  8723. except asyncio.CancelledError:
  8724. raise
  8725. except Exception as e:
  8726. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8727. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8728. def start_expected_prints_cleanup() -> None:
  8729. global _expected_prints_cleanup_task
  8730. if _expected_prints_cleanup_task is None:
  8731. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8732. logging.getLogger(__name__).info("Expected prints cleanup started")
  8733. def stop_expected_prints_cleanup() -> None:
  8734. global _expected_prints_cleanup_task
  8735. if _expected_prints_cleanup_task:
  8736. _expected_prints_cleanup_task.cancel()
  8737. _expected_prints_cleanup_task = None
  8738. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8739. # ---------------------------------------------------------------------------
  8740. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8741. # ---------------------------------------------------------------------------
  8742. _auth_cleanup_task: asyncio.Task | None = None
  8743. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8744. async def _run_auth_cleanup() -> None:
  8745. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8746. from backend.app.core.database import async_session
  8747. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8748. from backend.app.models.user_totp import UserTOTP
  8749. now = datetime.now(timezone.utc)
  8750. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8751. try:
  8752. async with async_session() as db:
  8753. stale_cutoff = now - timedelta(hours=1)
  8754. result = await db.execute(
  8755. select(UserTOTP).where(
  8756. UserTOTP.is_enabled.is_(False),
  8757. UserTOTP.created_at < stale_cutoff,
  8758. )
  8759. )
  8760. stale_records = result.scalars().all()
  8761. if stale_records:
  8762. for rec in stale_records:
  8763. await db.delete(rec)
  8764. await db.commit()
  8765. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8766. except Exception as e:
  8767. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8768. # Remove expired revoked-JTI entries (they are no longer needed once the
  8769. # original token's exp has passed — the token would be rejected by JWT
  8770. # signature verification regardless).
  8771. try:
  8772. async with async_session() as db:
  8773. await db.execute(
  8774. delete(AuthEphemeralToken).where(
  8775. AuthEphemeralToken.token_type == "revoked_jti",
  8776. AuthEphemeralToken.expires_at < now,
  8777. )
  8778. )
  8779. await db.commit()
  8780. except Exception as e:
  8781. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8782. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8783. # Events outside this window can never affect rate-limit decisions — they only
  8784. # consume DB space. Use the same window constant as the rate limiter so the
  8785. # two are always in sync.
  8786. try:
  8787. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8788. async with async_session() as db:
  8789. await db.execute(
  8790. delete(AuthRateLimitEvent).where(
  8791. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8792. )
  8793. )
  8794. await db.commit()
  8795. except Exception as e:
  8796. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8797. async def _auth_cleanup_loop() -> None:
  8798. """Periodic background task: run auth cleanup every hour."""
  8799. while True:
  8800. try:
  8801. await _run_auth_cleanup()
  8802. except asyncio.CancelledError:
  8803. break
  8804. except Exception as e:
  8805. logging.warning("Auth cleanup loop error: %s", e)
  8806. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8807. def start_auth_cleanup() -> None:
  8808. global _auth_cleanup_task
  8809. if _auth_cleanup_task is None:
  8810. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8811. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8812. def stop_auth_cleanup() -> None:
  8813. global _auth_cleanup_task
  8814. if _auth_cleanup_task:
  8815. _auth_cleanup_task.cancel()
  8816. _auth_cleanup_task = None
  8817. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8818. @asynccontextmanager
  8819. async def lifespan(app: FastAPI):
  8820. # Startup
  8821. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8822. # anything else can spawn tasks that might trip it.
  8823. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8824. install_proactor_reset_filter()
  8825. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  8826. # what turned descriptor exhaustion into a corrupted database (#2883).
  8827. from backend.app.core.fd_limit import raise_open_file_limit
  8828. raise_open_file_limit()
  8829. # Before init_db, so the warning is near the top of the log rather than
  8830. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8831. warn_if_running_on_uvloop()
  8832. await init_db()
  8833. # Browser download tokens expire after five minutes. Remove abandoned
  8834. # prepared ZIPs at startup as well as before each new preparation so a
  8835. # quiet appliance cannot retain an unusable bundle indefinitely.
  8836. try:
  8837. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8838. await prune_stale_printer_file_bundles()
  8839. except Exception as exc:
  8840. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8841. # After migrations, so the is_env_managed column exists. Never raises --
  8842. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8843. # startup (see apply_env_oidc_provider).
  8844. from backend.app.core.oidc_env import apply_env_oidc_provider
  8845. async with async_session() as oidc_db:
  8846. await apply_env_oidc_provider(oidc_db)
  8847. # Close out batches that finished before `completed` was a reachable status
  8848. # (#342). Without this the Batches tab opens on every batch created since
  8849. # the feature shipped, all still marked active. Never blocks startup.
  8850. try:
  8851. from backend.app.services.print_batch import backfill_batch_statuses
  8852. async with async_session() as batch_db:
  8853. await backfill_batch_statuses(batch_db)
  8854. except Exception as exc:
  8855. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8856. # Register an app-scoped httpx client for Bambu Cloud services so
  8857. # per-request BambuCloudService instances reuse the same connection pool
  8858. # (important for routes like /cloud/filament-info that chain many
  8859. # get_setting_detail calls). The shared client stores no region/token
  8860. # state, so the per-request ownership pattern that fixed the region-bleed
  8861. # bug is preserved.
  8862. import httpx as _httpx
  8863. from backend.app.services.bambu_cloud import set_shared_http_client
  8864. from backend.app.services.model_providers.makerworld.service import (
  8865. set_shared_http_client as set_shared_makerworld_http_client,
  8866. )
  8867. from backend.app.services.orca_cloud import (
  8868. set_shared_http_client as set_shared_orca_http_client,
  8869. )
  8870. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8871. set_shared_http_client(_shared_cloud_http_client)
  8872. # Reuse the same connection pool for MakerWorld — different host, same
  8873. # keep-alive pool saves a TLS handshake per request.
  8874. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8875. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8876. # each spun up (and never closed) its own client, leaking sockets.
  8877. set_shared_orca_http_client(_shared_cloud_http_client)
  8878. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8879. # This can happen when a print was cancelled mid-print on versions before this fix.
  8880. try:
  8881. async with async_session() as db:
  8882. from backend.app.models.print_queue import PrintQueueItem
  8883. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8884. aborted_items = result.scalars().all()
  8885. if aborted_items:
  8886. for item in aborted_items:
  8887. item.status = "cancelled"
  8888. await db.commit()
  8889. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8890. except Exception as e:
  8891. logging.warning("Failed to fix aborted queue items: %s", e)
  8892. # Restore debug logging state from previous session
  8893. await init_debug_logging()
  8894. # Set up printer manager callbacks
  8895. loop = asyncio.get_event_loop()
  8896. printer_manager.set_event_loop(loop)
  8897. printer_manager.set_status_change_callback(on_printer_status_change)
  8898. printer_manager.set_print_start_callback(on_print_start)
  8899. printer_manager.set_print_complete_callback(on_print_complete)
  8900. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8901. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8902. printer_manager.set_ams_change_callback(on_ams_change)
  8903. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8904. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8905. await printer_manager.load_awaiting_plate_clear_from_db()
  8906. # Layer change callback for external camera timelapse
  8907. async def on_layer_change(printer_id: int, layer_num: int):
  8908. """Capture timelapse frame on layer change + first layer notification."""
  8909. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8910. await tl_layer_change(printer_id, layer_num)
  8911. # #1867: bank a recent in-print frame so the finish-photo path has a
  8912. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8913. # #2547 added `on_print_progress` as a second driver — this one alone
  8914. # stops firing once the final layer begins.
  8915. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8916. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8917. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8918. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8919. # nozzle clean), so a bare layer_num check can fire minutes before the
  8920. # first real extrusion. We require gcode_state == RUNNING and
  8921. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8922. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8923. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8924. # edge fires later; _first_layer_notified stays clear until we actually send
  8925. # so a deferred re-evaluation can win. See issue #1837.
  8926. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8927. client = printer_manager.get_client(printer_id)
  8928. state = client.state if client else None
  8929. if not state or state.state != "RUNNING":
  8930. return
  8931. if state.mc_print_sub_stage not in (None, 0):
  8932. return
  8933. _first_layer_notified[printer_id] = True
  8934. try:
  8935. async with async_session() as db:
  8936. from backend.app.models.printer import Printer
  8937. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8938. printer = result.scalar_one_or_none()
  8939. if not printer:
  8940. return
  8941. printer_name = printer.name
  8942. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8943. total_layers = state.total_layers if state else 0
  8944. image_data = await _capture_snapshot_for_notification(
  8945. printer_id, printer, logging.getLogger(__name__)
  8946. )
  8947. await notification_service.on_first_layer_complete(
  8948. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8949. )
  8950. except Exception as e:
  8951. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8952. printer_manager.set_layer_change_callback(on_layer_change)
  8953. async def on_print_progress(printer_id: int, percent: int):
  8954. """#2547: keep the in-print frame bank fresh through the final layer.
  8955. `on_layer_change` stops the moment the last layer starts, which on the
  8956. H2C capture that closed #2547 left the bank stale for the three minutes
  8957. that layer took. Progress is the only field that keeps advancing there,
  8958. and it freezes before the End G-code runs — so banking on it stays
  8959. inside the print and never sees a swapped plate.
  8960. """
  8961. client = printer_manager.get_client(printer_id)
  8962. state = client.state if client else None
  8963. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8964. printer_manager.set_print_progress_callback(on_print_progress)
  8965. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8966. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8967. waiter = _bed_cool_waiters.get(printer_id)
  8968. if not waiter:
  8969. return
  8970. threshold = waiter["threshold"]
  8971. if bed_temp > threshold:
  8972. return
  8973. # Bed is at or below threshold — fire notification and remove waiter
  8974. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8975. if not waiter_info:
  8976. return # Another callback already handled it
  8977. bed_cool_logger = logging.getLogger(__name__)
  8978. bed_cool_logger.info(
  8979. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8980. bed_temp,
  8981. printer_id,
  8982. threshold,
  8983. )
  8984. try:
  8985. printer_info = printer_manager.get_printer(printer_id)
  8986. p_name = printer_info.name if printer_info else "Unknown"
  8987. async with async_session() as db:
  8988. await notification_service.on_bed_cooled(
  8989. printer_id=printer_id,
  8990. printer_name=p_name,
  8991. bed_temp=bed_temp,
  8992. threshold=threshold,
  8993. filename=waiter_info["filename"],
  8994. db=db,
  8995. )
  8996. except Exception as e:
  8997. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8998. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8999. async def on_drying_complete(printer_id: int, ams_id: int):
  9000. """Smart-plug auto-off-after-drying trigger (#1349).
  9001. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9002. manager walks all plugs linked to this printer and turns off only
  9003. the ones with ``auto_off_after_drying`` enabled, after their
  9004. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9005. dual-AMS dry that ends within the same MQTT push) call this once
  9006. per unit — the manager's ``_cancel_pending_off`` collapses
  9007. repeated scheduling on the same plug to one timer, so duplicate
  9008. fires are safe.
  9009. """
  9010. try:
  9011. async with async_session() as db:
  9012. await smart_plug_manager.on_drying_complete(printer_id, db)
  9013. except Exception as e:
  9014. logging.getLogger(__name__).warning(
  9015. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9016. printer_id,
  9017. ams_id,
  9018. e,
  9019. )
  9020. printer_manager.set_drying_complete_callback(on_drying_complete)
  9021. async def on_drying_cycle_end(printer_id: int, cycle):
  9022. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9023. from backend.app.services.spool_drying import record_drying_cycle
  9024. try:
  9025. async with async_session() as db:
  9026. await record_drying_cycle(db, printer_id, cycle)
  9027. except Exception as e:
  9028. logging.getLogger(__name__).warning(
  9029. "Failed to record drying for printer %d (AMS %d): %s",
  9030. printer_id,
  9031. cycle.ams_id,
  9032. e,
  9033. )
  9034. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9035. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9036. """Surface the read-back result of a spool assignment to the UI (#2582).
  9037. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9038. echoed back the filament id we pushed. We relay that as a websocket
  9039. event so the frontend can toast "loaded" / "assignment didn't take"
  9040. instead of the historic silent fire-and-forget, which made the
  9041. AMS→Studio hand-off feel random to users.
  9042. """
  9043. try:
  9044. from backend.app.services.spool_assignment_notifications import (
  9045. _slot_label_from_global_tray,
  9046. )
  9047. if ams_id == 255:
  9048. global_id = 254 + tray_id
  9049. elif ams_id >= 128:
  9050. global_id = ams_id
  9051. else:
  9052. global_id = ams_id * 4 + tray_id
  9053. slot_label = _slot_label_from_global_tray(global_id)
  9054. printer_info = printer_manager.get_printer(printer_id)
  9055. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9056. await ws_manager.broadcast(
  9057. {
  9058. "type": "spool_assignment_verified",
  9059. "printer_id": printer_id,
  9060. "printer_name": printer_name,
  9061. "ams_id": ams_id,
  9062. "tray_id": tray_id,
  9063. "slot": slot_label,
  9064. "verified": verified,
  9065. # Present on success: False means the filament setting landed
  9066. # but the K-profile (cali_idx) did not — the reporter's exact
  9067. # "loaded but no flow profile" symptom.
  9068. "kprofile_applied": detail.get("kprofile_applied", True),
  9069. # Present on failure: whether any tray telemetry was seen in
  9070. # the window (distinguishes "printer silent" from "printer
  9071. # stored something else").
  9072. "saw_tray": detail.get("saw_tray", False),
  9073. }
  9074. )
  9075. except Exception as e:
  9076. logging.getLogger(__name__).warning(
  9077. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9078. printer_id,
  9079. ams_id,
  9080. tray_id,
  9081. e,
  9082. )
  9083. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9084. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9085. """Persist a mid-print tray change for completion-time attribution.
  9086. AMS filament backup switches trays without telling the slicer, so the
  9087. tray-change log is the only record of which spool fed which layers.
  9088. Keeping it only in memory meant a restart mid-print charged everything
  9089. to the tray that finished the job.
  9090. """
  9091. try:
  9092. from backend.app.services.usage_tracker import record_tray_change
  9093. async with async_session() as db:
  9094. await record_tray_change(db, printer_id, tray_global, layer_num)
  9095. except Exception as e:
  9096. logging.getLogger(__name__).warning(
  9097. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9098. printer_id,
  9099. tray_global,
  9100. layer_num,
  9101. e,
  9102. )
  9103. printer_manager.set_tray_change_callback(on_tray_change)
  9104. # Initialize MQTT relay from settings
  9105. async with async_session() as db:
  9106. from backend.app.api.routes.settings import get_setting
  9107. mqtt_settings = {
  9108. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9109. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9110. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9111. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9112. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9113. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9114. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9115. }
  9116. await mqtt_relay.configure(mqtt_settings)
  9117. # Restore MQTT smart plug subscriptions
  9118. if mqtt_settings.get("mqtt_enabled"):
  9119. from backend.app.models.smart_plug import SmartPlug
  9120. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9121. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9122. mqtt_plugs = result.scalars().all()
  9123. restored = 0
  9124. for plug in mqtt_plugs:
  9125. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9126. restored += 1
  9127. if restored:
  9128. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9129. # Connect to all active printers
  9130. async with async_session() as db:
  9131. await init_printer_connections(db)
  9132. # Auto-connect to Spoolman if enabled
  9133. async with async_session() as db:
  9134. from backend.app.api.routes.settings import get_setting
  9135. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9136. spoolman_url = await get_setting(db, "spoolman_url")
  9137. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9138. try:
  9139. client = await init_spoolman_client(spoolman_url)
  9140. if await client.health_check():
  9141. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9142. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9143. field_ok = await client.ensure_tag_extra_field()
  9144. if not field_ok:
  9145. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9146. # Register the BambuStudio slicer-preset fields used by the
  9147. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9148. # unknown extra keys, so these must exist before any update
  9149. # that touches them.
  9150. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9151. if not await client.ensure_extra_field(field_name):
  9152. logging.warning(
  9153. "Spoolman extra field %r registration failed — "
  9154. "spool slicer-preset edits will return 502",
  9155. field_name,
  9156. )
  9157. else:
  9158. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9159. except Exception as e:
  9160. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9161. # Start the print scheduler
  9162. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9163. # Start the smart plug scheduler for time-based on/off
  9164. smart_plug_manager.start_scheduler()
  9165. # Start the Home Assistant sensor poller (#1148)
  9166. ha_sensor_manager.start()
  9167. location_ha_sensor_manager.start()
  9168. # Resume any pending auto-offs that were interrupted by restart
  9169. await smart_plug_manager.resume_pending_auto_offs()
  9170. # Start the notification digest scheduler
  9171. notification_service.start_digest_scheduler()
  9172. notify_live_activities.start()
  9173. notify_widgets.start()
  9174. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9175. # provider in reactions/both mode; the notification routes resync them.
  9176. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9177. # until the next provider save, not the whole startup.
  9178. try:
  9179. await telegram_reaction_poller.start()
  9180. except Exception as e:
  9181. logging.warning("Telegram reaction poller did not start: %s", e)
  9182. # Start the GitHub backup scheduler
  9183. await github_backup_service.start_scheduler()
  9184. # Start the local backup scheduler
  9185. await local_backup_service.start_scheduler()
  9186. await obico_detection_service.start()
  9187. # Start the library trash sweeper (#1008)
  9188. await library_trash_service.start_scheduler()
  9189. # Start the archive auto-purge sweeper (#1008 follow-up)
  9190. await archive_purge_service.start_scheduler()
  9191. # Start AMS history recording
  9192. start_ams_history_recording()
  9193. # Start printer sensor (nozzle / bed / chamber) history recording
  9194. start_printer_sensor_history_recording()
  9195. # Start printer runtime tracking
  9196. start_runtime_tracking()
  9197. # Start SpoolBuddy device watchdog
  9198. start_spoolbuddy_watchdog()
  9199. # Start camera stream orphan cleanup
  9200. start_camera_cleanup()
  9201. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9202. start_connection_watchdog()
  9203. # One-shot sweep for timelapse session directories orphaned by a crash
  9204. # or restart that happened mid-print (in-memory session tracking can't
  9205. # survive that, and nothing else reaps the leftover frames/output file)
  9206. try:
  9207. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9208. removed = cleanup_orphaned_timelapse_sessions()
  9209. if removed:
  9210. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9211. except Exception as e:
  9212. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9213. # Start expected-print TTL eviction (prevents memory leak when prints are
  9214. # registered but on_print_start never fires)
  9215. start_expected_prints_cleanup()
  9216. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9217. start_auth_cleanup()
  9218. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9219. from backend.app.services import announcements as announcements_service
  9220. announcements_service.start()
  9221. from backend.app.services.printer_media import start_printer_download_cleanup
  9222. start_printer_download_cleanup()
  9223. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9224. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9225. from backend.app.services.loop_watchdog import start_loop_watchdog
  9226. start_loop_watchdog()
  9227. # Initialize virtual printer manager and sync from DB
  9228. from backend.app.services.virtual_printer import virtual_printer_manager
  9229. virtual_printer_manager.set_session_factory(async_session)
  9230. virtual_printer_manager.set_printer_manager(printer_manager)
  9231. try:
  9232. await virtual_printer_manager.sync_from_db()
  9233. logging.info("Virtual printer manager synced from database")
  9234. except Exception as e:
  9235. logging.warning("Failed to sync virtual printers: %s", e)
  9236. yield
  9237. # Shutdown
  9238. print_scheduler.stop()
  9239. smart_plug_manager.stop_scheduler()
  9240. ha_sensor_manager.stop()
  9241. location_ha_sensor_manager.stop()
  9242. notification_service.stop_digest_scheduler()
  9243. await notify_live_activities.close()
  9244. await notify_widgets.close()
  9245. await telegram_reaction_poller.aclose()
  9246. github_backup_service.stop_scheduler()
  9247. local_backup_service.stop_scheduler()
  9248. library_trash_service.stop_scheduler()
  9249. archive_purge_service.stop_scheduler()
  9250. obico_detection_service.stop()
  9251. stop_ams_history_recording()
  9252. stop_printer_sensor_history_recording()
  9253. stop_runtime_tracking()
  9254. stop_spoolbuddy_watchdog()
  9255. stop_camera_cleanup()
  9256. stop_connection_watchdog()
  9257. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9258. stop_loop_watchdog()
  9259. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9260. # cleanly rather than waiting on a queue that nothing will ever fill.
  9261. try:
  9262. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9263. await shutdown_all_broadcasters()
  9264. except Exception as e:
  9265. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9266. stop_expected_prints_cleanup()
  9267. stop_auth_cleanup()
  9268. from backend.app.services import announcements as announcements_service
  9269. announcements_service.stop()
  9270. from backend.app.services.printer_media import stop_printer_download_cleanup
  9271. await stop_printer_download_cleanup()
  9272. printer_manager.disconnect_all()
  9273. slot_unlink_grace.reset()
  9274. await close_spoolman_client()
  9275. # Stop all virtual printer services
  9276. await virtual_printer_manager.stop_all()
  9277. await mqtt_smart_plug_service.disconnect(timeout=2)
  9278. await mqtt_relay.disconnect(timeout=2)
  9279. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9280. set_shared_http_client(None)
  9281. set_shared_makerworld_http_client(None)
  9282. set_shared_orca_http_client(None)
  9283. await _shared_cloud_http_client.aclose()
  9284. # Checkpoint WAL (SQLite only) and close all database connections
  9285. from backend.app.core.db_dialect import is_sqlite
  9286. if is_sqlite():
  9287. try:
  9288. async with engine.begin() as conn:
  9289. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9290. logging.info("WAL checkpoint completed")
  9291. except Exception as e:
  9292. logging.warning("WAL checkpoint failed: %s", e)
  9293. await engine.dispose()
  9294. app = FastAPI(
  9295. title=app_settings.app_name,
  9296. description="Archive and manage Bambu Lab 3MF files",
  9297. version=APP_VERSION,
  9298. lifespan=lifespan,
  9299. )
  9300. # =============================================================================
  9301. # Authentication Middleware - Secures ALL API routes by default
  9302. # =============================================================================
  9303. # Public routes that don't require authentication even when auth is enabled
  9304. PUBLIC_API_ROUTES = {
  9305. # Auth routes needed before/during login
  9306. "/api/v1/auth/status",
  9307. "/api/v1/auth/login",
  9308. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9309. # Advanced auth status needed for login page
  9310. "/api/v1/auth/advanced-auth/status",
  9311. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9312. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9313. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9314. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9315. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9316. # OIDC routes that must be reachable without a JWT
  9317. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9318. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9319. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9320. # Connected apps: the app's server swaps a code for the user's identity,
  9321. # authenticated by its client secret rather than a login token.
  9322. "/api/v1/connect/token",
  9323. # Version check for updates (no sensitive data)
  9324. "/api/v1/updates/version",
  9325. # Metrics endpoint handles its own prometheus_token authentication
  9326. "/api/v1/metrics",
  9327. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9328. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9329. # hostname / timezone / locale and the chrony NTP-gate state. The
  9330. # response contains user-set defaults and a public sync flag — no
  9331. # secrets. Without this entry the global auth middleware returns 401
  9332. # before the route handler runs, regardless of the route's own
  9333. # "no auth required" intent.
  9334. "/api/v1/system/appliance",
  9335. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9336. # authenticates with a long-lived ``camwall``-scoped token in the query
  9337. # string — exactly like the camera streams two lists below, and for the same
  9338. # reason (no header to put a JWT in). "Public" here only means the middleware
  9339. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9340. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9341. # plain ``camera_stream`` token does NOT open this door.
  9342. "/api/v1/camwall/printers",
  9343. # Overlay branding: the route enforces overlay-scoped token authentication.
  9344. "/api/v1/overlay-branding/logo",
  9345. }
  9346. # Route prefixes that are public (for routes with dynamic segments)
  9347. PUBLIC_API_PREFIXES = [
  9348. # WebSocket connections handle their own auth
  9349. "/api/v1/ws",
  9350. # OIDC authorize redirects — include provider_id in path
  9351. "/api/v1/auth/oidc/authorize/",
  9352. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9353. # a phone with no session, so no header can carry a JWT — the single-use
  9354. # capability token in the path IS the credential (same reasoning as the
  9355. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9356. # good/reject on the one archive the token was minted for.
  9357. "/api/v1/archives/confirm/",
  9358. ]
  9359. # Route patterns that are public (read-only display data)
  9360. # These are checked with "in path" - needed because browsers load images/videos
  9361. # via <img src> and <video src> which don't include Authorization headers
  9362. PUBLIC_API_PATTERNS = [
  9363. # Thumbnails
  9364. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9365. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9366. # Images and media
  9367. "/photos/", # /archives/{id}/photos/{filename}
  9368. "/project-image/", # /archives/{id}/project-image/{path}
  9369. "/qrcode", # /archives/{id}/qrcode
  9370. "/timelapse", # /archives/{id}/timelapse (video)
  9371. "/cover", # /printers/{id}/cover
  9372. "/icon", # /external-links/{id}/icon
  9373. # Camera (streams loaded via <img> tag)
  9374. "/camera/stream", # /printers/{id}/camera/stream
  9375. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9376. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9377. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9378. # string (same reasoning as the camera streams above — no header to carry a
  9379. # JWT). "Public" only means the middleware steps aside; the route still runs
  9380. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9381. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9382. "/overlay-status", # /printers/{id}/overlay-status
  9383. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9384. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9385. # download token in the URL path instead.
  9386. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9387. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9388. # and these patterns match by substring. Without its own entry the middleware
  9389. # 401s the slicer's header-less request before the route's token check runs,
  9390. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9391. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9392. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9393. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9394. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9395. ]
  9396. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9397. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9398. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9399. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9400. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9401. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9402. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9403. Invalid entries are dropped with a warning rather than failing startup, so
  9404. a typo in one origin doesn't take the whole deployment down.
  9405. """
  9406. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9407. if not raw:
  9408. return ()
  9409. valid: list[str] = []
  9410. for item in raw.split(","):
  9411. candidate = item.strip()
  9412. if not candidate:
  9413. continue
  9414. try:
  9415. parsed = urlparse(candidate)
  9416. except ValueError as e:
  9417. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9418. continue
  9419. if parsed.scheme not in ("http", "https"):
  9420. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9421. continue
  9422. if not parsed.netloc:
  9423. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9424. continue
  9425. if parsed.path and parsed.path != "/":
  9426. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9427. continue
  9428. if parsed.query or parsed.fragment:
  9429. _security_headers_logger.warning(
  9430. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9431. )
  9432. continue
  9433. if "*" in parsed.netloc:
  9434. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9435. continue
  9436. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9437. if valid:
  9438. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9439. return tuple(valid)
  9440. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9441. def _frame_ancestors(default_value: str) -> str:
  9442. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9443. ``default_value`` is the strict directive used when the operator has not
  9444. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9445. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9446. Settings URL builder's preview). When trusted origins
  9447. are configured, ``'self'`` is always included so same-origin embedding never
  9448. breaks even if an operator forgets to add their own origin to the list.
  9449. """
  9450. if _TRUSTED_FRAME_ORIGINS:
  9451. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9452. return f"frame-ancestors {default_value};"
  9453. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9454. # patterns are anchored on the exact emitted name so the relaxed policies
  9455. # below can never apply to any other asset.
  9456. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9457. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9458. # -> /assets/pdf.worker.min-<hash>.js
  9459. # Vite also emits a one-line chunk under the second name that only exports the
  9460. # worker's URL. The page imports it as a module, and a module script is run
  9461. # under the importing document's policy, never its own response's, so it
  9462. # matching as well changes nothing.
  9463. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9464. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9465. @app.middleware("http")
  9466. async def security_headers_middleware(request, call_next):
  9467. """Add standard HTTP security headers to every response."""
  9468. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9469. # changes nothing for Bambuddy's own pages — index.html has no inline
  9470. # scripts since the SW registration moved to /sw-register.js. The reason
  9471. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9472. # script injected into the HTML on the edge, with a fresh hash on every
  9473. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9474. # it clones the same nonce onto its injected <script>, and the inline
  9475. # script passes the policy without us needing 'unsafe-inline'. See
  9476. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9477. csp_nonce = secrets.token_urlsafe(16)
  9478. # Routes that render their own HTML need it too, or their inline script is
  9479. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9480. # one that does: it submits its own form so a verdict still costs one tap.
  9481. request.state.csp_nonce = csp_nonce
  9482. response = await call_next(request)
  9483. response.headers["X-Content-Type-Options"] = "nosniff"
  9484. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9485. # browsers honour CSP frame-ancestors instead, and the legacy
  9486. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9487. # When operators have explicitly allowlisted trusted frame origins (#1191
  9488. # — typically Home Assistant on a different port), drop X-Frame-Options
  9489. # and let the CSP-side frame-ancestors directive govern embedding.
  9490. if not _TRUSTED_FRAME_ORIGINS:
  9491. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9492. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9493. # Content-Security-Policy for the React SPA.
  9494. # Notes:
  9495. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9496. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9497. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9498. # - media-src blob:: timelapse video player uses Blob URLs.
  9499. # - font-src data:: some icon fonts are embedded as data URIs.
  9500. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9501. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9502. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9503. # default CSP would render a blank page.
  9504. response.headers["Content-Security-Policy"] = (
  9505. "default-src 'self'; "
  9506. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9507. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9508. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9509. "connect-src 'self'; "
  9510. "font-src 'self' data: https://fonts.gstatic.com; "
  9511. "worker-src 'self' blob:; "
  9512. "object-src 'none'; "
  9513. "base-uri 'self'; " + _frame_ancestors("'none'")
  9514. )
  9515. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9516. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9517. # its emscripten/embind glue generates invoker functions with `new
  9518. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9519. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9520. # own response — not the document's — so relaxing it here confines
  9521. # eval to that DOM-less worker context. The document policy below
  9522. # stays nonce-strict, and this response header has no effect when the
  9523. # file is merely fetched (a fetch's CSP is enforced against the
  9524. # requesting document, not the resource's own headers).
  9525. response.headers["Content-Security-Policy"] = (
  9526. "default-src 'self'; "
  9527. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9528. "connect-src 'self'; "
  9529. "object-src 'none'; "
  9530. "base-uri 'self'; " + _frame_ancestors("'none'")
  9531. )
  9532. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9533. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9534. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9535. # rule as the STEP worker above: the policy that governs a dedicated
  9536. # worker is the one delivered with its own script, so the wasm compile
  9537. # has to be permitted here rather than on the document. Unlike the STEP
  9538. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9539. response.headers["Content-Security-Policy"] = (
  9540. "default-src 'self'; "
  9541. "script-src 'self' 'wasm-unsafe-eval'; "
  9542. "connect-src 'self'; "
  9543. "object-src 'none'; "
  9544. "base-uri 'self'; " + _frame_ancestors("'none'")
  9545. )
  9546. else:
  9547. # The streaming overlay is embedded same-origin by the URL builder's
  9548. # preview in Settings (#1422), so this branch allows 'self'.
  9549. # Embedding from anywhere else is still refused: 'self'
  9550. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9551. # a clickjacking page on another host is blocked exactly as before.
  9552. # (The overlay draws status over a camera feed and its only interactive
  9553. # element is the logo link, so there is nothing to bait a click into
  9554. # even from a same-origin framer.) Cross-origin embedding of the
  9555. # overlay — Home Assistant on another port — remains what
  9556. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9557. # allowlist in.
  9558. #
  9559. # The connected-app consent page (/connect/authorize) gets the same
  9560. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9561. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9562. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9563. # requires every ancestor to be this origin, so a foreign page -- a
  9564. # sidebar link's site included -- still cannot frame the consent
  9565. # screen to bait a click.
  9566. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9567. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9568. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9569. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9570. # the policy served with their own script, so each gets it in its own
  9571. # branch above and the document policy stays as strict as it was.
  9572. response.headers["Content-Security-Policy"] = (
  9573. "default-src 'self'; "
  9574. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9575. "style-src 'self' 'unsafe-inline'; "
  9576. "img-src 'self' data: blob:; "
  9577. "media-src 'self' blob:; "
  9578. "connect-src 'self' ws: wss:; "
  9579. "font-src 'self' data:; "
  9580. "object-src 'none'; "
  9581. "base-uri 'self'; "
  9582. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9583. )
  9584. if request.url.scheme == "https":
  9585. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9586. return response
  9587. @app.middleware("http")
  9588. async def auth_middleware(request, call_next):
  9589. """Enforce authentication on all API routes when auth is enabled.
  9590. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9591. regardless of whether individual routes have auth dependencies.
  9592. """
  9593. from starlette.responses import JSONResponse
  9594. path = request.url.path
  9595. # Only apply to API routes
  9596. if not path.startswith("/api/"):
  9597. return await call_next(request)
  9598. # Allow public routes
  9599. if path in PUBLIC_API_ROUTES:
  9600. return await call_next(request)
  9601. # Allow public prefixes
  9602. for prefix in PUBLIC_API_PREFIXES:
  9603. if path.startswith(prefix):
  9604. return await call_next(request)
  9605. # Allow public patterns (read-only display data like thumbnails)
  9606. for pattern in PUBLIC_API_PATTERNS:
  9607. if pattern in path:
  9608. return await call_next(request)
  9609. # Check if auth is enabled. Fail CLOSED on any exception during the
  9610. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9611. # an attacker who could force a DB exception (e.g. file-descriptor
  9612. # exhaustion via login flood) bypass auth on every protected endpoint.
  9613. # Only the probe is guarded: the request itself runs outside the try, so an
  9614. # error in a route surfaces as the 500 it is rather than as an auth outage.
  9615. try:
  9616. async with async_session() as db:
  9617. from backend.app.core.auth import is_auth_enabled
  9618. auth_enabled = await is_auth_enabled(db)
  9619. except Exception:
  9620. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9621. return JSONResponse(
  9622. status_code=503,
  9623. content={"detail": "Authentication service temporarily unavailable"},
  9624. )
  9625. if not auth_enabled:
  9626. # Auth disabled, allow all requests
  9627. return await call_next(request)
  9628. # Auth is enabled - require valid token
  9629. auth_header = request.headers.get("Authorization")
  9630. x_api_key = request.headers.get("X-API-Key")
  9631. # Check for API key auth first
  9632. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9633. # API key authentication - let the request through to be validated by route handler
  9634. # API keys are validated per-route since they have different permission levels
  9635. return await call_next(request)
  9636. # Check for JWT auth
  9637. if not auth_header or not auth_header.startswith("Bearer "):
  9638. return JSONResponse(
  9639. status_code=401,
  9640. content={"detail": "Authentication required"},
  9641. headers={"WWW-Authenticate": "Bearer"},
  9642. )
  9643. # Validate JWT token
  9644. import jwt
  9645. try:
  9646. from backend.app.core.auth import (
  9647. ALGORITHM,
  9648. SECRET_KEY,
  9649. _is_token_fresh,
  9650. get_user_by_username,
  9651. is_jti_revoked,
  9652. )
  9653. token = auth_header.replace("Bearer ", "")
  9654. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9655. username = payload.get("sub")
  9656. if not username:
  9657. raise ValueError("No username in token")
  9658. jti = payload.get("jti")
  9659. if not jti:
  9660. raise ValueError("No jti in token")
  9661. iat = payload.get("iat")
  9662. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9663. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9664. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9665. async with async_session() as db:
  9666. if await is_jti_revoked(jti, db):
  9667. return JSONResponse(
  9668. status_code=401,
  9669. content={"detail": "Token has been revoked"},
  9670. headers={"WWW-Authenticate": "Bearer"},
  9671. )
  9672. user = await get_user_by_username(db, username)
  9673. if not user or not user.is_active:
  9674. return JSONResponse(
  9675. status_code=401,
  9676. content={"detail": "User not found or inactive"},
  9677. headers={"WWW-Authenticate": "Bearer"},
  9678. )
  9679. if not _is_token_fresh(iat, user):
  9680. return JSONResponse(
  9681. status_code=401,
  9682. content={"detail": "Token no longer valid"},
  9683. headers={"WWW-Authenticate": "Bearer"},
  9684. )
  9685. except jwt.ExpiredSignatureError:
  9686. return JSONResponse(
  9687. status_code=401,
  9688. content={"detail": "Token has expired"},
  9689. headers={"WWW-Authenticate": "Bearer"},
  9690. )
  9691. except (jwt.InvalidTokenError, ValueError):
  9692. return JSONResponse(
  9693. status_code=401,
  9694. content={"detail": "Invalid token"},
  9695. headers={"WWW-Authenticate": "Bearer"},
  9696. )
  9697. except Exception:
  9698. # Not a bad token but a failure checking it (database, pool): refuse,
  9699. # as for the probe above, rather than answer 401 -- the frontend reads
  9700. # a 401 from /auth/me as final and signs the user out.
  9701. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  9702. return JSONResponse(
  9703. status_code=503,
  9704. content={"detail": "Authentication service temporarily unavailable"},
  9705. )
  9706. return await call_next(request)
  9707. @app.middleware("http")
  9708. async def trace_id_middleware(request, call_next):
  9709. """Stamp every HTTP request with a trace ID and echo it back.
  9710. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9711. @app.middleware decorators LIFO, so the last-decorated runs first
  9712. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9713. which means auth-middleware log lines (and every line emitted on the
  9714. way down to and back from the route handler) all carry the same
  9715. trace ID. If we put it before auth, auth's logs would be stamped
  9716. with the *previous* request's ID — useless for correlation.
  9717. Honours an inbound ``X-Trace-Id`` header so callers running their
  9718. own tracing can correlate their span IDs with our log lines, but
  9719. only if the value passes the whitelist gate in
  9720. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9721. rejected (too long, contains control chars, etc.) silently triggers
  9722. a freshly minted server-side ID rather than failing the request.
  9723. The minted (or echoed) ID is set on a ContextVar so that every log
  9724. record emitted during the request — application logs *and* uvicorn's
  9725. access log — carries it via TraceIDFilter, and is also written to
  9726. the ``X-Trace-Id`` response header so clients can pin a server-side
  9727. log search to the exact request they made.
  9728. """
  9729. from backend.app.core.trace import (
  9730. generate_trace_id,
  9731. normalise_inbound_trace_id,
  9732. trace_id_var,
  9733. )
  9734. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9735. trace_id = inbound if inbound is not None else generate_trace_id()
  9736. token = trace_id_var.set(trace_id)
  9737. try:
  9738. response = await call_next(request)
  9739. finally:
  9740. # Reset the ContextVar so a record emitted in a totally
  9741. # unrelated background task that just happens to inherit this
  9742. # context doesn't keep referencing this request's ID forever.
  9743. # In practice ContextVar.reset is best-effort under asyncio
  9744. # task-spawn semantics, but the cost is one attribute write so
  9745. # we may as well do it.
  9746. trace_id_var.reset(token)
  9747. response.headers["X-Trace-Id"] = trace_id
  9748. return response
  9749. # API routes
  9750. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9751. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9752. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9753. app.include_router(users.router, prefix=app_settings.api_prefix)
  9754. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9755. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9756. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9757. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9758. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9759. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9760. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9761. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9762. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9763. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9764. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9765. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9766. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9767. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9768. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9769. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9770. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9771. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9772. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9773. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9774. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9775. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9776. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9777. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9778. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9779. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9780. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9781. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  9782. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9783. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9784. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9785. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9786. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9787. app.include_router(library.router, prefix=app_settings.api_prefix)
  9788. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9789. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9790. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9791. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9792. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9793. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9794. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9795. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9796. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9797. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9798. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  9799. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9800. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9801. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9802. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9803. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9804. app.include_router(system.router, prefix=app_settings.api_prefix)
  9805. app.include_router(support.router, prefix=app_settings.api_prefix)
  9806. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9807. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9808. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9809. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9810. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9811. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9812. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9813. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9814. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9815. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9816. # Serve static files (React build)
  9817. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9818. # Compressed, and cached for good where Vite hashed the name (#3175).
  9819. app.mount(
  9820. "/assets",
  9821. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  9822. name="assets",
  9823. )
  9824. if (app_settings.static_dir / "img").exists():
  9825. app.mount(
  9826. "/img",
  9827. StaticFiles(directory=app_settings.static_dir / "img"),
  9828. name="img",
  9829. )
  9830. if (app_settings.static_dir / "icons").exists():
  9831. app.mount(
  9832. "/icons",
  9833. StaticFiles(directory=app_settings.static_dir / "icons"),
  9834. name="icons",
  9835. )
  9836. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9837. # falls through to the SPA catch-all and returns index.html, which the
  9838. # browser's font sanitizer rejects ("downloadable font: rejected by
  9839. # sanitizer").
  9840. if (app_settings.static_dir / "fonts").exists():
  9841. app.mount(
  9842. "/fonts",
  9843. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9844. name="fonts",
  9845. )
  9846. @app.get("/")
  9847. async def serve_frontend():
  9848. """Serve the React frontend."""
  9849. index_file = app_settings.static_dir / "index.html"
  9850. if index_file.exists():
  9851. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9852. return {
  9853. "message": "Bambuddy API",
  9854. "docs": "/docs",
  9855. "frontend": "Build and place React app in /static directory",
  9856. }
  9857. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9858. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9859. # forever, but the HTML wrapping it is the only file that knows which hash
  9860. # is current. Without explicit cache-control headers Chromium decides
  9861. # heuristically (typically 10% of the time since Last-Modified) and on
  9862. # long-running kiosks happily serves stale HTML across browser restarts.
  9863. # That stale HTML references an old bundle hash, the old bundle is also
  9864. # in the disk cache, and the user ends up running pre-update JS forever
  9865. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9866. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9867. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9868. @app.get("/health")
  9869. async def health_check():
  9870. """Health check endpoint."""
  9871. return {"status": "healthy"}
  9872. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9873. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9874. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9875. # in deployment debugging.
  9876. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9877. async def serve_manifest():
  9878. """Serve PWA manifest."""
  9879. manifest_file = app_settings.static_dir / "manifest.json"
  9880. if manifest_file.exists():
  9881. return FileResponse(manifest_file, media_type="application/manifest+json")
  9882. return {"error": "Manifest not found"}
  9883. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9884. async def serve_service_worker():
  9885. """Serve service worker."""
  9886. sw_file = app_settings.static_dir / "sw.js"
  9887. if sw_file.exists():
  9888. return FileResponse(
  9889. sw_file,
  9890. media_type="application/javascript",
  9891. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9892. )
  9893. return {"error": "Service worker not found"}
  9894. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9895. async def serve_sw_register():
  9896. """Serve the service-worker registration bootstrap script.
  9897. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9898. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9899. """
  9900. reg_file = app_settings.static_dir / "sw-register.js"
  9901. if reg_file.exists():
  9902. return FileResponse(reg_file, media_type="application/javascript")
  9903. return {"error": "sw-register.js not found"}
  9904. # ── GCode viewer static files ────────────────────────────────────────────────
  9905. # Catch-all route for React Router (must be last)
  9906. @app.get("/{full_path:path}")
  9907. async def serve_spa(full_path: str):
  9908. """Serve React app for client-side routing."""
  9909. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9910. if full_path.startswith("api/"):
  9911. from fastapi import HTTPException
  9912. raise HTTPException(status_code=404, detail="Not found")
  9913. index_file = app_settings.static_dir / "index.html"
  9914. if index_file.exists():
  9915. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9916. return {"error": "Frontend not built"}