main.py 541 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181
  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 _get_printer_maintenance_internal, ensure_default_types
  87. from backend.app.api.routes.support import init_debug_logging
  88. from backend.app.core.config import APP_VERSION, settings as app_settings
  89. from backend.app.core.database import async_session, engine, init_db
  90. from backend.app.core.static_assets import AssetStaticFiles
  91. from backend.app.core.tasks import spawn_background_task
  92. from backend.app.core.websocket import ws_manager
  93. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  94. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  95. from backend.app.services.archive_cost_estimate import (
  96. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  97. )
  98. from backend.app.services.archive_purge import archive_purge_service
  99. from backend.app.services.bambu_ftp import (
  100. FileNotOnPrinterError,
  101. cache_3mf_download,
  102. clear_3mf_cache,
  103. download_file_async,
  104. download_file_try_paths_async,
  105. ftps_handshake_blocked,
  106. get_cached_3mf,
  107. get_ftp_retry_settings,
  108. normalize_3mf_name,
  109. with_ftp_retry,
  110. )
  111. from backend.app.services.bambu_mqtt import PrinterState
  112. from backend.app.services.camera_light import camera_light
  113. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  114. from backend.app.services.github_backup import github_backup_service
  115. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  116. from backend.app.services.homeassistant import homeassistant_service
  117. from backend.app.services.library_trash import library_trash_service
  118. from backend.app.services.local_backup import local_backup_service
  119. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  120. from backend.app.services.mqtt_relay import mqtt_relay
  121. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  122. from backend.app.services.notification_service import notification_service
  123. from backend.app.services.notify_live_activities import notify_live_activities
  124. from backend.app.services.notify_widgets import notify_widgets
  125. from backend.app.services.obico_detection import obico_detection_service
  126. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  127. from backend.app.services.print_scheduler import scheduler as print_scheduler
  128. from backend.app.services.print_storage import (
  129. REASON_FTP_TRANSFER_FAILED,
  130. REASON_FTPS_COOLOFF,
  131. external_storage_present,
  132. ftp_probe_paths,
  133. print_file_reachable_over_ftp,
  134. )
  135. from backend.app.services.printer_manager import (
  136. init_printer_connections,
  137. parse_plate_id,
  138. printer_manager,
  139. printer_state_to_dict,
  140. resolve_plate_id,
  141. )
  142. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  143. from backend.app.services.slot_nozzle import (
  144. nozzle_diameter_for_extruder,
  145. nozzle_flow_for_extruder,
  146. resolve_slot_nozzle,
  147. )
  148. from backend.app.services.smart_plug_manager import smart_plug_manager
  149. from backend.app.services.spool_assignment_notifications import (
  150. notify_missing_spool_assignments_on_print_start,
  151. )
  152. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  153. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  154. from backend.app.services.spoolman_tracking import (
  155. cleanup_tracking as _cleanup_spoolman_tracking,
  156. report_usage as _report_spoolman_usage,
  157. store_print_data as _store_spoolman_print_data,
  158. )
  159. from backend.app.services.tasmota import tasmota_service
  160. from backend.app.services.telegram_reactions import telegram_reaction_poller
  161. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  162. from backend.app.utils.ams_humidity import ams_humidity_percent
  163. from backend.app.utils.filament_types import printer_filament_type
  164. from backend.app.utils.fts_routing import extruder_for_inlet
  165. from backend.app.utils.local_time import utcnow_naive
  166. from backend.app.utils.print_jobs import is_internal_printer_job
  167. # =============================================================================
  168. # Dependency Check - runs before other imports to give helpful error messages
  169. # =============================================================================
  170. def _start_error_server(missing_packages: list):
  171. """Start a minimal HTTP server to display dependency errors in browser."""
  172. import os
  173. import signal
  174. from http.server import BaseHTTPRequestHandler, HTTPServer
  175. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  176. html = f"""<!DOCTYPE html>
  177. <html>
  178. <head>
  179. <title>Bambuddy - Setup Required</title>
  180. <style>
  181. body {{
  182. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  183. background: #0f172a; color: #e2e8f0;
  184. display: flex; justify-content: center; align-items: center;
  185. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  186. }}
  187. .container {{
  188. background: #1e293b; border-radius: 12px; padding: 40px;
  189. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  190. }}
  191. h1 {{ color: #f87171; margin-bottom: 10px; }}
  192. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  193. .packages {{
  194. background: #0f172a; border-radius: 8px; padding: 20px;
  195. margin: 20px 0; text-align: left;
  196. }}
  197. .packages ul {{ margin: 0; padding-left: 20px; }}
  198. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  199. .command {{
  200. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  201. margin: 15px 0; font-family: monospace; color: #4ade80;
  202. text-align: left; overflow-x: auto;
  203. }}
  204. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  205. </style>
  206. </head>
  207. <body>
  208. <div class="container">
  209. <h1>Setup Required</h1>
  210. <h2>Missing Python packages</h2>
  211. <div class="packages"><ul>{packages_html}</ul></div>
  212. <p>To fix, run this command on your server:</p>
  213. <div class="command">pip install -r requirements.txt</div>
  214. <p>Or if using a virtual environment:</p>
  215. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  216. <p class="note">After installing, restart Bambuddy:<br>
  217. <code>sudo systemctl restart bambuddy</code></p>
  218. </div>
  219. </body>
  220. </html>"""
  221. class ErrorHandler(BaseHTTPRequestHandler):
  222. def do_GET(self):
  223. self.send_response(503)
  224. self.send_header("Content-type", "text/html")
  225. self.end_headers()
  226. self.wfile.write(html.encode())
  227. def log_message(self, format, *args):
  228. print(f"[Error Server] {args[0]}")
  229. port = int(os.environ.get("PORT", 8000))
  230. print(f"\nStarting error server on http://0.0.0.0:{port}")
  231. print("Visit this URL in your browser to see the error details.\n")
  232. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  233. def shutdown(signum, frame):
  234. print("\nShutting down error server...")
  235. raise SystemExit(0)
  236. signal.signal(signal.SIGTERM, shutdown)
  237. signal.signal(signal.SIGINT, shutdown)
  238. server.serve_forever()
  239. def check_dependencies():
  240. """Check that all required packages are installed."""
  241. missing = []
  242. # Map of import name -> package name (for pip install)
  243. required = {
  244. "jwt": "PyJWT",
  245. "fastapi": "fastapi",
  246. "uvicorn": "uvicorn",
  247. "sqlalchemy": "sqlalchemy",
  248. "aiosqlite": "aiosqlite",
  249. "pydantic": "pydantic",
  250. "paho.mqtt": "paho-mqtt",
  251. }
  252. for module, package in required.items():
  253. try:
  254. __import__(module)
  255. except ImportError:
  256. missing.append(package)
  257. if missing:
  258. print("\n" + "=" * 60)
  259. print("ERROR: Missing required Python packages!")
  260. print("=" * 60)
  261. print(f"\nMissing packages: {', '.join(missing)}")
  262. print("\nTo fix, run:")
  263. print(" pip install -r requirements.txt")
  264. print("\nOr if using a virtual environment:")
  265. print(" ./venv/bin/pip install -r requirements.txt")
  266. print("=" * 60 + "\n")
  267. _start_error_server(missing)
  268. check_dependencies()
  269. # =============================================================================
  270. # Import settings first for logging configuration
  271. # Configure logging based on settings
  272. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  273. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  274. log_level = getattr(logging, log_level_str, logging.INFO)
  275. # Trace ID column ([-] when no request scope is active — startup, MQTT
  276. # callbacks, scheduled tasks not chained from a request — so the column
  277. # stays visually aligned and missing values are obvious in grep). See
  278. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  279. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  280. # Create root logger
  281. root_logger = logging.getLogger()
  282. root_logger.setLevel(log_level)
  283. # Trace-ID injection: this filter populates record.trace_id from the
  284. # per-request ContextVar so the format string above can reference it.
  285. # Attached to each HANDLER (not the root logger) because Python's
  286. # logging semantics only invoke a logger's filters on records that
  287. # *originated* at that logger — records propagated up from child
  288. # loggers (every named logger in the app) never trigger root's filter.
  289. # Putting it on the handlers means every record any handler emits gets
  290. # trace_id injected just before the formatter runs, regardless of which
  291. # logger created the record. Without this, the formatter raises
  292. # KeyError on every child-logger record and the record is silently
  293. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  294. # partially" bug we hit. See backend/app/core/trace.py for the
  295. # ContextVar the filter reads.
  296. from backend.app.core.trace import TraceIDFilter
  297. _trace_id_filter = TraceIDFilter()
  298. # Console handler - always enabled
  299. console_handler = logging.StreamHandler()
  300. console_handler.setLevel(log_level)
  301. console_handler.setFormatter(logging.Formatter(log_format))
  302. console_handler.addFilter(_trace_id_filter)
  303. root_logger.addHandler(console_handler)
  304. # File handler - only in production or if explicitly enabled
  305. if app_settings.log_to_file:
  306. log_file = app_settings.log_dir / "bambuddy.log"
  307. file_handler = RotatingFileHandler(
  308. log_file,
  309. maxBytes=app_settings.log_max_bytes,
  310. backupCount=app_settings.log_backup_count,
  311. encoding="utf-8",
  312. )
  313. file_handler.setLevel(log_level)
  314. file_handler.setFormatter(logging.Formatter(log_format))
  315. file_handler.addFilter(_trace_id_filter)
  316. root_logger.addHandler(file_handler)
  317. logging.info("Logging to file: %s", log_file)
  318. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  319. # access logger with propagate=False by default, so without this attach
  320. # there is no on-disk record of which endpoint triggered a server-state
  321. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  322. # for exactly this reason. Filtered to write methods only
  323. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  324. # frontend don't churn the rotation window faster than it's useful.
  325. from backend.app.core.logging_filters import (
  326. CancelledPoolNoiseFilter,
  327. WriteRequestsOnlyFilter,
  328. )
  329. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  330. uvicorn_access_logger.addHandler(file_handler)
  331. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  332. # Uvicorn's access logger has propagate=False (its own default), so the
  333. # root-attached TraceIDFilter never sees these records. Attach a
  334. # second instance directly so HTTP access lines carry the same trace
  335. # ID column as the application logs they correlate with.
  336. uvicorn_access_logger.addFilter(TraceIDFilter())
  337. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  338. # BaseHTTPMiddleware cancelling the inner task scope on client
  339. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  340. # underlying transaction leak; this filter only suppresses the residual
  341. # log records that pre-existing pools still emit during their cleanup.
  342. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  343. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  344. # handler (console included), whether or not file logging is on.
  345. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  346. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  347. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  348. # Reduce noise from third-party libraries in production
  349. if not app_settings.debug:
  350. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  351. logging.getLogger("httpcore").setLevel(logging.WARNING)
  352. logging.getLogger("httpx").setLevel(logging.WARNING)
  353. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  354. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  355. # Track active prints: {(printer_id, filename): archive_id}
  356. _active_prints: dict[tuple[int, str], int] = {}
  357. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  358. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  359. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  360. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  361. # instead of running its own grab-now chain when present, so the finish photo
  362. # captures the better-framed pre-bed-drop moment without us having to force
  363. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  364. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  365. #
  366. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  367. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  368. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  369. # bank and the others are not — so the consumer can't tell them apart and
  370. # must not rotate again.
  371. _stage22_finish_frames: dict[int, bytes] = {}
  372. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  373. # `finally` block (whether it captured a frame or not). The consumer in
  374. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  375. # so the FINISH-state fallback path — where moment and completion are dispatched
  376. # back-to-back — doesn't race past the producer with an empty pop, and the
  377. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  378. # grab (Bambu printers allow only one RTSP client at a time).
  379. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  380. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  381. # layer-change and on print-progress advances (#2547) while the model is still
  382. # printing, then consumed by the FINISH-state finish-photo path when the
  383. # dispatcher recorded that it injected End G-code into this print. Bambu
  384. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  385. # plate-swap) has run, so a live grab there would capture the swapped/empty
  386. # plate.
  387. #
  388. # The load-bearing property: both drivers are print telemetry that stops before
  389. # the End G-code executes — no further layer_num increases, and mc_percent
  390. # freezes — so the last banked frame is always the finished print before the
  391. # swap. Anything added as a third driver must hold that same property.
  392. _inprint_frame_bank: dict[int, bytes] = {}
  393. # Monotonic timestamp of the last banked frame per printer — throttles banking
  394. # so tall prints don't add a camera grab on every layer.
  395. _inprint_frame_bank_ts: dict[int, float] = {}
  396. # Minimum seconds between banked frames, except the final object layer which
  397. # always refreshes for the best framing.
  398. _INPRINT_BANK_MIN_INTERVAL = 25.0
  399. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  400. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  401. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  402. # the first connected status update for that connection; transitions back
  403. # to False whenever we observe `state.connected = False` so the next
  404. # reconnect re-arms reconciliation. Keyed by printer_id.
  405. _printer_reconciled_since_connect: dict[int, bool] = {}
  406. # Same edge, same keying, for priming the printer's calibration table exactly
  407. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  408. # is otherwise filled only when someone opens the Profiles page or Configure
  409. # Slot, when a GitHub backup runs, or when the printer happens to answer
  410. # somebody else's query on the report topic. Until then the AMS slot card has
  411. # no K value to show on the printers whose trays carry none of their own
  412. # (#2854 — H2-series report cali_idx and nothing more).
  413. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  414. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  415. # {(printer_id, filename): archive_id}
  416. _expected_prints: dict[tuple[int, str], int] = {}
  417. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  418. # Used by usage tracker to map 3MF slots to physical AMS trays
  419. _print_ams_mappings: dict[int, list[int]] = {}
  420. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  421. _print_cost_center_ids: dict[int, int] = {}
  422. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  423. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  424. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  425. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  426. # for the queue path. Cleared on print completion or TTL eviction.
  427. _print_plate_ids: dict[int, int] = {}
  428. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  429. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  430. _last_progress_milestone: dict[int, int] = {}
  431. # Track whether first layer complete notification has been sent for current print
  432. _first_layer_notified: dict[int, bool] = {}
  433. # Track whether we already sent a kill-switch stop for the current unauthorized print
  434. _unauthorized_print_kill_sent: set[int] = set()
  435. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  436. # lookup briefly so an unknown active print does not query the database on
  437. # every status frame. A short TTL keeps settings changes responsive.
  438. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  439. _kill_switch_setting_cache: tuple[bool, float] | None = None
  440. # Provider notification started when the kill switch stops a print. The later
  441. # MQTT print-complete callback awaits this task and only sends its regular
  442. # provider notification when the immediate attempt failed.
  443. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  444. # HMS faults already notified, with when each was last seen:
  445. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  446. # fault that flickers beside a held notice was forgotten on every gap and
  447. # notified on every return (#3226). The window is long because the measured
  448. # gaps reach 64 s.
  449. _notified_hms_errors: dict[int, dict[str, float]] = {}
  450. _HMS_CLEAR_GRACE_SECONDS = 600.0
  451. # The print state each printer was last seen in, and the faults recorded before
  452. # it last changed, which are forgotten as soon as they are gone (see
  453. # _take_new_hms_faults).
  454. _hms_print_state: dict[int, str] = {}
  455. _hms_forget_when_gone: dict[int, set[str]] = {}
  456. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  457. # Used for snapshot-diff detection at print completion
  458. _timelapse_baselines: dict[int, set[str]] = {}
  459. # Track printers waiting for bed to cool after print completion.
  460. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  461. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  462. _bed_cool_waiters: dict[int, dict] = {}
  463. # Track printers where the user explicitly stopped the print from the queue UI.
  464. # When on_print_complete fires with status "failed" for these printers we treat it
  465. # as "cancelled" (stopped by user) so the correct notification email is sent.
  466. _user_stopped_printers: set[int] = set()
  467. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  468. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  469. # holds the previous observation so we only fire on the True → False edge (a
  470. # False → False repeat doesn't notify; an initial False at startup doesn't
  471. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  472. # holds the per-printer pending asyncio task that fires the notification
  473. # after a debounce window — cancelled if the printer reconnects before the
  474. # window elapses, so transient MQTT blips don't flood the user.
  475. _printer_last_connected: dict[int, bool] = {}
  476. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  477. # Debounce: a printer must stay offline this long before we notify. Sized
  478. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  479. # so a single stale-trigger cooldown isn't enough to fire — only a real
  480. # offline that survives one reconnect attempt notifies.
  481. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  482. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  483. # when status="failed" to label the print's failure_reason in archives.
  484. #
  485. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  486. # which is wrong on two counts:
  487. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  488. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  489. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  490. # the public wiki) as part of its user-cancel sequence. Matching on the module
  491. # alone caused user-cancellations to be archived as "Layer shift" failures.
  492. # We now match by full short code only — anything not in this map leaves
  493. # failure_reason=None rather than guessing.
  494. # Values are the canonical camelCase failure-reason keys, NOT display labels
  495. # (issue #2974). The vocabulary is enforced on writes by
  496. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  497. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  498. # Statistics breakdown. Storing a label here instead put a second spelling of
  499. # the same cause into one column: the Failure Analysis widget groups on the raw
  500. # value, so a print the backend classified and an identical one a user
  501. # classified counted as two different reasons, and the label form could never
  502. # be translated because there was no key for ``t()`` to resolve.
  503. _HMS_FAILURE_REASONS: dict[str, str] = {
  504. # Layer shift / step loss
  505. "0300_4057": "layerShift",
  506. "0300_4068": "layerShift",
  507. "0300_800C": "layerShift",
  508. # Filament runout (printer-side & per-AMS-slot)
  509. "0300_8004": "filamentRunout",
  510. "0700_8011": "filamentRunout",
  511. "0701_8011": "filamentRunout",
  512. "0702_8011": "filamentRunout",
  513. "0703_8011": "filamentRunout",
  514. "0704_8011": "filamentRunout",
  515. "0705_8011": "filamentRunout",
  516. "0706_8011": "filamentRunout",
  517. "0707_8011": "filamentRunout",
  518. "07FF_8011": "filamentRunout",
  519. # Clogged nozzle / extruder
  520. "0300_4006": "cloggedNozzle",
  521. "0300_8016": "cloggedNozzle",
  522. "0300_801C": "cloggedNozzle",
  523. "0700_8003": "cloggedNozzle",
  524. "0700_8007": "cloggedNozzle",
  525. "0700_8013": "cloggedNozzle",
  526. "0701_8003": "cloggedNozzle",
  527. "0701_8007": "cloggedNozzle",
  528. "0701_8013": "cloggedNozzle",
  529. "0702_8003": "cloggedNozzle",
  530. # AI print monitoring — spaghetti / the model coming off the plate.
  531. # `spaghettiDetached` is a key the archive editor already offers for this
  532. # failure mode, not a new one, so a derived reason opens the dropdown on
  533. # that option rather than blank — and survives the next save, which clears
  534. # any value the editor does not recognise.
  535. #
  536. # A module-0x0C row is safe here despite the warning above: that warning is
  537. # about matching on the module alone, and 0C00_8042 is a full short code
  538. # with a documented meaning ("The AI print monitor has detected a spaghetti
  539. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  540. # cannot collide.
  541. #
  542. # 0300_8003's own text ends "before continuing your print", but on an X2D
  543. # it arrives with the print already paused, offering only
  544. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  545. #
  546. # Two neighbours are left out on purpose, so this does not get re-derived:
  547. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  548. # reads as a warning about a print that is still running, not a halt.
  549. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  550. # the waste chute. That is not the print failing.
  551. #
  552. # That line is drawn from the text, not from `severity`, because severity
  553. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  554. # module/error word with no level in it, and bambu_mqtt.py gives every
  555. # print_error entry a flat severity=3. Matching on the short code alone is
  556. # the right shape for derive_failure_reason, not an omission.
  557. "0300_8003": "spaghettiDetached",
  558. "0C00_8042": "spaghettiDetached",
  559. }
  560. def _hms_short_code(attr: int, code: int | str) -> str:
  561. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  562. if isinstance(code, str):
  563. code_int = int(code.replace("0x", ""), 16) if code else 0
  564. else:
  565. code_int = int(code or 0)
  566. attr_int = int(attr or 0)
  567. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  568. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  569. """Derive the failure_reason key for an archived print.
  570. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  571. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  572. no HMS code matches (don't guess — null is honest). The keys are the
  573. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  574. translated at render time.
  575. """
  576. if status in ("aborted", "cancelled"):
  577. return "userCancelled"
  578. if status != "failed":
  579. return None
  580. for err in hms_errors or []:
  581. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  582. if short_code in _HMS_FAILURE_REASONS:
  583. return _HMS_FAILURE_REASONS[short_code]
  584. return None
  585. # Track created_by_id for expected prints so the user email can be sent even when
  586. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  587. # {(printer_id, filename): created_by_id}
  588. _expected_print_creators: dict[tuple[int, str], int] = {}
  589. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  590. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  591. # updates for the same printer in quick succession (~30 ms apart, observed in
  592. # the wild on H2D + dual AMS).
  593. #
  594. # Without this serialisation, two concurrent on_ams_change callbacks each read
  595. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  596. # the second commit hits
  597. # IntegrityError: duplicate key value violates unique constraint
  598. # "spool_assignment_printer_id_ams_id_tray_id_key"
  599. # SQLite's WAL serial-write semantics had been silently swallowing the race
  600. # until optional Postgres support landed (asyncpg allows true concurrent
  601. # transactions and surfaces the constraint violation).
  602. #
  603. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  604. # assign) are inside the lock. The Spoolman sync block further down stays
  605. # concurrent because it's network-bound and idempotent.
  606. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  607. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  608. """Return the per-printer assignment lock, creating it on first use."""
  609. lock = _ams_assignment_locks.get(printer_id)
  610. if lock is None:
  611. lock = asyncio.Lock()
  612. _ams_assignment_locks[printer_id] = lock
  613. return lock
  614. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  615. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  616. # tag tuple changes for the slot. Cleared when the slot is reported empty
  617. # so remove + reinsert reliably re-prompts the UI.
  618. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  619. async def _broadcast_unknown_tag(
  620. *,
  621. printer_id: int,
  622. ams_id: int,
  623. tray_id: int,
  624. tag_uid: str,
  625. tray_uuid: str,
  626. tray_type: str | None = None,
  627. tray_color: str | None = None,
  628. tray_sub_brands: str | None = None,
  629. tray_count: int | None = None,
  630. ) -> None:
  631. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  632. _logger = logging.getLogger(__name__)
  633. slot_key = (ams_id, tray_id)
  634. tag_key = (tag_uid or "", tray_uuid or "")
  635. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  636. if per_printer.get(slot_key) == tag_key:
  637. _logger.debug(
  638. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  639. printer_id,
  640. ams_id,
  641. tray_id,
  642. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  643. )
  644. return
  645. _logger.info(
  646. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  647. printer_id,
  648. ams_id,
  649. tray_id,
  650. tray_type,
  651. tray_color,
  652. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  653. )
  654. # Broadcast first; only commit the dedup if the WS write succeeds.
  655. # If broadcast raises, the next MQTT push retries instead of being
  656. # permanently silenced by a poisoned dedup entry.
  657. await ws_manager.broadcast(
  658. {
  659. "type": "unknown_tag",
  660. "printer_id": printer_id,
  661. "ams_id": ams_id,
  662. "tray_id": tray_id,
  663. "tag_uid": tag_uid,
  664. "tray_uuid": tray_uuid,
  665. "tray_type": tray_type,
  666. "tray_color": tray_color,
  667. "tray_sub_brands": tray_sub_brands,
  668. "tray_count": tray_count,
  669. }
  670. )
  671. per_printer[slot_key] = tag_key
  672. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  673. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  674. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  675. if per_printer is None:
  676. return
  677. per_printer.pop((ams_id, tray_id), None)
  678. # TTL for expected-print entries: evict registrations older than this to prevent
  679. # unbounded growth when a print is registered but never starts (e.g. printer
  680. # disconnect, app restart, print started from the printer panel).
  681. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  682. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  683. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  684. # Cleanup loop interval
  685. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  686. _expected_prints_cleanup_task: asyncio.Task | None = None
  687. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  688. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  689. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  690. possible_keys: list[tuple[int, str]] = []
  691. filename = (state.gcode_file or state.current_print or "").strip()
  692. subtask_name = (state.subtask_name or "").strip()
  693. if subtask_name:
  694. possible_keys.append((printer_id, subtask_name))
  695. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  696. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  697. if filename:
  698. base_name = filename.rsplit("/", 1)[-1]
  699. if base_name.endswith(".gcode.3mf"):
  700. root_name = base_name[: -len(".gcode.3mf")]
  701. possible_keys.append((printer_id, root_name))
  702. possible_keys.append((printer_id, base_name))
  703. possible_keys.append((printer_id, f"{root_name}.gcode"))
  704. possible_keys.append((printer_id, f"{root_name}.3mf"))
  705. elif base_name.endswith(".3mf"):
  706. root_name = base_name[: -len(".3mf")]
  707. possible_keys.append((printer_id, root_name))
  708. possible_keys.append((printer_id, base_name))
  709. elif base_name.endswith(".gcode"):
  710. root_name = base_name[: -len(".gcode")]
  711. possible_keys.append((printer_id, root_name))
  712. possible_keys.append((printer_id, f"{root_name}.3mf"))
  713. possible_keys.append((printer_id, base_name))
  714. else:
  715. possible_keys.append((printer_id, base_name))
  716. possible_keys.append((printer_id, f"{base_name}.3mf"))
  717. return possible_keys
  718. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  719. """Check the cheap, process-local print ownership signals."""
  720. if printer_manager.get_current_print_user(printer_id):
  721. return True
  722. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  723. async def _is_printer_kill_switch_enabled_cached() -> bool:
  724. """Return the kill-switch setting without querying on every MQTT frame."""
  725. global _kill_switch_setting_cache
  726. now = time.monotonic()
  727. if _kill_switch_setting_cache is not None:
  728. enabled, expires_at = _kill_switch_setting_cache
  729. if now < expires_at:
  730. return enabled
  731. async with async_session() as db:
  732. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  733. enabled = await is_printer_kill_switch_enabled(db)
  734. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  735. return enabled
  736. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  737. """Resolve whether the current print was started by Bambuddy.
  738. ``None`` means identity is not yet safe to decide. The kill switch must
  739. defer in that case: stopping a print is irreversible, and the first status
  740. frames after a restart may arrive before all subtask fields are populated.
  741. """
  742. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  743. return True
  744. possible_keys = _build_status_print_keys(printer_id, state)
  745. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  746. # is on disk. subtask_id is minted per print and pins the answer to the job
  747. # actually running, rather than to an unrelated one that reuses a filename.
  748. raw_subtask_id = getattr(state, "subtask_id", None)
  749. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  750. if subtask_id in ("", "0"):
  751. return None
  752. from backend.app.models.archive import PrintArchive
  753. result = await db.execute(
  754. select(PrintArchive)
  755. .where(
  756. PrintArchive.printer_id == printer_id,
  757. PrintArchive.status == "printing",
  758. PrintArchive.subtask_id == subtask_id,
  759. )
  760. .order_by(PrintArchive.created_at.desc())
  761. .limit(1)
  762. )
  763. archive = result.scalar_one_or_none()
  764. # An archive row on its own proves nothing: `on_print_start` archives every
  765. # print it observes, including ones started from Bambu Studio or Handy, and
  766. # stamps them with the same status and subtask_id. Authorizing on its mere
  767. # existence would disable the kill switch the moment the 3MF finishes
  768. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  769. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  770. # (carried over from the queue item that started it).
  771. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  772. # Rehydrate the fast in-memory path for subsequent status frames. Include
  773. # both the archive filename and every normalized key reported by MQTT.
  774. _active_prints[(printer_id, archive.filename)] = archive.id
  775. for key in possible_keys:
  776. _active_prints[key] = archive.id
  777. return True
  778. # No dispatch marker. Before calling this someone else's print, check whether
  779. # Bambuddy has a job of its own running on this printer: a library-file
  780. # dispatch has no archive at send time, and an archive created seconds later
  781. # by `on_print_start` carries neither marker. The queue row, which the
  782. # scheduler commits to status="printing" before the MQTT send, is the one
  783. # durable record every Bambuddy print has. It cannot be tied to this
  784. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  785. # print is irreversible, and refusing to act costs nothing but a log line.
  786. from backend.app.models.print_queue import PrintQueueItem
  787. dispatched_here = await db.scalar(
  788. select(PrintQueueItem.id)
  789. .where(
  790. PrintQueueItem.printer_id == printer_id,
  791. PrintQueueItem.status == "printing",
  792. )
  793. .limit(1)
  794. )
  795. if dispatched_here is not None:
  796. return None
  797. return False
  798. async def _send_kill_switch_provider_notification(
  799. printer_id: int,
  800. printer_name: str,
  801. data: dict,
  802. ) -> bool:
  803. """Send the immediate print-stopped provider notification.
  804. Returning a success flag lets the normal MQTT completion path retry when
  805. this early notification could not be delivered.
  806. """
  807. logger = logging.getLogger(__name__)
  808. try:
  809. async with async_session() as db:
  810. await notification_service.on_print_complete(
  811. printer_id,
  812. printer_name,
  813. "stopped",
  814. data,
  815. db,
  816. )
  817. return True
  818. except Exception as e:
  819. logger.warning(
  820. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  821. printer_id,
  822. e,
  823. )
  824. return False
  825. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  826. """Wait for an immediate kill-switch notification, if one was scheduled."""
  827. if task is None:
  828. return False
  829. try:
  830. return await task
  831. except Exception as e:
  832. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  833. return False
  834. async def _get_plug_energy(plug, db) -> dict | None:
  835. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  836. For HA plugs, configures the service with current settings from DB.
  837. For MQTT plugs, returns data from the subscription service.
  838. For REST plugs, polls the status URL with JSON path extraction.
  839. """
  840. if plug.plug_type == "homeassistant":
  841. from backend.app.api.routes.settings import get_homeassistant_settings
  842. ha_settings = await get_homeassistant_settings(db)
  843. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  844. return await homeassistant_service.get_energy(plug)
  845. elif plug.plug_type == "mqtt":
  846. # MQTT plugs report "today" energy, not lifetime total
  847. # For per-print tracking, we use "today" as the counter (resets at midnight)
  848. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  849. if mqtt_data:
  850. return {
  851. "power": mqtt_data.power,
  852. "today": mqtt_data.energy,
  853. "total": mqtt_data.energy, # Use today as total for per-print calculations
  854. }
  855. return None
  856. elif plug.plug_type == "rest":
  857. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  858. return await rest_smart_plug_service.get_energy(plug)
  859. else:
  860. return await tasmota_service.get_energy(plug)
  861. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  862. """Capture the smart plug lifetime counter on the archive at print start.
  863. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  864. tracking survives a backend restart mid-print. The print-end handler reads
  865. this value back from the DB and computes the delta against the current
  866. plug counter.
  867. """
  868. _logger = logging.getLogger(__name__)
  869. try:
  870. candidates = await energy_plug_candidates(db, printer_id)
  871. if not candidates:
  872. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  873. return False
  874. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  875. if selected is None:
  876. # Naming the plugs matters here: with several linked to one printer
  877. # this is the difference between "the meter is offline" and "you
  878. # linked only accessories" (#2859).
  879. _logger.warning(
  880. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  881. printer_id,
  882. archive.id,
  883. ", ".join(plug.name for plug in candidates),
  884. )
  885. return False
  886. plug, energy = selected
  887. archive.energy_start_kwh = float(energy["total"])
  888. # With the plug's snapshots, what lets the cost follow the price over
  889. # the print rather than take the price at its end (#1251). A price that
  890. # can't be had must not cost the print its energy reading.
  891. archive.energy_start_at = utcnow_naive()
  892. archive.energy_start_plug_id = plug.id
  893. try:
  894. from backend.app.services.energy_price import current_price
  895. archive.energy_start_price = await current_price(db)
  896. except Exception as e:
  897. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  898. archive.energy_start_price = None
  899. await db.commit()
  900. _logger.info(
  901. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  902. f" ({context})" if context else "",
  903. archive.id,
  904. plug.name,
  905. energy["total"],
  906. )
  907. return True
  908. except Exception as e:
  909. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  910. return False
  911. def register_expected_print(
  912. printer_id: int,
  913. filename: str,
  914. archive_id: int,
  915. ams_mapping: list[int] | None = None,
  916. created_by_id: int | None = None,
  917. cost_center_id: int | None = None,
  918. plate_id: int | None = None,
  919. ):
  920. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  921. # Store with multiple filename variations to catch different naming patterns
  922. _expected_prints[(printer_id, filename)] = archive_id
  923. # Also store without .3mf extension if present
  924. if filename.endswith(".3mf"):
  925. base = filename[:-4]
  926. _expected_prints[(printer_id, base)] = archive_id
  927. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  928. # Store AMS mapping for usage tracking at print completion
  929. if ams_mapping is not None:
  930. _print_ams_mappings[archive_id] = ams_mapping
  931. if cost_center_id is not None:
  932. _print_cost_center_ids[archive_id] = cost_center_id
  933. # Store plate_id for usage tracking when this is a single-plate dispatch from
  934. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  935. # file's filament total to the spool instead of just the printed plate (#1697).
  936. if plate_id is not None:
  937. _print_plate_ids[archive_id] = plate_id
  938. # Store created_by_id so the user start email can be sent even when the archive
  939. # itself has no created_by_id (e.g. library-file-based queue prints)
  940. if created_by_id is not None:
  941. _expected_print_creators[(printer_id, filename)] = created_by_id
  942. if filename.endswith(".3mf"):
  943. base = filename[:-4]
  944. _expected_print_creators[(printer_id, base)] = created_by_id
  945. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  946. # Record registration time for TTL-based eviction
  947. _registered_at = time.monotonic()
  948. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  949. if filename.endswith(".3mf"):
  950. base = filename[:-4]
  951. _expected_print_registered_at[(printer_id, base)] = _registered_at
  952. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  953. logging.getLogger(__name__).info(
  954. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  955. )
  956. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  957. """Undo :func:`register_expected_print` when the print never went out.
  958. Registration has to happen *before* the MQTT print command, because the
  959. printer can report the print before the line after the send executes. So
  960. every path that registers and then fails to send — a cancel winning the
  961. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  962. between — leaves an expectation for a print that will never arrive.
  963. The TTL sweep evicts those after two hours, which is far longer than it
  964. takes a user to react to a failed dispatch by pressing print again: that
  965. reprint would be folded into the *old* archive and take the stale
  966. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  967. Mirrors the sweep's rules, including the one that is easy to get wrong:
  968. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  969. file, so they may only be dropped once no live key still points at that
  970. archive.
  971. """
  972. keys = [(printer_id, filename)]
  973. if filename.endswith(".3mf"):
  974. base = filename[:-4]
  975. keys.append((printer_id, base))
  976. keys.append((printer_id, f"{base}.gcode"))
  977. removed = False
  978. for key in keys:
  979. if _expected_prints.pop(key, None) is not None:
  980. removed = True
  981. _expected_print_creators.pop(key, None)
  982. _expected_print_registered_at.pop(key, None)
  983. if archive_id not in set(_expected_prints.values()):
  984. _print_ams_mappings.pop(archive_id, None)
  985. _print_plate_ids.pop(archive_id, None)
  986. if removed:
  987. logging.getLogger(__name__).info(
  988. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  989. printer_id,
  990. filename,
  991. archive_id,
  992. )
  993. def _compute_run_filament_grams(
  994. status: str,
  995. archive_filament_used_grams: float | None,
  996. progress: float | int | None,
  997. usage_results: list[dict] | None,
  998. ) -> float | None:
  999. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1000. Priority for every status:
  1001. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1002. weight delta — same source that drives "Total Consumed" on the
  1003. Inventory page, so Stats and Inventory totals stay aligned).
  1004. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1005. back to the canonical "this print used X" value).
  1006. 3. For partial statuses: ``estimate * progress%``.
  1007. 4. ``None`` if nothing is known.
  1008. """
  1009. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1010. if tracked_grams > 0:
  1011. return round(tracked_grams, 1)
  1012. if status == "completed":
  1013. return archive_filament_used_grams
  1014. if archive_filament_used_grams:
  1015. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1016. if scale > 0:
  1017. return round(archive_filament_used_grams * scale, 1)
  1018. return None
  1019. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1020. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1021. stored_ams_mapping = data.get("ams_mapping")
  1022. if not stored_ams_mapping and archive_id:
  1023. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1024. return stored_ams_mapping
  1025. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1026. """Resolve plate_id for print start without consuming stored direct-Print state.
  1027. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1028. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1029. read it back at print-start without popping (the entry is popped on print
  1030. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1031. """
  1032. if archive_id is None:
  1033. return None
  1034. return _print_plate_ids.get(archive_id)
  1035. def _partial_progress_scale(progress: int | float | None) -> float:
  1036. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1037. Used by every site that multiplies a "would-have-used" slicer estimate
  1038. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1039. so the three sites in ``_background_notifications`` (and the per-plate
  1040. override helper) can't drift apart on the coercion shape.
  1041. """
  1042. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1043. def _scope_notification_archive_data_to_plate(
  1044. archive_data: dict,
  1045. archive_file_path: str | None,
  1046. plate_id: int | None,
  1047. print_status: str,
  1048. progress: int | float | None,
  1049. base_dir: Path,
  1050. ) -> dict:
  1051. """Override summed-across-plates totals in ``archive_data`` with the values
  1052. for ``plate_id`` so the completion notification reports what was actually
  1053. printed, not the whole project (#1785).
  1054. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1055. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1056. the archive card's "whole project" headline, wrong for the completion
  1057. notification of a single-plate print. The queue UI already re-reads the
  1058. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1059. notification payload (filament grams, time estimate, per-slot breakdown).
  1060. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1061. no per-plate values — in every fail case the original ``archive_data`` is
  1062. returned unchanged so the notification still sends.
  1063. """
  1064. if plate_id is None or not archive_file_path:
  1065. return archive_data
  1066. from backend.app.utils.threemf_tools import (
  1067. extract_filament_usage_from_3mf,
  1068. extract_print_time_from_3mf,
  1069. )
  1070. archive_path = base_dir / archive_file_path
  1071. if not archive_path.exists():
  1072. return archive_data
  1073. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1074. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1075. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1076. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1077. if plate_time:
  1078. archive_data["print_time_seconds"] = plate_time
  1079. # Gate both the grams headline AND the per-slot breakdown on the same
  1080. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1081. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1082. # to the project-level grams the archive columns already provide rather
  1083. # than ship a project-level headline next to an all-zero per-plate
  1084. # breakdown.
  1085. if plate_grams > 0:
  1086. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1087. archive_data["filament_slots"] = [
  1088. {
  1089. "slot_id": s.get("slot_id"),
  1090. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1091. "type": s.get("type", ""),
  1092. "color": s.get("color", ""),
  1093. }
  1094. for s in plate_slots
  1095. ]
  1096. return archive_data
  1097. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1098. """Best-effort filament metadata from the MQTT print-start snapshot.
  1099. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1100. file during print, see #1533) so the fallback PrintArchive still has
  1101. enough filament info to support the inventory views and AMS-expansion
  1102. planning the operator opens it for. Returns a dict with optional
  1103. ``filament_type`` and ``filament_color`` keys in the same
  1104. comma-separated format the 3MF extractor produces, so the rest of the
  1105. codebase treats the fallback archive identically to a normal one.
  1106. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1107. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1108. entries). When supplied, only the slots actually consumed by this
  1109. print contribute. Without it the function falls back to every loaded
  1110. AMS slot — less accurate but still useful.
  1111. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1112. that the unit tests pass directly, AND the on_print_start callback
  1113. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1114. bambu_mqtt service hands to main.py at runtime. The original
  1115. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1116. handled the inner shape and silently returned ``{}`` for every real
  1117. print start, leaving fallback archives' filament fields NULL — the
  1118. exact regression the fix was meant to close. Reported with a log
  1119. proving the AMS state was right there at
  1120. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1121. """
  1122. result: dict[str, str] = {}
  1123. # Look at the on_print_start wrapper first, then the inner shape.
  1124. raw_data = (data or {}).get("raw_data")
  1125. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1126. if not isinstance(ams_root, dict):
  1127. ams_root = (data or {}).get("ams") or {}
  1128. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1129. if not isinstance(ams_units, list) or not ams_units:
  1130. return result
  1131. # Map global tray id (unit * 4 + tray) → (type, color).
  1132. loaded: dict[int, tuple[str, str]] = {}
  1133. for unit in ams_units:
  1134. if not isinstance(unit, dict):
  1135. continue
  1136. try:
  1137. unit_id = int(unit.get("id", 0))
  1138. except (TypeError, ValueError):
  1139. continue
  1140. for tray in unit.get("tray") or []:
  1141. if not isinstance(tray, dict):
  1142. continue
  1143. try:
  1144. tray_id = int(tray.get("id", 0))
  1145. except (TypeError, ValueError):
  1146. continue
  1147. ttype = (tray.get("tray_type") or "").strip()
  1148. tcolor = (tray.get("tray_color") or "").strip().upper()
  1149. if not ttype:
  1150. continue # Empty / unloaded slot.
  1151. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1152. if not loaded:
  1153. return result
  1154. if ams_mapping:
  1155. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1156. filaments = [loaded[g] for g in used_ids if g in loaded]
  1157. if not filaments:
  1158. return result # Mapping points entirely at slots we have no data for.
  1159. else:
  1160. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1161. types_joined = ",".join(f[0] for f in filaments)
  1162. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1163. # Column limits per backend/app/models/archive.py: filament_type=50,
  1164. # filament_color=200.
  1165. if types_joined:
  1166. result["filament_type"] = types_joined[:50]
  1167. if colors_joined:
  1168. result["filament_color"] = colors_joined[:200]
  1169. return result
  1170. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1171. """Start a layer-timelapse session for *archive_id* when the printer has
  1172. an external camera configured. Returns True if a session was started.
  1173. Three call sites in on_print_start (expected-archive promotion, fallback
  1174. archive creation, fresh-archive creation) used to inline this same
  1175. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1176. on the first pass). Centralising the conditional + call here makes the
  1177. contract testable in isolation and keeps the three sites locked in step.
  1178. """
  1179. if not (printer.external_camera_enabled and printer.external_camera_url):
  1180. return False
  1181. from backend.app.services.layer_timelapse import start_session
  1182. start_session(
  1183. printer_id,
  1184. archive_id,
  1185. printer.external_camera_url,
  1186. printer.external_camera_type or "mjpeg",
  1187. snapshot_url=printer.external_camera_snapshot_url,
  1188. rotation=getattr(printer, "camera_rotation", 0),
  1189. )
  1190. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1191. return True
  1192. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1193. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1194. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1195. — since #2926 — the description the parser already resolved, which is preferred
  1196. when present so the queue's failure reason reads the same as the status
  1197. response. The short code still produces the bracketed label, and still
  1198. resolves the sentence for a caller whose entries predate the field. An entry
  1199. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1200. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1201. label when no description is on file. Returns None for an empty list so
  1202. callers can leave error_message unset.
  1203. """
  1204. if not hms_errors:
  1205. return None
  1206. from backend.app.services.hms_errors import get_error_description
  1207. parts: list[str] = []
  1208. for err in hms_errors:
  1209. try:
  1210. # `_hms_short_code` rather than a local derivation: this one used to
  1211. # format the error without masking it to 16 bits, so an `hms[]` entry
  1212. # whose code carries an alert-level group produced a five-digit label
  1213. # like "0500_3000A" — not a code the user can look up, and never a
  1214. # catalogue key, so the sentence was lost with it.
  1215. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1216. except (TypeError, ValueError):
  1217. continue
  1218. description = err.get("description") or get_error_description(short_code)
  1219. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1220. # groups and is not a code anyone can look up; its full code in the
  1221. # printer screen's four groups is (#2728).
  1222. full_code = str(err.get("full_code") or "")
  1223. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1224. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1225. return "; ".join(parts) if parts else None
  1226. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1227. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1228. print completes successfully. Gated to status=='completed': failed, cancelled
  1229. and aborted prints do not count as usage. Caller is responsible for committing
  1230. the session. No-op when the queue item has no linked library file (e.g. reprints
  1231. from an archive). See #1008."""
  1232. if queue_status != "completed" or item.library_file_id is None:
  1233. return
  1234. from backend.app.models.library import LibraryFile
  1235. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1236. if lib_file is None:
  1237. return
  1238. lib_file.print_count = (lib_file.print_count or 0) + 1
  1239. lib_file.last_printed_at = datetime.now(timezone.utc)
  1240. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1241. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1242. When on_print_complete fires with status 'failed' for a printer in this set we
  1243. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1244. rather than a 'print failed' notification.
  1245. """
  1246. _user_stopped_printers.add(printer_id)
  1247. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1248. _last_status_broadcast: dict[int, str] = {}
  1249. # Track printers where we've updated nozzle_count
  1250. _nozzle_count_updated: set[int] = set()
  1251. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1252. """Wait the debounce window then fire `on_printer_offline` if the printer
  1253. is still offline.
  1254. Scheduled by `on_printer_status_change` on the connected → disconnected
  1255. edge (#1752). Cancelled by the same handler if the printer reconnects
  1256. before the window elapses, so a single MQTT blip + recovery doesn't
  1257. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1258. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1259. route through the same status-change callback, so this covers both.
  1260. """
  1261. logger = logging.getLogger(__name__)
  1262. try:
  1263. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1264. still_offline = not printer_manager.is_connected(printer_id)
  1265. logger.info(
  1266. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1267. printer_id,
  1268. still_offline,
  1269. )
  1270. if not still_offline:
  1271. return
  1272. async with async_session() as db:
  1273. from backend.app.models.printer import Printer
  1274. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1275. printer = result.scalar_one_or_none()
  1276. if not printer:
  1277. logger.warning(
  1278. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1279. printer_id,
  1280. )
  1281. return
  1282. logger.info(
  1283. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1284. printer_id,
  1285. printer.name,
  1286. )
  1287. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1288. except asyncio.CancelledError:
  1289. raise
  1290. except Exception as e:
  1291. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1292. finally:
  1293. _printer_offline_notify_tasks.pop(printer_id, None)
  1294. def _hms_notify_key(error) -> str:
  1295. """What identifies a fault for notification de-duplication.
  1296. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1297. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1298. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1299. and -0006 together) shared a key and only the first was ever notified. An
  1300. entry without a full code falls back to attr and code together.
  1301. """
  1302. full_code = getattr(error, "full_code", "") or ""
  1303. if full_code:
  1304. return full_code.upper()
  1305. return f"{error.attr:08X}:{error.code}"
  1306. def _hms_fault_counts(error) -> bool:
  1307. """Whether a fault counts as a problem: the same rule the frontend's
  1308. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1309. It counts when Bambu publishes text for it or it offers action buttons, and
  1310. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1311. no actions does not count: those are things like "the top cover is open" or
  1312. "the chamber is hot, fan speed increased", which a printer can hold through
  1313. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1314. it always has; those are prompts such as "unable to start drying" (#2728).
  1315. """
  1316. if error.severity < 1:
  1317. return False
  1318. has_actions = bool(getattr(error, "actions", None))
  1319. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1320. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1321. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1322. """The new faults that count (see ``_hms_fault_counts``).
  1323. These go to the MQTT relay; the caller also needs a description before it
  1324. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1325. used to read ``severity >= 2`` when severity held the part byte; on the real
  1326. level that would drop the task-stopping errors (#2728).
  1327. """
  1328. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1329. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1330. """The faults on this printer not notified yet, and record them as notified.
  1331. Tracking is updated before anything is sent, so concurrent status callbacks
  1332. cannot notify the same fault twice. A notified fault is forgotten once it
  1333. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1334. and on is notified once (#3226), while one that clears and comes back much
  1335. later is notified again.
  1336. When ``print_state`` changes (a print resumed, started or finished), every
  1337. fault recorded so far is forgotten the first time it is gone, without the
  1338. wait: a runout fixed before resuming must be notified if it happens again a
  1339. few minutes later, while the printer sits paused. Not only the faults gone
  1340. at the change itself, because the update that flips the state can still
  1341. carry the old fault (a ``print_error`` entry stays until a payload brings
  1342. ``hms``).
  1343. """
  1344. now = time.time()
  1345. current = {_hms_notify_key(e) for e in errors}
  1346. seen = _notified_hms_errors.setdefault(printer_id, {})
  1347. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1348. if print_state is not None:
  1349. print_state = print_state.upper()
  1350. if _hms_print_state.get(printer_id, print_state) != print_state:
  1351. forget_when_gone.update(seen)
  1352. _hms_print_state[printer_id] = print_state
  1353. for key, last_seen in list(seen.items()):
  1354. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1355. del seen[key]
  1356. forget_when_gone.discard(key)
  1357. new = current - seen.keys()
  1358. for key in current:
  1359. seen[key] = now
  1360. if not seen:
  1361. _notified_hms_errors.pop(printer_id, None)
  1362. if not forget_when_gone:
  1363. _hms_forget_when_gone.pop(printer_id, None)
  1364. return _hms_errors_to_notify(errors, new)
  1365. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1366. # "Printing", -1 and 255 are "no stage" (#3211).
  1367. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1368. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1369. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1370. Records it as notified. Called only for a printing state with progress above 0.
  1371. Progress before the first layer is not progress through the print (#3211).
  1372. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1373. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1374. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1375. 75% notification together with Print Started, and since 75 was then on
  1376. record, 25 and 50 could never fire. So nothing counts while the printer
  1377. reports a layer count but has not started layer 1.
  1378. Without a layer count -- a print whose first frame carried no
  1379. ``total_layer_num``, until the pushall that asks for it is answered
  1380. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1381. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1382. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1383. reports neither keeps the old behaviour rather than never notifying.
  1384. """
  1385. if (state.layer_num or 0) < 1:
  1386. if (state.total_layers or 0) > 0:
  1387. return None
  1388. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1389. return None
  1390. progress = state.progress or 0
  1391. current_milestone = 0
  1392. if progress >= 75:
  1393. current_milestone = 75
  1394. elif progress >= 50:
  1395. current_milestone = 50
  1396. elif progress >= 25:
  1397. current_milestone = 25
  1398. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1399. _last_progress_milestone[printer_id] = current_milestone
  1400. return current_milestone
  1401. return None
  1402. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1403. """Handle printer status changes - broadcast via WebSocket."""
  1404. try:
  1405. notify_live_activities.observe(printer_id, state)
  1406. except Exception:
  1407. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1408. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1409. # transitions disconnected → connected — which covers both Bambuddy
  1410. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1411. # `reconcile_stale_active_prints` exactly once for this connection so
  1412. # any archive still in `status="printing"` that can't actually be
  1413. # running anymore (printer IDLE / different subtask / empty subtask)
  1414. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1415. # finished during a disconnect window + a smart-plug power cycle
  1416. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1417. # next boot. Reconciliation runs concurrently — it must not block the
  1418. # WebSocket dedup / broadcast logic below, and the connected edge is
  1419. # marked True BEFORE the await so concurrent status updates inside
  1420. # the same connection don't re-trigger reconciliation.
  1421. #
  1422. # Wait for a real push_status before reconciling (#1679): MQTT
  1423. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1424. # the connection, BEFORE `_request_push_all` round-trips. At that
  1425. # instant the `PrinterState` is still on construction defaults — most
  1426. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1427. # If reconcile spawns here, every in-flight archive falls through to
  1428. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1429. # creates a duplicate archive on the real PRINT COMPLETE and
  1430. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1431. # keeps the #1542 mechanism intact: once the first real push_status
  1432. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1433. # fires again with the flag still False — reconcile then runs against
  1434. # actual evidence.
  1435. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1436. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1437. _printer_reconciled_since_connect[printer_id] = True
  1438. spawn_background_task(
  1439. reconcile_stale_active_prints(printer_id),
  1440. name=f"reconcile-stale-prints-{printer_id}",
  1441. )
  1442. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1443. # Re-arm so the next reconnect triggers reconciliation again.
  1444. _printer_reconciled_since_connect[printer_id] = False
  1445. # Same edge, for the calibration table the AMS card reads its K values from.
  1446. #
  1447. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1448. # tables to ask for. A `state_known` gate alone is not enough: the first
  1449. # real push_status is what makes the state known, and the nozzle fields do
  1450. # not always arrive in it. Latching there would spend this connection's one
  1451. # attempt on a printer that could not yet say what was fitted.
  1452. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1453. if (
  1454. state.connected
  1455. and state_known
  1456. and nozzle_known
  1457. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1458. ):
  1459. _printer_kprofiles_primed_since_connect[printer_id] = True
  1460. spawn_background_task(
  1461. prime_kprofile_table(printer_id),
  1462. name=f"prime-kprofiles-{printer_id}",
  1463. )
  1464. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1465. _printer_kprofiles_primed_since_connect[printer_id] = False
  1466. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1467. # else in the AMS report changing -- a power cycle does it to every slot --
  1468. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1469. # while the printer is idle; needs_check is cheap and throttled per slot.
  1470. # Guarded: nothing here may stop the status broadcast below.
  1471. try:
  1472. if not state.connected:
  1473. kprofile_drift.forget_printer(printer_id)
  1474. elif kprofile_drift.needs_check(printer_id, state):
  1475. spawn_background_task(
  1476. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1477. name=f"reapply-kprofiles-{printer_id}",
  1478. )
  1479. except Exception:
  1480. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1481. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1482. # connected → disconnected. The "back online" channel is already covered
  1483. # by the print-failure notification (firmware reports gcode_state=FAILED
  1484. # on reconnect of an interrupted print), so we don't add a symmetric
  1485. # online event here.
  1486. prev_connected = _printer_last_connected.get(printer_id)
  1487. _printer_last_connected[printer_id] = state.connected
  1488. if prev_connected is True and not state.connected:
  1489. existing = _printer_offline_notify_tasks.get(printer_id)
  1490. if existing is None or existing.done():
  1491. logging.getLogger(__name__).info(
  1492. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1493. printer_id,
  1494. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1495. )
  1496. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1497. _maybe_notify_printer_offline(printer_id),
  1498. name=f"printer-offline-notify-{printer_id}",
  1499. )
  1500. elif state.connected:
  1501. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1502. if pending is not None and not pending.done():
  1503. logging.getLogger(__name__).info(
  1504. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1505. printer_id,
  1506. )
  1507. pending.cancel()
  1508. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1509. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1510. temps = state.temperatures or {}
  1511. nozzle_temp = round(temps.get("nozzle", 0))
  1512. bed_temp = round(temps.get("bed", 0))
  1513. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1514. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1515. # Auto-detect dual-nozzle printers from MQTT temperature data
  1516. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1517. _nozzle_count_updated.add(printer_id)
  1518. # Update nozzle_count in database
  1519. async with async_session() as db:
  1520. from backend.app.models.printer import Printer
  1521. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1522. printer = result.scalar_one_or_none()
  1523. if printer and printer.nozzle_count != 2:
  1524. printer.nozzle_count = 2
  1525. await db.commit()
  1526. logging.getLogger(__name__).info(
  1527. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1528. )
  1529. # Include target temps for heating phase detection
  1530. bed_target = round(temps.get("bed_target", 0))
  1531. nozzle_target = round(temps.get("nozzle_target", 0))
  1532. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1533. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1534. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1535. #
  1536. # dry_countdown_stalled rides along because it is the one drying signal the
  1537. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1538. # dry_time stopped moving, so on the frame that flips it every other member
  1539. # of this key is identical and the push would be deduplicated away. Mid-print
  1540. # a temperature would eventually break the tie, but a parked command on an
  1541. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1542. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1543. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1544. ams_dry_key = (
  1545. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1546. if state.raw_data
  1547. else ()
  1548. )
  1549. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1550. #
  1551. # The filament identity fields are here because Configure Slot writes
  1552. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1553. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1554. # matched, this function returned before broadcasting, and the card kept
  1555. # showing the old filament until the 30s fallback poll or a page reload —
  1556. # even though the configure route asks the printer for a fresh pushall and
  1557. # that push does carry the new values. Reset always worked, because it
  1558. # clears tray_type.
  1559. #
  1560. # These fields only change when someone configures a slot or swaps a spool,
  1561. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1562. ams_tray_key = (
  1563. tuple(
  1564. (
  1565. t.get("id"),
  1566. t.get("tray_type", ""),
  1567. t.get("state"),
  1568. t.get("tray_color", ""),
  1569. t.get("tray_info_idx", ""),
  1570. t.get("tray_sub_brands", ""),
  1571. t.get("cali_idx"),
  1572. )
  1573. for a in (state.raw_data.get("ams") or [])
  1574. for t in a.get("tray", [])
  1575. )
  1576. if state.raw_data
  1577. else ()
  1578. )
  1579. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1580. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1581. # in the AMS change-hash (tray fields only, and widening that would fire
  1582. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1583. # screen changed no key at all and the card's inlet badges sat stale until a
  1584. # reload. Like the filament-backup flag, these only move when someone
  1585. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1586. fts_key = (
  1587. state.fila_switch.installed if state.fila_switch else False,
  1588. tuple(sorted(state.ams_switch_inlet.items())),
  1589. # Which hotend holds which slot. Unlike the two above this does move
  1590. # mid-print, on every filament change — but only between discrete slots,
  1591. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1592. # it live: it decides which hotend the Load dialog may offer and whether
  1593. # Unload has anything to act on.
  1594. tuple(
  1595. sorted(
  1596. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1597. # Sort on the extruder id alone: the other members are nullable
  1598. # and comparing None with an int raises.
  1599. key=lambda entry: entry[0],
  1600. )
  1601. ),
  1602. )
  1603. status_key = (
  1604. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1605. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1606. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1607. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1608. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1609. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1610. )
  1611. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1612. if not is_active_print:
  1613. _unauthorized_print_kill_sent.discard(printer_id)
  1614. elif printer_id in _unauthorized_print_kill_sent:
  1615. # stop_print() was already sent for this print; avoid all further
  1616. # ownership and settings work until the printer leaves an active state.
  1617. pass
  1618. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1619. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1620. _unauthorized_print_kill_sent.discard(printer_id)
  1621. else:
  1622. kill_switch_enabled = False
  1623. authorization: bool | None = None
  1624. status_logger = logging.getLogger(__name__)
  1625. try:
  1626. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1627. if kill_switch_enabled:
  1628. async with async_session() as db:
  1629. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1630. except Exception as e:
  1631. # Fail safe: a database/reconciliation error must never turn into an
  1632. # irreversible stop of a print whose ownership is still unknown.
  1633. authorization = None
  1634. status_logger.warning(
  1635. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1636. )
  1637. if not kill_switch_enabled or authorization is True:
  1638. _unauthorized_print_kill_sent.discard(printer_id)
  1639. elif authorization is None:
  1640. _unauthorized_print_kill_sent.discard(printer_id)
  1641. status_logger.debug(
  1642. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1643. printer_id,
  1644. )
  1645. else:
  1646. try:
  1647. stopped = printer_manager.stop_print(printer_id)
  1648. if stopped:
  1649. _unauthorized_print_kill_sent.add(printer_id)
  1650. printer_info = printer_manager.get_printer(printer_id)
  1651. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1652. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1653. notification_data = {
  1654. "status": "stopped",
  1655. "filename": state.gcode_file or state.current_print or "",
  1656. "subtask_name": state.subtask_name or "",
  1657. "progress": state.progress,
  1658. "reason": "unauthorized_print",
  1659. }
  1660. status_logger.warning(
  1661. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1662. printer_id,
  1663. state.state,
  1664. )
  1665. try:
  1666. await ws_manager.broadcast(
  1667. {
  1668. "type": "kill_switch_triggered",
  1669. "printer_id": printer_id,
  1670. "printer_name": printer_name,
  1671. "filename": filename,
  1672. "reason": "unauthorized_print",
  1673. }
  1674. )
  1675. except Exception as e:
  1676. status_logger.warning(
  1677. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1678. )
  1679. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1680. if previous_task is not None and not previous_task.done():
  1681. previous_task.cancel()
  1682. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1683. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1684. name=f"kill-switch-notification-{printer_id}",
  1685. )
  1686. else:
  1687. status_logger.warning(
  1688. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1689. printer_id,
  1690. state.state,
  1691. )
  1692. except Exception as e:
  1693. status_logger.warning(
  1694. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1695. )
  1696. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1697. try:
  1698. printer_info = printer_manager.get_printer(printer_id)
  1699. if printer_info:
  1700. await mqtt_relay.on_printer_status(
  1701. printer_id,
  1702. state,
  1703. printer_info.name,
  1704. printer_info.serial_number,
  1705. printer_manager.is_awaiting_plate_clear(printer_id),
  1706. )
  1707. except Exception:
  1708. pass # Don't fail status callback if MQTT fails
  1709. if _last_status_broadcast.get(printer_id) == status_key:
  1710. return # No change, skip WebSocket broadcast
  1711. _last_status_broadcast[printer_id] = status_key
  1712. # Check for progress milestone notifications (25%, 50%, 75%)
  1713. progress = state.progress or 0
  1714. is_printing = state.state in ("RUNNING", "PRINTING")
  1715. if is_printing and progress > 0:
  1716. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1717. if current_milestone is not None:
  1718. try:
  1719. from backend.app.models.printer import Printer
  1720. # Read the printer in a short session and release the connection
  1721. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1722. # pinned a pooled connection per milestone, per printer (issue #2572).
  1723. async with async_session() as db:
  1724. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1725. printer = result.scalar_one_or_none()
  1726. printer_name = printer.name if printer else f"Printer {printer_id}"
  1727. filename = state.subtask_name or state.gcode_file or "Unknown"
  1728. # remaining_time is in minutes, convert to seconds for notification
  1729. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1730. # Capture camera snapshot for notification image attachment (no DB held).
  1731. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1732. # Notification send needs a session (provider/template lookups).
  1733. async with async_session() as db:
  1734. await notification_service.on_print_progress(
  1735. printer_id,
  1736. printer_name,
  1737. filename,
  1738. current_milestone,
  1739. db,
  1740. remaining_time_seconds,
  1741. image_data=image_data,
  1742. )
  1743. except Exception as e:
  1744. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1745. elif progress < 5:
  1746. # Reset milestone tracking when print restarts or new print begins
  1747. _last_progress_milestone[printer_id] = 0
  1748. _first_layer_notified[printer_id] = False
  1749. # HMS error codes that should not trigger notifications even though they
  1750. # have known descriptions (e.g. user-initiated actions, not real errors).
  1751. _HMS_NOTIFICATION_SUPPRESS = {
  1752. "0500_400E", # Printing was cancelled (user action, not an error)
  1753. }
  1754. # Check for new HMS errors and send notifications
  1755. current_hms_errors = getattr(state, "hms_errors", []) or []
  1756. if current_hms_errors:
  1757. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1758. if new_errors:
  1759. try:
  1760. from backend.app.models.printer import Printer
  1761. # Read the printer in a short session and release the connection
  1762. # BEFORE the ~15s camera snapshot below (issue #2572).
  1763. async with async_session() as db:
  1764. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1765. printer = result.scalar_one_or_none()
  1766. printer_name = printer.name if printer else f"Printer {printer_id}"
  1767. # Format error details for notification
  1768. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1769. module_names = {
  1770. 0x03: "Print/Task",
  1771. 0x05: "Nozzle/Extruder",
  1772. 0x07: "AMS/Filament",
  1773. 0x0C: "Motion Controller",
  1774. 0x12: "Chamber",
  1775. }
  1776. # Capture camera snapshot once for all error notifications (no DB held).
  1777. error_image_data = await _capture_snapshot_for_notification(
  1778. printer_id, printer, logging.getLogger(__name__)
  1779. )
  1780. # Notification sends need a session (provider/template lookups).
  1781. async with async_session() as db:
  1782. sent_count = 0
  1783. for error in new_errors:
  1784. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1785. # Build short code like "0700_8010"
  1786. # Mask to 16 bits to handle printers that send larger values
  1787. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1788. error_code_masked = error_code_int & 0xFFFF
  1789. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1790. # Only notify for errors Bambu publishes text for — printers
  1791. # send undocumented codes that aren't real errors, and Bambu
  1792. # lists some with empty text. Resolved at parse time (#2926);
  1793. # short_code is still needed for the suppression set below.
  1794. description = error.description
  1795. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1796. continue
  1797. error_type = f"{module_name} Error"
  1798. error_detail = description
  1799. await notification_service.on_printer_error(
  1800. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1801. )
  1802. sent_count += 1
  1803. if sent_count:
  1804. logging.getLogger(__name__).info(
  1805. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1806. )
  1807. # Also publish to MQTT relay (no DB): every new fault that
  1808. # counts, with or without text, the same set the UI counts.
  1809. printer_info = printer_manager.get_printer(printer_id)
  1810. if printer_info:
  1811. errors_data = [
  1812. {
  1813. "code": e.code,
  1814. "attr": e.attr,
  1815. "module": e.module,
  1816. "severity": e.severity,
  1817. }
  1818. for e in new_errors
  1819. ]
  1820. await mqtt_relay.on_printer_error(
  1821. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1822. )
  1823. except Exception as e:
  1824. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1825. else:
  1826. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1827. # across a print state change) are forgotten. Some codes, e.g. chamber
  1828. # temperature regulation during PETG prints, toggle every few seconds.
  1829. _take_new_hms_faults(printer_id, [], state.state)
  1830. await ws_manager.send_printer_status(
  1831. printer_id,
  1832. printer_state_to_dict(
  1833. state,
  1834. printer_id,
  1835. printer_manager.get_model(printer_id),
  1836. printer_manager.get_drying_targets(printer_id),
  1837. ),
  1838. )
  1839. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1840. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1841. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1842. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1843. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1844. K-profiles are per-nozzle and the printer's calibration table is numbered
  1845. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1846. switch's other inlet therefore silently invalidates every configured slot in
  1847. it: the index stays put and now resolves against the other nozzle's table.
  1848. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1849. and 0.020 on the right kept the left profile after the move, and a manual
  1850. RFID re-read only re-asserted the same wrong one.
  1851. Configuring a slot is a deliberate preparation step, so this re-selects
  1852. rather than re-configures: only the calibration binding moves, and only for
  1853. slots whose spool already has a stored profile for the new nozzle. A slot
  1854. Bambuddy knows nothing about is left exactly as the operator left it.
  1855. """
  1856. logger = logging.getLogger(__name__)
  1857. target_extruder = extruder_for_inlet(inlet)
  1858. if target_extruder is None:
  1859. return
  1860. client = printer_manager.get_client(printer_id)
  1861. state = printer_manager.get_status(printer_id)
  1862. if not client or not state or not state.raw_data:
  1863. return
  1864. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1865. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1866. # the nozzle width, which changes both the K profile to select and the
  1867. # preset the slot should carry.
  1868. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1869. ams_raw = state.raw_data.get("ams")
  1870. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1871. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1872. if not unit:
  1873. return
  1874. try:
  1875. async with async_session() as db:
  1876. for tray in unit.get("tray", []):
  1877. tray_id = int(tray.get("id", -1))
  1878. if tray_id < 0 or not tray.get("tray_type"):
  1879. continue
  1880. current_idx = tray.get("cali_idx")
  1881. profile = await find_slot_kprofile_for_extruder(
  1882. db,
  1883. printer_id,
  1884. ams_id,
  1885. tray_id,
  1886. target_extruder,
  1887. nozzle_diameter,
  1888. printer_manager.get_model(printer_id),
  1889. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1890. )
  1891. if profile is None or profile.cali_idx is None:
  1892. continue
  1893. if current_idx == profile.cali_idx:
  1894. continue # Already on the right one.
  1895. logger.info(
  1896. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1897. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1898. printer_id,
  1899. ams_id,
  1900. tray_id,
  1901. inlet,
  1902. target_extruder,
  1903. profile.name,
  1904. current_idx,
  1905. profile.cali_idx,
  1906. profile.k_value,
  1907. )
  1908. client.extrusion_cali_sel(
  1909. ams_id=ams_id,
  1910. tray_id=tray_id,
  1911. cali_idx=profile.cali_idx,
  1912. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1913. nozzle_diameter=nozzle_diameter,
  1914. )
  1915. except Exception as e:
  1916. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1917. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1918. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1919. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1920. from the delayed re-check -- which is why it takes the AMS data and print
  1921. state as arguments instead of reading them from the push (#3186).
  1922. """
  1923. logger = logging.getLogger(__name__)
  1924. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1925. # Auto-unlink spool assignments with stale fingerprints. Under the
  1926. # per-printer assignment lock since #3186: the held-removal re-check runs
  1927. # this outside any MQTT push, so it can now overlap one.
  1928. try:
  1929. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1930. from sqlalchemy.orm import selectinload
  1931. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1932. from backend.app.models.spool import Spool as _Spool
  1933. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1934. from backend.app.services.ams_slot_presence import spool_present
  1935. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1936. # Built-in assignments only. Since #2812 they survive a switch to
  1937. # Spoolman mode rather than being deleted by it, and this pass ends
  1938. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1939. # time as the AMS contents changed under the other mode, undoing the
  1940. # preservation more slowly but just as completely.
  1941. assignments = []
  1942. if not await spoolman_owns_assignments(db):
  1943. result = await db.execute(
  1944. select(SA)
  1945. .where(SA.printer_id == printer_id)
  1946. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1947. )
  1948. assignments = result.scalars().all()
  1949. # ``printing_now`` (top of this function) keeps a runout from
  1950. # unlinking the spool that fed the print — the next idle-time pass
  1951. # unlinks it if the user really did take it out.
  1952. stale = []
  1953. # Removals this pass is holding rather than unlinking (#3186).
  1954. held: set[tuple] = set()
  1955. for assignment in assignments:
  1956. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1957. if assignment.ams_id == 255:
  1958. ps = printer_manager.get_status(printer_id)
  1959. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1960. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1961. current_tray = None
  1962. for vt in vt_tray_raw:
  1963. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1964. current_tray = vt
  1965. break
  1966. if not current_tray:
  1967. # vt_tray data may not have arrived yet — keep assignment
  1968. continue
  1969. else:
  1970. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1971. if not current_tray:
  1972. if printing_now:
  1973. logger.info(
  1974. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1975. assignment.spool_id,
  1976. assignment.ams_id,
  1977. assignment.tray_id,
  1978. )
  1979. continue
  1980. # A whole AMS unit can drop out of one push and come back in
  1981. # the next; only a slot that stays gone is a removal (#3186).
  1982. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  1983. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  1984. held.add(hold_key)
  1985. logger.info(
  1986. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  1987. "unlinking if it is still gone in %ds",
  1988. assignment.spool_id,
  1989. assignment.ams_id,
  1990. assignment.tray_id,
  1991. int(slot_unlink_grace.GRACE_SECONDS),
  1992. )
  1993. continue
  1994. logger.info(
  1995. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1996. assignment.spool_id,
  1997. assignment.ams_id,
  1998. assignment.tray_id,
  1999. )
  2000. stale.append(assignment) # Slot empty
  2001. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2002. # A Bambu Lab spool is in this slot — check if it's the same spool
  2003. # that's currently assigned. If yes, keep the assignment (avoids
  2004. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2005. # the printer's filament preset on every startup).
  2006. tray_uuid = current_tray.get("tray_uuid", "")
  2007. tag_uid = current_tray.get("tag_uid", "")
  2008. spool = assignment.spool
  2009. spool_matches = False
  2010. if spool:
  2011. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2012. spool.tag_uid
  2013. and tag_uid
  2014. and tag_uid != "0000000000000000"
  2015. and spool.tag_uid.upper() == tag_uid.upper()
  2016. ):
  2017. spool_matches = True
  2018. if spool_matches:
  2019. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2020. cur_color = current_tray.get("tray_color", "")
  2021. cur_type = current_tray.get("tray_type", "")
  2022. fp_color = assignment.fingerprint_color or ""
  2023. fp_type = assignment.fingerprint_type or ""
  2024. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2025. assignment.fingerprint_color = cur_color
  2026. assignment.fingerprint_type = cur_type
  2027. logger.debug(
  2028. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2029. assignment.spool_id,
  2030. assignment.ams_id,
  2031. assignment.tray_id,
  2032. )
  2033. continue
  2034. # Different BL spool or unrecognized — unlink so auto-assign can match
  2035. logger.info(
  2036. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2037. assignment.spool_id,
  2038. assignment.ams_id,
  2039. assignment.tray_id,
  2040. tray_uuid,
  2041. )
  2042. stale.append(assignment)
  2043. else:
  2044. cur_color = current_tray.get("tray_color", "")
  2045. cur_type = current_tray.get("tray_type", "")
  2046. cur_state = current_tray.get("state")
  2047. fp_color = assignment.fingerprint_color or ""
  2048. fp_type = assignment.fingerprint_type or ""
  2049. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2050. # the slot was empty when the user pre-assigned via SpoolBuddy
  2051. # (the firmware drops ams_filament_setting on empty slots, so
  2052. # MQTT was deferred). The moment any filament gets inserted
  2053. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2054. # reconfigured spool — fire the deferred configuration.
  2055. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2056. # extruder" code) OR, on firmwares that don't use the state
  2057. # enum meaningfully, a non-empty tray_type when state is
  2058. # NOT one of the firmware's explicit empty signals (9, 10).
  2059. # state-only was wrong for firmwares that never set 11 — A1
  2060. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2061. # always report state=3 — so the replay never fired for them
  2062. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2063. # explicit "empty" signals authoritative over any stale
  2064. # tray_type that might survive the relay's auto-clearing.
  2065. #
  2066. # tray_exist_bits comes first because that guard cannot tell
  2067. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2068. # writes state=9 when the bit is 0 and leaves it there when the
  2069. # bit returns. A non-RFID spool inserted into a pre-assigned
  2070. # slot brings no tray_type with it, so the stale 9 made this
  2071. # expression false forever and the deferred config never fired
  2072. # — the deadlock #1322 removed from the assign path, still in
  2073. # place here (#3084, #3100).
  2074. loaded = spool_present(current_tray) is True or (
  2075. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2076. )
  2077. if not fp_type.strip() and loaded and assignment.spool:
  2078. try:
  2079. from backend.app.api.routes.inventory import (
  2080. apply_spool_to_slot_via_mqtt,
  2081. )
  2082. await apply_spool_to_slot_via_mqtt(
  2083. db=db,
  2084. current_user=None,
  2085. spool=assignment.spool,
  2086. printer_id=printer_id,
  2087. ams_id=assignment.ams_id,
  2088. tray_id=assignment.tray_id,
  2089. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2090. current_tray_type=cur_type,
  2091. )
  2092. logger.info(
  2093. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2094. assignment.spool_id,
  2095. printer_id,
  2096. assignment.ams_id,
  2097. assignment.tray_id,
  2098. )
  2099. except Exception:
  2100. logger.exception(
  2101. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2102. assignment.spool_id,
  2103. printer_id,
  2104. assignment.ams_id,
  2105. assignment.tray_id,
  2106. )
  2107. assignment.fingerprint_color = cur_color
  2108. assignment.fingerprint_type = cur_type
  2109. continue
  2110. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2111. # Blank tray data mid-print is a runout, not a swap: the
  2112. # firmware clears colour and type when it unloads a spool
  2113. # it just emptied. Unlinking here would erase the record
  2114. # of which spool fed the print so far.
  2115. if printing_now and not cur_color.strip() and not cur_type.strip():
  2116. logger.info(
  2117. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2118. "(runout?)",
  2119. assignment.spool_id,
  2120. assignment.ams_id,
  2121. assignment.tray_id,
  2122. )
  2123. continue
  2124. # Same reasoning off the print, on firmware's own say-so:
  2125. # a blank tray report from a slot whose tray_exist_bits
  2126. # bit is set describes a spool the AMS cannot identify —
  2127. # a non-RFID one, or one whose slot was reset — not a
  2128. # spool that was taken out. Deleting the assignment there
  2129. # threw away the identity the user had supplied, which is
  2130. # the only place it existed (#3100). A slot the bit calls
  2131. # empty, or one that carries no bit at all, still unlinks.
  2132. #
  2133. # Unless the slot was reported empty first: a removal
  2134. # already held means a spool came out and another went
  2135. # in, so the blank report keeps the hold running below
  2136. # rather than cancelling it (#3186).
  2137. if (
  2138. spool_present(current_tray) is True
  2139. and not cur_color.strip()
  2140. and not cur_type.strip()
  2141. and not slot_unlink_grace.is_held(
  2142. printer_id,
  2143. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2144. )
  2145. ):
  2146. logger.info(
  2147. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2148. "tray reports no filament data yet",
  2149. assignment.spool_id,
  2150. assignment.ams_id,
  2151. assignment.tray_id,
  2152. )
  2153. continue
  2154. # A blank report the presence bit does not vouch for is
  2155. # still only one push. An idle X1C cleared a whole AMS
  2156. # unit's bits, colour and type for a moment and lost
  2157. # four saved assignments that way (#3186); unlink only
  2158. # if the slot is still blank after the grace period.
  2159. if not cur_color.strip() and not cur_type.strip():
  2160. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2161. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2162. held.add(hold_key)
  2163. logger.info(
  2164. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2165. "unlinking if it is still blank in %ds",
  2166. assignment.spool_id,
  2167. assignment.ams_id,
  2168. assignment.tray_id,
  2169. int(slot_unlink_grace.GRACE_SECONDS),
  2170. )
  2171. continue
  2172. # Fingerprint mismatch — but check if tray now matches the
  2173. # assigned spool (e.g. auto-configure changed the tray).
  2174. # Both sides are reduced to the type the slot can carry
  2175. # before comparing: the assign path writes that rather
  2176. # than the spool's raw material (#2902), so a spool whose
  2177. # material is a product line — "PLA+", "HTPLA" — reports
  2178. # back as "PLA" and would otherwise fail this check and
  2179. # be auto-unlinked from the slot it was just assigned to.
  2180. # Reducing the printer's side too keeps slots configured
  2181. # by an older Bambuddy, still reporting "PLA+", matching.
  2182. spool = assignment.spool
  2183. if spool:
  2184. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2185. # Two ways the assign path can have arrived at the
  2186. # slot's type, so both count as "we wrote this".
  2187. # The material column is one; the spool's preset is
  2188. # the other, and it outranks the material when the
  2189. # spool has one -- a spool whose material says PLA
  2190. # and whose preset is "Bambu PLA Aero" puts
  2191. # PLA-AERO in the slot (#2902). Read from the stored
  2192. # preset name rather than resolving the preset,
  2193. # because this runs on every AMS push and a cloud
  2194. # lookup here would be both slow and unavailable on
  2195. # the unauthenticated replay path.
  2196. spool_types = {printer_filament_type(spool.material).upper()}
  2197. if spool.slicer_filament_name:
  2198. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2199. # An imported local preset stores its type outright,
  2200. # which is what the assign path used -- and the name
  2201. # above may be unset. One keyed read, and only on a
  2202. # mismatch, which is rare.
  2203. #
  2204. # slicer_filament is free text up to fifty characters,
  2205. # so the digits have to be checked against the range
  2206. # of the integer primary key they are about to be
  2207. # compared with. Postgres raises on an out-of-range
  2208. # integer rather than simply not matching, and that
  2209. # would poison this session and abandon the rest of
  2210. # the cleanup pass.
  2211. lp_ref = (spool.slicer_filament or "").strip()
  2212. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2213. from backend.app.models.local_preset import LocalPreset as _LP
  2214. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2215. if lp_type:
  2216. spool_types.add(printer_filament_type(lp_type).upper())
  2217. if (
  2218. _colors_similar(cur_color, spool_color)
  2219. and printer_filament_type(cur_type).upper() in spool_types
  2220. ):
  2221. logger.info(
  2222. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2223. assignment.spool_id,
  2224. assignment.ams_id,
  2225. assignment.tray_id,
  2226. )
  2227. assignment.fingerprint_color = cur_color
  2228. assignment.fingerprint_type = cur_type
  2229. continue
  2230. logger.info(
  2231. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2232. assignment.spool_id,
  2233. assignment.ams_id,
  2234. assignment.tray_id,
  2235. cur_color,
  2236. cur_type,
  2237. fp_color,
  2238. fp_type,
  2239. spool.rgba if spool else "?",
  2240. spool.material if spool else "?",
  2241. )
  2242. stale.append(assignment) # Spool changed
  2243. slot_unlink_grace.settle(printer_id, "inventory", held)
  2244. # Snapshot slots before delete — ORM attribute access after the
  2245. # commit would refresh against a deleted row.
  2246. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2247. for a in stale:
  2248. await db.delete(a)
  2249. if stale:
  2250. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2251. # Commit any changes (stale deletions and/or fingerprint updates)
  2252. await db.commit()
  2253. # Tell open browsers the assignment is gone (#2575). Only the manual
  2254. # REST assign/unassign endpoints broadcast this event; without it the
  2255. # frontend's spool-assignments cache keeps rendering the unlinked
  2256. # spool on the slot until an unrelated refetch — which reads exactly
  2257. # like "the fix didn't work" (reporter verified: a browser refresh
  2258. # after the swap showed the correct state all along).
  2259. for ams_id, tray_id in unlinked_slots:
  2260. await ws_manager.broadcast(
  2261. {
  2262. "type": "spool_assignment_changed",
  2263. "printer_id": printer_id,
  2264. "ams_id": ams_id,
  2265. "tray_id": tray_id,
  2266. }
  2267. )
  2268. except Exception as e:
  2269. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2270. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2271. """Delete Spoolman slot rows whose held removal has run its grace period.
  2272. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2273. talks to Spoolman for every tray; this only needs the local rows, so it
  2274. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2275. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2276. not in a slot the presence bit calls occupied -- and nothing else.
  2277. """
  2278. logger = logging.getLogger(__name__)
  2279. try:
  2280. async with async_session() as db:
  2281. from backend.app.api.routes.settings import get_setting
  2282. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2283. from backend.app.services.ams_slot_presence import spool_present
  2284. enabled = await get_setting(db, "spoolman_enabled")
  2285. if not enabled or enabled.lower() != "true":
  2286. return
  2287. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2288. if sync_mode and sync_mode != "auto":
  2289. return
  2290. trays: dict[tuple[int, int], dict] = {}
  2291. for ams_unit in ams_data or []:
  2292. if not isinstance(ams_unit, dict):
  2293. continue
  2294. for tray in ams_unit.get("tray", []):
  2295. if isinstance(tray, dict):
  2296. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2297. rows = (
  2298. (
  2299. await db.execute(
  2300. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2301. )
  2302. )
  2303. .scalars()
  2304. .all()
  2305. )
  2306. held: set[tuple] = set()
  2307. expired: list[tuple[int, int]] = []
  2308. for row in rows:
  2309. tray = trays.get((row.ams_id, row.tray_id))
  2310. if tray is None or printing_now:
  2311. continue
  2312. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2313. continue
  2314. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2315. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2316. continue
  2317. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2318. expired.append((row.ams_id, row.tray_id))
  2319. else:
  2320. held.add(hold_key)
  2321. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2322. if not expired:
  2323. return
  2324. # A statement rather than ORM deletes, like the sync pass: the two
  2325. # can overlap, and a row the other already removed must not fail
  2326. # this commit.
  2327. for ams_id, tray_id in expired:
  2328. await db.execute(
  2329. delete(SpoolmanSlotAssignment).where(
  2330. SpoolmanSlotAssignment.printer_id == printer_id,
  2331. SpoolmanSlotAssignment.ams_id == ams_id,
  2332. SpoolmanSlotAssignment.tray_id == tray_id,
  2333. )
  2334. )
  2335. await db.commit()
  2336. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2337. for ams_id, tray_id in expired:
  2338. await ws_manager.broadcast(
  2339. {
  2340. "type": "spool_assignment_changed",
  2341. "printer_id": printer_id,
  2342. "ams_id": ams_id,
  2343. "tray_id": tray_id,
  2344. }
  2345. )
  2346. except Exception as e:
  2347. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2348. async def _recheck_held_unlinks(printer_id: int) -> None:
  2349. """Re-run just the slot cleanup against the printer's current AMS state.
  2350. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2351. passes otherwise run only when the AMS hash changes, and a slot that went
  2352. empty and stayed empty may never change it again.
  2353. """
  2354. status = printer_manager.get_status(printer_id)
  2355. # A disconnected printer's state is its last report, not a new one: acting
  2356. # on it would "confirm" a removal nobody has seen for the whole grace
  2357. # period. Leave the holds; the first push after reconnecting decides.
  2358. if status is None or not status.connected:
  2359. return
  2360. ams_raw = status.raw_data.get("ams")
  2361. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2362. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2363. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2364. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2365. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2366. async def on_ams_change(printer_id: int, ams_data: list):
  2367. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2368. logger = logging.getLogger(__name__)
  2369. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2370. # on_print_complete may pop _active_sessions during our awaits (#880).
  2371. from backend.app.services.usage_tracker import _active_sessions
  2372. _print_active = printer_id in _active_sessions
  2373. # A slot that reports empty while a print is running is a filament runout,
  2374. # not a spool swap: the spool is still physically in the AMS, just
  2375. # consumed. Dropping either inventory backend's slot link there loses the
  2376. # only record of which spool fed the print, so the completion path can't
  2377. # charge the runout segment to anything. Both cleanup passes below consult
  2378. # this; computed once, up front, so neither depends on the other having run.
  2379. _unlink_state = printer_manager.get_status(printer_id)
  2380. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2381. # MQTT relay - publish AMS change
  2382. try:
  2383. printer_info = printer_manager.get_printer(printer_id)
  2384. if printer_info:
  2385. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2386. except Exception:
  2387. pass # Don't fail AMS callback if MQTT fails
  2388. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2389. # This ensures frontend gets immediate updates when AMS slots are configured
  2390. try:
  2391. state = printer_manager.get_status(printer_id)
  2392. if state:
  2393. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2394. await ws_manager.send_printer_status(
  2395. printer_id,
  2396. printer_state_to_dict(
  2397. state,
  2398. printer_id,
  2399. printer_manager.get_model(printer_id),
  2400. printer_manager.get_drying_targets(printer_id),
  2401. ),
  2402. )
  2403. except Exception as e:
  2404. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2405. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2406. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2407. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2408. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2409. # "no existing assignment" for the same (printer, ams, tray) and race to
  2410. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2411. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2412. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2413. try:
  2414. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2415. from sqlalchemy.orm import selectinload
  2416. from backend.app.api.routes.settings import get_setting
  2417. from backend.app.models.spool import Spool
  2418. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2419. from backend.app.services.spool_tag_matcher import (
  2420. auto_assign_spool,
  2421. create_spool_from_tray,
  2422. find_matching_untagged_spool,
  2423. get_spool_by_tag,
  2424. is_bambu_tag,
  2425. is_valid_tag,
  2426. link_tag_to_inventory_spool,
  2427. )
  2428. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2429. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2430. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2431. if not _spoolman_on or _spoolman_on.lower() != "true":
  2432. for ams_unit in ams_data:
  2433. if not isinstance(ams_unit, dict):
  2434. continue
  2435. ams_id = int(ams_unit.get("id", 0))
  2436. for tray in ams_unit.get("tray", []):
  2437. if not isinstance(tray, dict):
  2438. continue
  2439. tray_id = int(tray.get("id", 0))
  2440. tag_uid = tray.get("tag_uid", "")
  2441. tray_uuid = tray.get("tray_uuid", "")
  2442. tray_info_idx = tray.get("tray_info_idx", "")
  2443. if not tray.get("tray_type"):
  2444. # Slot reported empty — drop any cached unknown-tag
  2445. # broadcast so reinserting the same spool re-prompts.
  2446. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2447. continue # Empty slot
  2448. # Check if assignment already exists for this slot
  2449. existing = await db.execute(
  2450. select(SA)
  2451. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2452. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2453. )
  2454. existing_assignment = existing.scalar_one_or_none()
  2455. if existing_assignment:
  2456. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2457. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2458. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2459. # Skip during active prints: the usage tracker handles deduction
  2460. # precisely via 3MF data on print completion. Without this guard the
  2461. # AMS remain% SET and the usage tracker ADD both fire from the same
  2462. # MQTT message, doubling the deduction (#880).
  2463. if _print_active:
  2464. continue
  2465. remain_raw = tray.get("remain")
  2466. if (
  2467. remain_raw is not None
  2468. and existing_assignment.spool
  2469. and not existing_assignment.spool.weight_locked
  2470. ):
  2471. try:
  2472. remain_val = int(remain_raw)
  2473. except (TypeError, ValueError):
  2474. remain_val = -1
  2475. if 1 <= remain_val <= 100:
  2476. lw = existing_assignment.spool.label_weight or 1000
  2477. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2478. current_used = existing_assignment.spool.weight_used or 0
  2479. if new_used > current_used + 1:
  2480. logger.info(
  2481. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2482. existing_assignment.spool_id,
  2483. current_used,
  2484. new_used,
  2485. remain_val,
  2486. )
  2487. existing_assignment.spool.weight_used = new_used
  2488. await db.commit()
  2489. # Re-apply stored K-profile when the live tray's
  2490. # cali_idx drifted from the spool's stored profile.
  2491. # This catches "reset slot → re-read" and any other
  2492. # path where the firmware loses the user's K-profile
  2493. # selection while the SpoolAssignment row persists.
  2494. # Per the maintainer's rule: any time a spool tag is
  2495. # identified and matches inventory, the slot must be
  2496. # configured with the spool's stored settings. Without
  2497. # this block the existing-assignment branch only ran
  2498. # weight-sync and let the firmware-default cali_idx win.
  2499. try:
  2500. spool = existing_assignment.spool
  2501. if (
  2502. spool is not None
  2503. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2504. and spool.k_profiles
  2505. ):
  2506. state = printer_manager.get_status(printer_id)
  2507. slot_nozzle = resolve_slot_nozzle(
  2508. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2509. )
  2510. nozzle_diameter = slot_nozzle.diameter
  2511. slot_extruder = slot_nozzle.extruder
  2512. # Prefer exact extruder match, fall back to
  2513. # extruder-agnostic kp for the same printer +
  2514. # nozzle. Avoids hard-skipping when the AMS is
  2515. # mapped differently than at calibration time.
  2516. matching_kp = None
  2517. fallback_kp = None
  2518. for kp in spool.k_profiles:
  2519. if (
  2520. kp.printer_id != printer_id
  2521. or kp.nozzle_diameter != nozzle_diameter
  2522. or kp.cali_idx is None
  2523. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2524. ):
  2525. continue
  2526. if (
  2527. slot_extruder is not None
  2528. and kp.extruder is not None
  2529. and kp.extruder == slot_extruder
  2530. ):
  2531. matching_kp = kp
  2532. break
  2533. if fallback_kp is None:
  2534. fallback_kp = kp
  2535. chosen_kp = matching_kp or fallback_kp
  2536. if chosen_kp is not None:
  2537. live_cali_idx = tray.get("cali_idx")
  2538. # Only fire MQTT when the printer's live
  2539. # cali_idx differs from the stored value.
  2540. # Avoids spamming the broker on every
  2541. # MQTT push during steady-state operation.
  2542. if live_cali_idx != chosen_kp.cali_idx:
  2543. client = printer_manager.get_client(printer_id)
  2544. if client:
  2545. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2546. client.extrusion_cali_sel(
  2547. ams_id=ams_id,
  2548. tray_id=tray_id,
  2549. cali_idx=chosen_kp.cali_idx,
  2550. filament_id=cali_filament_id,
  2551. nozzle_diameter=nozzle_diameter,
  2552. )
  2553. logger.info(
  2554. "Re-applied K-profile cali_idx=%d for spool %d "
  2555. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2556. chosen_kp.cali_idx,
  2557. spool.id,
  2558. printer_id,
  2559. ams_id,
  2560. tray_id,
  2561. live_cali_idx,
  2562. )
  2563. except Exception:
  2564. logger.exception(
  2565. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2566. printer_id,
  2567. ams_id,
  2568. tray_id,
  2569. )
  2570. continue
  2571. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2572. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2573. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2574. if not spool:
  2575. # Try matching an untagged inventory spool (same material/color)
  2576. spool = await find_matching_untagged_spool(db, tray)
  2577. if spool:
  2578. await link_tag_to_inventory_spool(db, spool, tray)
  2579. elif _auto_add_unknown:
  2580. spool = await create_spool_from_tray(db, tray)
  2581. else:
  2582. # Auto-add disabled: surface the slot so the
  2583. # user can add it manually via the UI.
  2584. await _broadcast_unknown_tag(
  2585. printer_id=printer_id,
  2586. ams_id=ams_id,
  2587. tray_id=tray_id,
  2588. tag_uid=tag_uid,
  2589. tray_uuid=tray_uuid,
  2590. tray_type=tray.get("tray_type"),
  2591. tray_color=tray.get("tray_color"),
  2592. tray_sub_brands=tray.get("tray_sub_brands"),
  2593. tray_count=len(ams_unit.get("tray", [])),
  2594. )
  2595. continue
  2596. # Slot matched (existing tag, untagged inventory
  2597. # match, or freshly auto-created spool) — drop any
  2598. # stale dedup so a future tag swap re-prompts.
  2599. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2600. await auto_assign_spool(
  2601. printer_id,
  2602. ams_id,
  2603. tray_id,
  2604. spool,
  2605. printer_manager,
  2606. db,
  2607. tray_info_idx=tray_info_idx,
  2608. )
  2609. await db.commit()
  2610. await ws_manager.broadcast(
  2611. {
  2612. "type": "spool_auto_assigned",
  2613. "printer_id": printer_id,
  2614. "ams_id": ams_id,
  2615. "tray_id": tray_id,
  2616. "spool_id": spool.id,
  2617. }
  2618. )
  2619. logger.info(
  2620. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2621. spool.id,
  2622. printer_id,
  2623. ams_id,
  2624. tray_id,
  2625. )
  2626. elif is_valid_tag(tag_uid, tray_uuid):
  2627. # Non-BL spool with some tag — let user choose
  2628. await _broadcast_unknown_tag(
  2629. printer_id=printer_id,
  2630. ams_id=ams_id,
  2631. tray_id=tray_id,
  2632. tag_uid=tag_uid,
  2633. tray_uuid=tray_uuid,
  2634. tray_type=tray.get("tray_type"),
  2635. tray_color=tray.get("tray_color"),
  2636. tray_sub_brands=tray.get("tray_sub_brands"),
  2637. tray_count=len(ams_unit.get("tray", [])),
  2638. )
  2639. # No-tag slots (generic non-RFID filament) are left alone:
  2640. # nothing to identify, prompting "+ Add" would just create
  2641. # ghost spools with empty tags on every confirm.
  2642. except Exception as e:
  2643. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2644. try:
  2645. async with async_session() as db:
  2646. from backend.app.api.routes.settings import get_setting
  2647. from backend.app.models.printer import Printer
  2648. # Check if Spoolman is enabled
  2649. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2650. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2651. return
  2652. # Check sync mode
  2653. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2654. if sync_mode and sync_mode != "auto":
  2655. return # Only sync on auto mode
  2656. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2657. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2658. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2659. # always owned by per-print tracking, never by AMS auto-sync. The
  2660. # setting is still read by the settings UI for backwards compat but
  2661. # has no effect on the sync path here.
  2662. # Get Spoolman URL
  2663. spoolman_url = await get_setting(db, "spoolman_url")
  2664. if not spoolman_url:
  2665. return
  2666. # Get or create Spoolman client
  2667. client = await get_spoolman_client()
  2668. if not client:
  2669. try:
  2670. client = await init_spoolman_client(spoolman_url)
  2671. except ValueError as exc:
  2672. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2673. return
  2674. # Check if Spoolman is reachable
  2675. if not await client.health_check():
  2676. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2677. return
  2678. # Get printer name for location
  2679. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2680. printer = result.scalar_one_or_none()
  2681. printer_name = printer.name if printer else f"Printer {printer_id}"
  2682. # OPTIMIZATION: Fetch all spools once before processing trays
  2683. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2684. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2685. try:
  2686. cached_spools = await client.get_spools()
  2687. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2688. except Exception as e:
  2689. logger.error(
  2690. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2691. printer_id,
  2692. e,
  2693. )
  2694. return
  2695. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2696. from sqlalchemy.orm import selectinload
  2697. from backend.app.models.spool_assignment import SpoolAssignment
  2698. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2699. from backend.app.services.ams_slot_presence import spool_present
  2700. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2701. # Built-in remaining weight, used by sync_ams_tray only when the
  2702. # firmware reports an unusable remain%/tray_weight for a slot.
  2703. #
  2704. # Left empty since #2812. This block runs in Spoolman mode only,
  2705. # and until then the built-in table was emptied on the switch, so
  2706. # there was never anything here to read and the fallback was inert.
  2707. # Preserving those rows makes it live again, and it is keyed by slot
  2708. # rather than by spool: after a mode switch the tray may well hold
  2709. # different filament, and ``create_spool`` writes ``remaining_weight``
  2710. # unconditionally, so a stale figure would be seeded into a brand new
  2711. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2712. # intent survives for whoever revisits the cross-mode fallback.
  2713. inventory_weights: dict[tuple[int, int], float] = {}
  2714. if not await spoolman_owns_assignments(db):
  2715. try:
  2716. assign_result = await db.execute(
  2717. select(SpoolAssignment)
  2718. .options(selectinload(SpoolAssignment.spool))
  2719. .where(SpoolAssignment.printer_id == printer_id)
  2720. )
  2721. for assignment in assign_result.scalars().all():
  2722. spool = assignment.spool
  2723. if spool and spool.label_weight > 0:
  2724. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2725. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2726. except Exception as e:
  2727. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2728. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2729. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2730. try:
  2731. slot_result = await db.execute(
  2732. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2733. )
  2734. for slot in slot_result.scalars().all():
  2735. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2736. except Exception as e:
  2737. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2738. # Sync each AMS tray and collect slot changes for DB persistence
  2739. synced = 0
  2740. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2741. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2742. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2743. for ams_unit in ams_data:
  2744. if not isinstance(ams_unit, dict):
  2745. continue
  2746. ams_id = int(ams_unit.get("id", 0))
  2747. trays = ams_unit.get("tray", [])
  2748. for tray_data in trays:
  2749. if not isinstance(tray_data, dict):
  2750. continue
  2751. tray_id_raw = int(tray_data.get("id", 0))
  2752. tray = client.parse_ams_tray(ams_id, tray_data)
  2753. if not tray:
  2754. # Empty tray slot — record for local assignment cleanup
  2755. # and drop any cached unknown-tag broadcast so a
  2756. # reinserted spool re-prompts.
  2757. #
  2758. # Not during a running print: a slot that empties there
  2759. # is a filament runout, and the spool is still in the
  2760. # AMS. `spoolman_slot_assignments` is how a tag-less
  2761. # spool assigned through the Bambuddy UI is resolved at
  2762. # completion (#1459), so deleting the row mid-print
  2763. # loses the runout segment's usage — the same failure
  2764. # the internal inventory's auto-unlink had.
  2765. #
  2766. # Nor when firmware's presence bit says the slot is
  2767. # occupied. parse_ams_tray calls a tray with no type or
  2768. # no colour empty, and a spool the AMS cannot read has
  2769. # neither until something configures it — so a tag-less
  2770. # spool assigned through the UI had its row deleted by
  2771. # the first idle push after it was inserted. Same
  2772. # deletion as the internal inventory's in #3100, same
  2773. # answer, so the two modes stay in step.
  2774. #
  2775. # And only once the slot has stayed empty for the grace
  2776. # period -- the internal inventory's #3186 answer, for
  2777. # the same one-push blank.
  2778. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2779. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2780. if not printing_now and (
  2781. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2782. ):
  2783. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2784. empty_slots.append((ams_id, tray_id_raw))
  2785. else:
  2786. spoolman_held.add(hold_key)
  2787. logger.info(
  2788. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2789. "unlinking if it is still empty in %ds",
  2790. ams_id,
  2791. tray_id_raw,
  2792. linked_spool,
  2793. int(slot_unlink_grace.GRACE_SECONDS),
  2794. )
  2795. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2796. continue
  2797. spool_tag = (
  2798. tray.tray_uuid
  2799. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2800. else tray.tag_uid
  2801. )
  2802. # Provide the hint only when no RFID is available
  2803. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2804. try:
  2805. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2806. result = await client.sync_ams_tray(
  2807. tray,
  2808. printer_name,
  2809. db,
  2810. # Per-print tracking is the only weight writer (#1119).
  2811. # AMS auto-sync still maintains spool metadata / slot
  2812. # assignments but no longer touches remaining_weight.
  2813. disable_weight_sync=True,
  2814. cached_spools=cached_spools,
  2815. inventory_remaining=inv_remaining,
  2816. spoolman_spool_id_hint=hint,
  2817. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2818. )
  2819. if result is None and spool_tag and not auto_add_unknown_rfid:
  2820. # Spoolman skipped auto-create per user setting — surface
  2821. # the slot so the UI can offer "+ Add to inventory".
  2822. await _broadcast_unknown_tag(
  2823. printer_id=printer_id,
  2824. ams_id=ams_id,
  2825. tray_id=tray.tray_id,
  2826. tag_uid=tray.tag_uid or "",
  2827. tray_uuid=tray.tray_uuid or "",
  2828. tray_type=tray.tray_type,
  2829. tray_color=tray.tray_color,
  2830. tray_sub_brands=tray.tray_sub_brands,
  2831. tray_count=len(trays),
  2832. )
  2833. elif result:
  2834. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2835. if result:
  2836. synced += 1
  2837. if result.get("id"):
  2838. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2839. # If a new spool was created, add it to the cache
  2840. # so subsequent trays can find it if they reference the same tag
  2841. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2842. if not spool_exists:
  2843. cached_spools.append(result)
  2844. logger.debug(
  2845. "[Printer %s] Added newly created spool %s to cache",
  2846. printer_id,
  2847. result["id"],
  2848. )
  2849. # Reconcile slot_preset_mappings (the same row internal
  2850. # mode keeps in sync via inventory + spool_tag_matcher).
  2851. # Without this the slot card surfaces the previous spool's
  2852. # preset name — same bug shape, different inventory mode.
  2853. from backend.app.services.slot_preset_writer import (
  2854. upsert_slot_preset_for_spoolman_spool,
  2855. )
  2856. await upsert_slot_preset_for_spoolman_spool(
  2857. db=db,
  2858. spoolman_spool=result,
  2859. tray_info_idx=tray.tray_info_idx or "",
  2860. tray_sub_brands=tray.tray_sub_brands or "",
  2861. tray_type=tray.tray_type or "",
  2862. printer_id=printer_id,
  2863. ams_id=ams_id,
  2864. tray_id=tray.tray_id,
  2865. )
  2866. except Exception as e:
  2867. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2868. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2869. if synced > 0:
  2870. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2871. # Persist slot assignment changes to the local table
  2872. if slot_changes or empty_slots:
  2873. try:
  2874. for ams_id, tray_id, spool_id in slot_changes:
  2875. await db.execute(
  2876. text(
  2877. "INSERT INTO spoolman_slot_assignments"
  2878. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2879. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2880. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2881. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2882. ),
  2883. {
  2884. "printer_id": printer_id,
  2885. "ams_id": ams_id,
  2886. "tray_id": tray_id,
  2887. "spool_id": spool_id,
  2888. },
  2889. )
  2890. for ams_id, tray_id in empty_slots:
  2891. await db.execute(
  2892. delete(SpoolmanSlotAssignment).where(
  2893. SpoolmanSlotAssignment.printer_id == printer_id,
  2894. SpoolmanSlotAssignment.ams_id == ams_id,
  2895. SpoolmanSlotAssignment.tray_id == tray_id,
  2896. )
  2897. )
  2898. await db.commit()
  2899. except Exception as e:
  2900. await db.rollback()
  2901. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2902. else:
  2903. # Tell open browsers the slot changed. This loop rewrites
  2904. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2905. # above, and the AMS slot card reads that row ahead of the
  2906. # live tray_info_idx -- so with no event the card keeps
  2907. # showing the previous spool's preset name. Internal mode
  2908. # raises spool_auto_assigned for the same reason; this loop
  2909. # broadcast nothing at all, which made Spoolman mode the
  2910. # worse half of the same bug. On the else branch so a
  2911. # failed commit stays silent and a broadcast failure cannot
  2912. # roll back rows that are already committed.
  2913. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2914. await ws_manager.broadcast(
  2915. {
  2916. "type": "spool_assignment_changed",
  2917. "printer_id": printer_id,
  2918. "ams_id": ams_id,
  2919. "tray_id": tray_id,
  2920. }
  2921. )
  2922. except Exception as e:
  2923. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2924. # Largest finish photo attached to a notification; a bigger one is still linked.
  2925. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2926. async def _finish_photo_for_notification(
  2927. db, archive, archive_id: int, filename: str
  2928. ) -> tuple[str | None, bytes | None]:
  2929. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2930. With authentication off the link is the archive's own photo route, as it
  2931. always was: it opens without a login and doesn't expire. With
  2932. authentication on that route needs a media token, which nothing tapping a
  2933. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2934. link only ever answered 401. The photo is then saved as a notification
  2935. photo as well (utils/notification_photos.py) and the link points there: an
  2936. unguessable name that opens this one photo and nothing else, for 3 days.
  2937. The link is relative when no External URL is set. Bytes over
  2938. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2939. ``(None, None)`` when the photo can't be found.
  2940. """
  2941. from backend.app.api.routes.settings import get_setting
  2942. from backend.app.core.auth import is_auth_enabled
  2943. from backend.app.utils.archive_paths import find_archive_photo
  2944. from backend.app.utils.notification_photos import save_notification_photo
  2945. log = logging.getLogger(__name__)
  2946. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2947. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2948. photo_bytes: bytes | None = None
  2949. try:
  2950. photo_path = find_archive_photo(archive, filename)
  2951. if photo_path is not None:
  2952. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2953. except Exception as e:
  2954. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2955. try:
  2956. auth_on = await is_auth_enabled(db)
  2957. except Exception:
  2958. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2959. if auth_on:
  2960. url = None
  2961. if photo_bytes:
  2962. try:
  2963. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2964. url = f"{base}/api/v1/notifications/photos/{name}"
  2965. except Exception as e:
  2966. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2967. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2968. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2969. return url, None
  2970. if photo_bytes:
  2971. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2972. return url, photo_bytes
  2973. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  2974. """Capture a camera snapshot for notification image attachment.
  2975. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2976. Uses: external camera > buffered frame > fresh capture.
  2977. Turns the chamber light on for the picture when the printer asks for it
  2978. (#1655). ``light=False`` is for callers that capture all through a print,
  2979. where the light would flash with every frame.
  2980. """
  2981. if not printer:
  2982. return None
  2983. async with camera_light(printer if light else None):
  2984. return await _capture_snapshot_frame(printer_id, printer, logger)
  2985. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  2986. """The capture behind ``_capture_snapshot_for_notification``."""
  2987. try:
  2988. from backend.app.api.routes.settings import get_setting
  2989. async with async_session() as db:
  2990. capture_enabled = await get_setting(db, "capture_finish_photo")
  2991. if capture_enabled is not None and capture_enabled.lower() != "true":
  2992. return None
  2993. # Try external camera first
  2994. if printer.external_camera_enabled and printer.external_camera_url:
  2995. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2996. from backend.app.api.routes.camera import live_frame_for_capture
  2997. from backend.app.services.external_camera import capture_frame
  2998. # An external camera allows one reader, so capturing while a viewer
  2999. # is attached fails (#2707). A None here falls through to the paths
  3000. # below exactly as a failed capture did.
  3001. defer, buffered = live_frame_for_capture(printer_id)
  3002. if defer:
  3003. frame_data = buffered
  3004. else:
  3005. frame_data = await capture_frame(
  3006. printer.external_camera_url,
  3007. printer.external_camera_type or "mjpeg",
  3008. snapshot_url=printer.external_camera_snapshot_url,
  3009. )
  3010. if frame_data and len(frame_data) <= 2_500_000:
  3011. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3012. return _apply_camera_rotation(frame_data, printer, logger)
  3013. # Try buffered frame from active stream
  3014. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3015. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3016. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3017. buffered_frame = get_buffered_frame(printer_id)
  3018. if (active_for_printer or active_chamber) and buffered_frame:
  3019. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3020. if len(buffered_frame) <= 2_500_000:
  3021. return _apply_camera_rotation(buffered_frame, printer, logger)
  3022. # Fresh capture from printer camera
  3023. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3024. from backend.app.services.camera import capture_camera_frame_bytes
  3025. frame_data = await capture_camera_frame_bytes(
  3026. printer.ip_address, printer.access_code, printer.model, timeout=15
  3027. )
  3028. if frame_data and len(frame_data) <= 2_500_000:
  3029. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3030. return _apply_camera_rotation(frame_data, printer, logger)
  3031. except Exception as e:
  3032. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3033. return None
  3034. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3035. """#1867: bank a recent in-print camera frame for the finish photo.
  3036. Called on every layer change and (#2547) on every print-progress advance.
  3037. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3038. path has a pre-End-G-code image for prints that end with a plate swap.
  3039. Both drivers are print telemetry that stops the instant printing ends: no
  3040. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3041. plate swap) executes. So the last banked frame is always the finished print,
  3042. never the swapped plate — that property is what the #1867 path relies on and
  3043. it must survive any change to the throttle below.
  3044. Layer changes alone were not enough: they stop when the *final* layer
  3045. begins, which on a three-minute last layer left the bank stale by the whole
  3046. length of that layer (#2547). Progress keeps ticking through it.
  3047. Best-effort: any failure just leaves the previous banked frame.
  3048. """
  3049. logger = logging.getLogger(__name__)
  3050. client = printer_manager.get_client(printer_id)
  3051. state = client.state if client else None
  3052. if not state or state.state != "RUNNING":
  3053. return
  3054. # Only during actual extrusion — firmware ticks layer_num during the
  3055. # pre-print calibration sequence, whose sub-stages are non-zero.
  3056. if state.mc_print_sub_stage not in (None, 0):
  3057. return
  3058. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3059. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3060. # now that progress advances also drive banking, that exemption would fire a
  3061. # camera grab on every percent tick of the last layer. Bambu printers accept
  3062. # one RTSP client at a time, so each grab contends with the live view.
  3063. now = time.monotonic()
  3064. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3065. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3066. return
  3067. total = state.total_layers or 0
  3068. try:
  3069. async with async_session() as db:
  3070. from backend.app.models.printer import Printer
  3071. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3072. printer = result.scalar_one_or_none()
  3073. if not printer:
  3074. return
  3075. # Reuses the notification snapshot path, which honours the
  3076. # `capture_finish_photo` setting (returns None when disabled) so we
  3077. # don't bank frames the user never asked for. Without the chamber light
  3078. # (#1655): this runs every 25 seconds for the whole print.
  3079. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3080. if frame:
  3081. _inprint_frame_bank[printer_id] = frame
  3082. _inprint_frame_bank_ts[printer_id] = now
  3083. logger.debug(
  3084. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3085. printer_id,
  3086. layer_num,
  3087. total,
  3088. len(frame),
  3089. )
  3090. except Exception as e:
  3091. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3092. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3093. """Apply camera rotation to snapshot image if configured."""
  3094. from backend.app.services.camera import apply_camera_rotation
  3095. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3096. async def _send_print_start_notification(
  3097. printer_id: int,
  3098. data: dict,
  3099. archive_data: dict | None = None,
  3100. logger=None,
  3101. ):
  3102. """Helper to send print start notification with optional archive data."""
  3103. if logger is None:
  3104. logger = logging.getLogger(__name__)
  3105. try:
  3106. async with async_session() as db:
  3107. from backend.app.models.printer import Printer
  3108. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3109. printer = result.scalar_one_or_none()
  3110. printer_name = printer.name if printer else f"Printer {printer_id}"
  3111. # Capture camera snapshot for notification image attachment
  3112. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3113. if image_data:
  3114. if archive_data is None:
  3115. archive_data = {}
  3116. archive_data["image_data"] = image_data
  3117. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3118. # Send user-specific email notification for print start
  3119. if archive_data and archive_data.get("created_by_id"):
  3120. await notification_service.send_user_print_email(
  3121. event_type="user_print_start",
  3122. created_by_id=archive_data["created_by_id"],
  3123. printer_name=printer_name,
  3124. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3125. db=db,
  3126. )
  3127. except Exception as e:
  3128. logger.warning("Notification on_print_start failed: %s", e)
  3129. async def _dispatch_user_print_email(
  3130. status: str,
  3131. created_by_id: int | None,
  3132. printer_name: str,
  3133. filename: str,
  3134. db,
  3135. image_data: bytes | None = None,
  3136. finish_photo_url: str | None = None,
  3137. ) -> None:
  3138. """Send a user-specific print-completion email based on print status.
  3139. Maps the normalised print status to the correct event type and delegates
  3140. to :meth:`NotificationService.send_user_print_email`. A single helper
  3141. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3142. "stopped"`` dispatch block at every call site.
  3143. Does nothing if *created_by_id* is ``None``.
  3144. """
  3145. if created_by_id is None:
  3146. return
  3147. if status == "completed":
  3148. event_type = "user_print_complete"
  3149. elif status == "failed":
  3150. event_type = "user_print_failed"
  3151. elif status in ("stopped", "aborted", "cancelled"):
  3152. event_type = "user_print_stopped"
  3153. else:
  3154. return
  3155. await notification_service.send_user_print_email(
  3156. event_type=event_type,
  3157. created_by_id=created_by_id,
  3158. printer_name=printer_name,
  3159. filename=filename,
  3160. db=db,
  3161. image_data=image_data,
  3162. finish_photo_url=finish_photo_url,
  3163. )
  3164. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3165. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3166. try:
  3167. from backend.app.services.archive import extract_printable_objects_from_archive
  3168. client = printer_manager.get_client(printer_id)
  3169. if not client:
  3170. return
  3171. # Extract with positions for UI overlay, scoped to the plate that
  3172. # is printing — resolve_plate_id is the same resolver /cover uses,
  3173. # so the object list can't disagree with the thumbnail it is drawn
  3174. # over (#2522).
  3175. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3176. app_settings.base_dir / archive.file_path,
  3177. plate_number=resolve_plate_id(client.state),
  3178. )
  3179. if printable_objects:
  3180. client.state.printable_objects = printable_objects
  3181. client.state.printable_objects_bbox_all = bbox_all
  3182. client.state.skipped_objects = []
  3183. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3184. except Exception as e:
  3185. logger.debug("Failed to extract printable objects from archive: %s", e)
  3186. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3187. """Put the skip-objects list back after a restart mid-print.
  3188. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3189. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3190. which the #1304 guard suppresses on the first RUNNING push after startup.
  3191. Everything else this hook restores (the archive, the usage-tracking session,
  3192. the timelapse baseline) was already handled; the object list was not, so a
  3193. restart mid-print took skip-objects away for the rest of that print.
  3194. Nothing recovered it either: the printer card gates its Skip button on the
  3195. object count, and the one endpoint that can rebuild the list is reachable
  3196. only from the modal that button opens.
  3197. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3198. leftover ``status="printing"`` row from a completion we never saw cannot
  3199. hand this print someone else's objects. Without one, nothing is loaded
  3200. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3201. case on demand.
  3202. """
  3203. client = printer_manager.get_client(printer_id)
  3204. if client is None or client.state.printable_objects:
  3205. return
  3206. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3207. if subtask_id in ("", "0"):
  3208. return
  3209. from backend.app.models.archive import PrintArchive
  3210. archive = await db.scalar(
  3211. select(PrintArchive)
  3212. .where(
  3213. PrintArchive.printer_id == printer_id,
  3214. PrintArchive.status == "printing",
  3215. PrintArchive.subtask_id == subtask_id,
  3216. )
  3217. .order_by(PrintArchive.created_at.desc())
  3218. .limit(1)
  3219. )
  3220. if archive is not None:
  3221. _load_objects_from_archive(archive, printer_id, logger)
  3222. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3223. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3224. # past it; the second covers a handshake that failed again on the way back and
  3225. # armed a fresh one. Module-level so tests can shrink them.
  3226. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3227. # Retry ladder for the other temporary give-up: the file service answered and
  3228. # the transfer still did not finish, which at print start is usually the printer
  3229. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3230. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3231. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3232. # two cover a printer that stays busy well into the print.
  3233. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3234. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3235. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3236. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3237. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3238. # by view, so two views race), the cool-off retry task, and print completion.
  3239. # Without this they each read file_path == "" and each run a full copy, so the row
  3240. # ends up pointing at one timestamped directory while the others sit orphaned.
  3241. #
  3242. # Keyed by printer rather than archive because a printer runs one print at a time,
  3243. # which makes the two equally strong here — and it bounds the dict by printer
  3244. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3245. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3246. # resuming, so "no waiters" is not a question this API can answer.
  3247. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3248. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3249. """Fill in a no-3MF archive from a 3MF that turned up later.
  3250. Returns True when the row was upgraded. Safe to call speculatively: it
  3251. verifies the archive still exists, is still a fallback, and that the file
  3252. is a readable 3MF before touching anything.
  3253. Serialised per printer — see ``_fallback_recovery_locks``.
  3254. """
  3255. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3256. async with lock:
  3257. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3258. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3259. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3260. import zipfile
  3261. from backend.app.models.archive import PrintArchive
  3262. from backend.app.services.archive import ArchiveService
  3263. logger = logging.getLogger(__name__)
  3264. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3265. return False
  3266. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3267. # A truncated or half-written download is worse than no download: it
  3268. # would replace an honest empty archive with wrong metadata.
  3269. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3270. return False
  3271. async with async_session() as db:
  3272. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3273. if archive is None or archive.deleted_at is not None:
  3274. return False
  3275. if archive.file_path:
  3276. # Already recovered, or never was a fallback. Either way there is a
  3277. # real 3MF attached and overwriting it is not this function's job.
  3278. return False
  3279. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3280. service = ArchiveService(db)
  3281. recovered = await service.archive_print(
  3282. printer_id=printer_id,
  3283. source_file=source_3mf,
  3284. print_data={**print_data, "status": archive.status or "printing"},
  3285. subtask_id=archive.subtask_id,
  3286. update_archive_id=archive.id,
  3287. )
  3288. if recovered is None:
  3289. return False
  3290. logger.info(
  3291. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3292. archive_id,
  3293. source_3mf,
  3294. recovered.file_size,
  3295. )
  3296. # `archive_updated`, not `archive_created` — the row was already on the
  3297. # Archives page as an empty card and is now filled in, not new.
  3298. await ws_manager.send_archive_updated(
  3299. {
  3300. "id": recovered.id,
  3301. "printer_id": recovered.printer_id,
  3302. "filename": recovered.filename,
  3303. "print_name": recovered.print_name,
  3304. "status": recovered.status,
  3305. }
  3306. )
  3307. return True
  3308. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3309. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3310. Called from the paths that pull a 3MF for a print that is already under way
  3311. — chiefly the cover endpoint, which downloads the very file the archive flow
  3312. could not get and, before #2957, used it for a thumbnail and nothing else.
  3313. The bytes are already local, so this costs a parse and a row update.
  3314. No-op when the running print has a real archive, which is the common case.
  3315. """
  3316. from backend.app.models.archive import PrintArchive
  3317. logger = logging.getLogger(__name__)
  3318. # `_active_prints` is keyed on the raw names seen at print start — the
  3319. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3320. # Callers here arrive with whichever variant their own path produced, so
  3321. # match on the same normalization the download cache uses rather than on an
  3322. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3323. # endpoint find an archive registered under "Desktop_Goose".
  3324. wanted = normalize_3mf_name(name)
  3325. archive_id = None
  3326. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3327. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3328. archive_id = value
  3329. break
  3330. if archive_id is None:
  3331. return False
  3332. async with async_session() as db:
  3333. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3334. # Cheap pre-check so the common case (a normal archive) does no work.
  3335. if archive is None or archive.file_path or archive.deleted_at is not None:
  3336. return False
  3337. try:
  3338. return await _recover_fallback_archive(archive_id, path, printer_id)
  3339. except Exception as e:
  3340. # Recovery is opportunistic. A failure here must never take down the
  3341. # caller, which is usually just trying to render a thumbnail.
  3342. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3343. return False
  3344. def _schedule_fallback_3mf_retry(
  3345. printer_id: int,
  3346. archive_id: int,
  3347. filenames: list[str],
  3348. delays: tuple[float, ...] | None = None,
  3349. reason: str = REASON_FTPS_COOLOFF,
  3350. ) -> None:
  3351. """Re-attempt the 3MF download after a temporary give-up.
  3352. ``reason`` says which give-up this is, and picks the default ladder: an
  3353. FTPS cool-off has to be waited out, while a transfer that timed out under
  3354. contention is worth asking about again straight away (#3063). It is only
  3355. read for the ladder and the log line -- the retry itself is identical, since
  3356. in both cases the file is on the printer and the last attempt at it failed
  3357. for a reason that does not last.
  3358. """
  3359. logger = logging.getLogger(__name__)
  3360. if delays is None:
  3361. delays = (
  3362. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3363. if reason == REASON_FTP_TRANSFER_FAILED
  3364. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3365. )
  3366. async def _retry() -> None:
  3367. from backend.app.models.archive import PrintArchive
  3368. from backend.app.models.printer import Printer
  3369. for delay in delays:
  3370. await asyncio.sleep(delay)
  3371. async with async_session() as db:
  3372. archive = (
  3373. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3374. ).scalar_one_or_none()
  3375. if archive is None or archive.deleted_at is not None or archive.file_path:
  3376. return
  3377. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3378. if printer is None:
  3379. return
  3380. # Read the fields while the session is open rather than touching
  3381. # a detached instance minutes later, mid-download.
  3382. printer_ip = printer.ip_address
  3383. printer_code = printer.access_code
  3384. printer_model = printer.model
  3385. # Someone else may have fetched it in the meantime — the cover
  3386. # endpoint routinely does, and its copy is the same bytes.
  3387. for name in filenames:
  3388. cached = get_cached_3mf(printer_id, name)
  3389. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3390. return
  3391. if ftps_handshake_blocked(printer_ip):
  3392. logger.info(
  3393. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3394. printer_id,
  3395. archive_id,
  3396. )
  3397. continue
  3398. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3399. for candidate in filenames:
  3400. # Bare name only. These come from the print-start flow, which
  3401. # already strips the path, but the local temp write must not
  3402. # depend on that holding for every future caller — a name that
  3403. # is absolute or contains ".." would otherwise escape the data
  3404. # volume via the `/` operator.
  3405. name = Path(candidate).name
  3406. if not name or name in (".", ".."):
  3407. continue
  3408. if not name.endswith(".3mf"):
  3409. name = f"{name}.3mf"
  3410. temp_path = app_settings.archive_dir / "temp" / name
  3411. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3412. try:
  3413. hit = await download_file_try_paths_async(
  3414. printer_ip,
  3415. printer_code,
  3416. ftp_probe_paths(name),
  3417. temp_path,
  3418. socket_timeout=ftp_timeout,
  3419. printer_model=printer_model,
  3420. )
  3421. except Exception as e:
  3422. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3423. continue
  3424. if not hit:
  3425. continue
  3426. cache_3mf_download(printer_id, name, temp_path)
  3427. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3428. return
  3429. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3430. async def _guarded() -> None:
  3431. try:
  3432. await _retry()
  3433. except asyncio.CancelledError:
  3434. raise
  3435. except Exception as e:
  3436. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3437. finally:
  3438. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3439. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3440. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3441. if existing and not existing.done():
  3442. existing.cancel()
  3443. task = asyncio.create_task(_guarded())
  3444. _fallback_3mf_retry_tasks[printer_id] = task
  3445. logger.info(
  3446. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3447. archive_id,
  3448. reason,
  3449. printer_id,
  3450. ", ".join(f"{d:g}s" for d in delays),
  3451. )
  3452. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3453. """Whether an archive created here should ask for the print's outcome (#1898).
  3454. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3455. branches below: a queued job already has its archive and takes the
  3456. expected-print branch, where the queue item's own ``confirm_outcome``
  3457. decides. The queue is still consulted, because a restart mid-print empties
  3458. ``_expected_prints`` — without the check the setting could override a queue
  3459. item that deliberately has the flag off. Any failure answers "don't ask":
  3460. an unwanted prompt is worse than a missing one, and this must never be the
  3461. reason a print goes unarchived.
  3462. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3463. leaves one behind when a completion cannot be matched to it
  3464. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3465. only takes it back once the printer has sat connected and terminal for
  3466. minutes. Until then every screen-started print on that printer would
  3467. silently lose its prompt, so the row is held against ``observed_name`` by
  3468. the same comparison a completion uses: a positive disagreement means the row
  3469. is about some other run and this print is external after all.
  3470. """
  3471. logger = logging.getLogger(__name__)
  3472. try:
  3473. # A savepoint rather than a rollback of the caller's transaction on
  3474. # failure: a failed statement leaves the transaction unusable, but a
  3475. # full rollback also expires every object the caller has loaded (the
  3476. # printer, the archive it just created), and on an async session the
  3477. # next attribute read then raises instead of reloading. Everything here
  3478. # is a read, so undoing the savepoint loses nothing.
  3479. async with db.begin_nested():
  3480. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3481. except Exception as e:
  3482. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3483. return False
  3484. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3485. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3486. from backend.app.api.routes.settings import get_setting, setting_is_true
  3487. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3488. return False
  3489. from backend.app.models.print_queue import PrintQueueItem
  3490. dispatched_here = await db.scalar(
  3491. select(PrintQueueItem)
  3492. .where(
  3493. PrintQueueItem.printer_id == printer_id,
  3494. PrintQueueItem.status == "printing",
  3495. )
  3496. .limit(1)
  3497. )
  3498. if dispatched_here is None:
  3499. return True
  3500. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3501. observed = (observed_name or "").strip()
  3502. if not expected or not observed or _subtask_names_match(expected, observed):
  3503. logger.info(
  3504. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3505. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3506. printer_id,
  3507. dispatched_here.id,
  3508. )
  3509. return False
  3510. logger.info(
  3511. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3512. "%r; treating this as an externally started print.",
  3513. dispatched_here.id,
  3514. printer_id,
  3515. expected,
  3516. observed,
  3517. )
  3518. return True
  3519. async def _dispatch_outcome_confirmation_safely(
  3520. db,
  3521. printer_id: int,
  3522. printer_name: str,
  3523. data: dict,
  3524. archive_id: int,
  3525. archive_data: dict | None = None,
  3526. ) -> None:
  3527. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3528. The completion task sends the per-user print email on the same session
  3529. right after the prompt. A failed statement in the prompt leaves that
  3530. session needing a rollback, and without one the email step fails with
  3531. PendingRollbackError; the prompt is the optional part, so it must not be
  3532. the reason the email never goes out.
  3533. """
  3534. try:
  3535. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3536. except Exception as e:
  3537. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3538. try:
  3539. await db.rollback()
  3540. except Exception:
  3541. pass
  3542. async def dispatch_outcome_confirmation(
  3543. db,
  3544. printer_id: int,
  3545. printer_name: str,
  3546. data: dict,
  3547. archive_id: int,
  3548. archive_data: dict | None = None,
  3549. ) -> bool:
  3550. """Emit the post-print outcome prompt for a completed archive (#1898).
  3551. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3552. queue item, or from ``confirm_outcome_external_prints`` for a print
  3553. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3554. question still open. Mints the per-archive capability token the one-tap
  3555. verdict links carry.
  3556. Lives here rather than inline in ``on_print_complete``'s notification task
  3557. because that task swallows every exception: extracted, the gate and the two
  3558. emissions can be driven by a test, which is the only thing standing between
  3559. a regression here and a farm that quietly stops asking.
  3560. Returns whether a prompt was sent.
  3561. """
  3562. logger = logging.getLogger(__name__)
  3563. from backend.app.models.archive import PrintArchive
  3564. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3565. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3566. return False
  3567. import secrets as _secrets
  3568. # A spent token stays on the row so the one-tap route can recognise it, so
  3569. # "has a token" no longer means "answerable". A prompt going out now needs a
  3570. # live one: mint a new token whenever the stored one is already spent, or
  3571. # every button in the new message would land on the already-answered page.
  3572. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3573. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3574. confirm_archive.confirm_token_used_at = None
  3575. await db.commit()
  3576. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3577. base = await get_external_base_url(db)
  3578. if not await get_setting(db, "external_url"):
  3579. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3580. # absolute URL, so an unconfigured install used to get a message body
  3581. # with two unusable relative paths and no buttons at all. The shared
  3582. # fallback at least produces tappable links; say which setting makes
  3583. # them resolve from a phone.
  3584. logger.warning(
  3585. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3586. "Set Settings → External URL so they resolve away from this host.",
  3587. base,
  3588. )
  3589. token = confirm_archive.confirm_token
  3590. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3591. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3592. confirm_url = f"{base}/archives?confirm={archive_id}"
  3593. await ws_manager.send_print_confirm_request(
  3594. printer_id,
  3595. {
  3596. "archive_id": archive_id,
  3597. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3598. },
  3599. )
  3600. await notification_service.on_print_confirm_request(
  3601. printer_id,
  3602. printer_name,
  3603. data,
  3604. db,
  3605. archive_data=archive_data,
  3606. good_url=good_url,
  3607. reject_url=reject_url,
  3608. confirm_url=confirm_url,
  3609. archive_id=archive_id,
  3610. )
  3611. return True
  3612. async def on_print_start(printer_id: int, data: dict):
  3613. """Handle print start - archive the 3MF file immediately."""
  3614. logger = logging.getLogger(__name__)
  3615. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3616. try:
  3617. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3618. except Exception:
  3619. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3620. # Clear any stale user-stopped flag from previous print cycles
  3621. _user_stopped_printers.discard(printer_id)
  3622. # A new print starts its milestones from zero (#3211). The status path only
  3623. # resets on progress below 5 while not printing, which a printer that goes
  3624. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3625. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3626. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3627. _last_progress_milestone[printer_id] = 0
  3628. _kill_switch_notification_tasks.pop(printer_id, None)
  3629. # #1721: drop any leftover pre-captured finish frame from a prior print
  3630. # so a never-consumed cache entry can't bleed into the new print's photo.
  3631. _stage22_finish_frames.pop(printer_id, None)
  3632. # #1867: same for the in-print frame bank — a queued print must not reuse
  3633. # the previous job's banked frame.
  3634. _inprint_frame_bank.pop(printer_id, None)
  3635. _inprint_frame_bank_ts.pop(printer_id, None)
  3636. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3637. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3638. # print's flag instead of inheriting it.
  3639. print_dispatch_context.adopt(printer_id)
  3640. # Cancel any active bed cooldown waiter for this printer
  3641. if _bed_cool_waiters.pop(printer_id, None):
  3642. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3643. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3644. from backend.app.api.routes.printers import clear_cover_cache
  3645. clear_cover_cache(printer_id)
  3646. await ws_manager.send_print_start(printer_id, data)
  3647. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3648. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3649. # MQTT relay - publish print start
  3650. try:
  3651. printer_info = printer_manager.get_printer(printer_id)
  3652. if printer_info:
  3653. await mqtt_relay.on_print_start(
  3654. printer_id,
  3655. printer_info.name,
  3656. printer_info.serial_number,
  3657. data.get("filename", ""),
  3658. data.get("subtask_name", ""),
  3659. )
  3660. except Exception:
  3661. pass # Don't fail print start callback if MQTT fails
  3662. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3663. # and mapping, and the seeded tray-change log.
  3664. #
  3665. # Unconditional, for both inventory backends. This only *captures* — the
  3666. # writing is still split, with the internal tracker skipped at completion
  3667. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3668. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3669. # tray-change log, and that log is the only record of which spool fed
  3670. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3671. # it on one side only would leave Spoolman users with the mid-print
  3672. # restart bug this fixes for everyone else.
  3673. try:
  3674. async with async_session() as db:
  3675. from backend.app.api.routes.settings import get_setting
  3676. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3677. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3678. await usage_on_print_start(
  3679. printer_id,
  3680. data,
  3681. printer_manager,
  3682. db=db,
  3683. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3684. )
  3685. except Exception as e:
  3686. logger.warning("Usage tracker on_print_start failed: %s", e)
  3687. # Track if notification was sent (to avoid sending twice)
  3688. notification_sent = False
  3689. # Smart plug automation: turn on plug when print starts
  3690. try:
  3691. async with async_session() as db:
  3692. await smart_plug_manager.on_print_start(printer_id, db)
  3693. except Exception as e:
  3694. logger.warning("Smart plug on_print_start failed: %s", e)
  3695. async with async_session() as db:
  3696. from backend.app.models.printer import Printer
  3697. from backend.app.services.bambu_ftp import list_files_async
  3698. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3699. printer = result.scalar_one_or_none()
  3700. # Plate detection check - pause if objects detected on build plate
  3701. logger.info(
  3702. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3703. )
  3704. if printer and printer.plate_detection_enabled:
  3705. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3706. # Release the pooled DB connection before the plate-detection camera
  3707. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3708. # printer SELECT has run so far — nothing to persist — so this commit
  3709. # is a data-noop that ends the read transaction and returns the
  3710. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3711. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3712. # archive lookups below re-acquire a fresh connection on next execute.
  3713. await db.commit()
  3714. try:
  3715. from backend.app.services.plate_detection import check_plate_empty
  3716. # Build ROI tuple from printer settings if available
  3717. roi = None
  3718. if all(
  3719. [
  3720. printer.plate_detection_roi_x is not None,
  3721. printer.plate_detection_roi_y is not None,
  3722. printer.plate_detection_roi_w is not None,
  3723. printer.plate_detection_roi_h is not None,
  3724. ]
  3725. ):
  3726. roi = (
  3727. printer.plate_detection_roi_x,
  3728. printer.plate_detection_roi_y,
  3729. printer.plate_detection_roi_w,
  3730. printer.plate_detection_roi_h,
  3731. )
  3732. # Auto-turn on chamber light if it's off for better detection
  3733. light_was_off = False
  3734. client = printer_manager.get_client(printer_id)
  3735. if client and client.state:
  3736. light_was_off = not client.state.chamber_light
  3737. if light_was_off:
  3738. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3739. client.set_chamber_light(True)
  3740. # Wait for light to physically turn on and camera to adjust exposure
  3741. await asyncio.sleep(2.5)
  3742. plate_photo_data = None
  3743. objects_detected = False
  3744. try:
  3745. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3746. plate_result = await check_plate_empty(
  3747. printer_id=printer_id,
  3748. ip_address=printer.ip_address,
  3749. access_code=printer.access_code,
  3750. model=printer.model,
  3751. include_debug_image=False,
  3752. external_camera_url=printer.external_camera_url,
  3753. external_camera_type=printer.external_camera_type,
  3754. use_external=printer.external_camera_enabled,
  3755. roi=roi,
  3756. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3757. )
  3758. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3759. if objects_detected:
  3760. # Objects detected - pause the print!
  3761. logger.warning(
  3762. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3763. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3764. )
  3765. pause_client = printer_manager.get_client(printer_id)
  3766. if pause_client:
  3767. pause_client.pause_print()
  3768. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3769. # Snapshot while the light's still on — restoring it first
  3770. # would leave the notification with a dark photo.
  3771. try:
  3772. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3773. except Exception as snap_err:
  3774. logger.warning(
  3775. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3776. )
  3777. finally:
  3778. # Restore chamber light to original state as soon as the
  3779. # camera is done with it, whatever happened above.
  3780. if light_was_off and client:
  3781. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3782. try:
  3783. client.set_chamber_light(False)
  3784. except Exception as light_err:
  3785. logger.warning(
  3786. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3787. printer_id,
  3788. light_err,
  3789. )
  3790. if objects_detected:
  3791. # Send notification about plate not empty
  3792. await ws_manager.broadcast(
  3793. {
  3794. "type": "plate_not_empty",
  3795. "printer_id": printer_id,
  3796. "printer_name": printer.name,
  3797. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3798. }
  3799. )
  3800. # Also send push notification
  3801. try:
  3802. await notification_service.on_plate_not_empty(
  3803. printer_id=printer_id,
  3804. printer_name=printer.name,
  3805. db=db,
  3806. difference_percent=plate_result.difference_percent,
  3807. image_data=plate_photo_data,
  3808. )
  3809. except Exception as notif_err:
  3810. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3811. else:
  3812. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3813. except Exception as plate_err:
  3814. # Don't block print on plate detection errors
  3815. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3816. if not printer:
  3817. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3818. if not notification_sent:
  3819. await _send_print_start_notification(printer_id, data, logger=logger)
  3820. return
  3821. if not printer.auto_archive:
  3822. # auto-archive disabled — check if there's an expected print (dispatched
  3823. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3824. # If so, fall through to the expected-print handling below so the archive
  3825. # is tracked in _active_prints and usage tracking works at completion.
  3826. _fn = data.get("filename", "")
  3827. _sn = data.get("subtask_name", "")
  3828. _check_keys: list[tuple[int, str]] = []
  3829. if _sn:
  3830. _check_keys += [
  3831. (printer_id, _sn),
  3832. (printer_id, f"{_sn}.3mf"),
  3833. (printer_id, f"{_sn}.gcode.3mf"),
  3834. ]
  3835. if _fn:
  3836. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3837. _check_keys.append((printer_id, _base_fn))
  3838. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3839. _check_keys += [
  3840. (printer_id, _no_archive_base),
  3841. (printer_id, f"{_no_archive_base}.3mf"),
  3842. ]
  3843. _has_expected = any(k in _expected_prints for k in _check_keys)
  3844. if not _has_expected:
  3845. # No expected print — truly external print (started from slicer/touchscreen)
  3846. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3847. if not notification_sent:
  3848. _no_archive_creator: int | None = None
  3849. for _key in _check_keys:
  3850. _expected_prints.pop(_key, None)
  3851. _expected_print_registered_at.pop(_key, None)
  3852. popped_creator = _expected_print_creators.pop(_key, None)
  3853. if _no_archive_creator is None:
  3854. _no_archive_creator = popped_creator
  3855. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3856. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3857. return
  3858. else:
  3859. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3860. # Get the filename and subtask_name
  3861. filename = data.get("filename", "")
  3862. subtask_name = data.get("subtask_name", "")
  3863. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3864. # present, it lets us match an archive across a backend restart (#972):
  3865. # same id → same print → resume the existing row instead of cancelling
  3866. # it and recreating from scratch (which loses started_at). Treat "0"
  3867. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3868. raw_mqtt = data.get("raw_data") or {}
  3869. subtask_id = raw_mqtt.get("subtask_id")
  3870. if subtask_id is not None:
  3871. subtask_id = str(subtask_id).strip()
  3872. if subtask_id in ("", "0"):
  3873. subtask_id = None
  3874. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3875. # Skip the printer's own jobs — a calibration run is not a user's print.
  3876. # See is_internal_printer_job for what counts and why both fields are
  3877. # tested; the pressure-advance line reports as a subtask name with no
  3878. # /usr/ path, which the old prefix-only test here missed entirely.
  3879. #
  3880. # No notification either. The event describes the printer calibrating
  3881. # itself, so "Print started" is as wrong as the archive was, and the
  3882. # matching completion is suppressed in on_print_complete for the same
  3883. # reason.
  3884. if is_internal_printer_job(filename, subtask_name):
  3885. logger.info(
  3886. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3887. filename,
  3888. subtask_name,
  3889. )
  3890. return
  3891. if not filename and not subtask_name:
  3892. # Send notification without archive data (no filename)
  3893. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3894. if not notification_sent:
  3895. await _send_print_start_notification(printer_id, data, logger=logger)
  3896. return
  3897. # Check if this is an expected print from reprint/scheduled
  3898. # Build list of possible keys to check
  3899. expected_keys = []
  3900. if subtask_name:
  3901. expected_keys.append((printer_id, subtask_name))
  3902. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3903. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3904. if filename:
  3905. fname = filename.split("/")[-1] if "/" in filename else filename
  3906. expected_keys.append((printer_id, fname))
  3907. # Strip extensions to match
  3908. base = fname.replace(".gcode", "").replace(".3mf", "")
  3909. expected_keys.append((printer_id, base))
  3910. expected_keys.append((printer_id, f"{base}.3mf"))
  3911. expected_archive_id = None
  3912. for key in expected_keys:
  3913. expected_archive_id = _expected_prints.pop(key, None)
  3914. _expected_print_registered_at.pop(key, None)
  3915. if expected_archive_id:
  3916. # Clean up other possible keys for this print
  3917. for other_key in expected_keys:
  3918. _expected_prints.pop(other_key, None)
  3919. _expected_print_registered_at.pop(other_key, None)
  3920. break
  3921. if expected_archive_id:
  3922. # This is a reprint/scheduled print - use existing archive, don't create new one
  3923. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3924. from backend.app.models.archive import PrintArchive
  3925. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3926. archive = result.scalar_one_or_none()
  3927. if archive:
  3928. # Update archive status to printing
  3929. archive.status = "printing"
  3930. archive.started_at = datetime.now(timezone.utc)
  3931. # The previous run's answer is still on this row and the
  3932. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3933. # so without a reset the second run inherits the first run's
  3934. # verdict: no prompt at all, and a green "good" badge on a run
  3935. # nobody ever judged.
  3936. if archive.confirm_requested:
  3937. archive.user_verdict = None
  3938. archive.user_verdict_source = None
  3939. archive.user_verdict_at = None
  3940. archive.confirm_token = None
  3941. archive.confirm_token_used_at = None
  3942. # Reprint of an archive reuses the source row. Without resetting
  3943. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3944. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3945. # extracts the *original* print's last frame, which then ships in
  3946. # the completion notification (#1707). Clear the path so the
  3947. # scanner runs fresh; also unlink the old video file so reprints
  3948. # don't accumulate orphans in the archive directory. Photos list
  3949. # is left alone — accumulating one finish photo per run is fine.
  3950. # The print-start baseline (#2704) is stale for the same reason:
  3951. # it describes the printer before the previous run. The capture
  3952. # below overwrites it, but clear it here too so an early failure
  3953. # can't leave the scan diffing against the wrong snapshot.
  3954. #
  3955. # Unlinked only when it is the same plate printing again. Every
  3956. # plate of a Send All shares this archive, and the video on it
  3957. # can be the only copy of another plate's run -- the printer's
  3958. # was deleted once it attached (#3275). That one is left in the
  3959. # archive directory, which goes with the archive. A video whose
  3960. # plate is not on record (attached by hand, or before the
  3961. # column existed) is kept too: nothing tells it apart from
  3962. # another plate's, and keeping costs one file where deleting
  3963. # can cost the only copy.
  3964. archive.timelapse_baseline = None
  3965. stale_timelapse_relpath = archive.timelapse_path
  3966. stale_timelapse_plate_id = archive.timelapse_plate_id
  3967. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  3968. if stale_timelapse_relpath:
  3969. archive.timelapse_path = None
  3970. archive.timelapse_plate_id = None
  3971. if stale_timelapse_relpath and stale_timelapse_plate_id != starting_plate_id:
  3972. logger.info(
  3973. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  3974. stale_timelapse_relpath,
  3975. stale_timelapse_plate_id,
  3976. expected_archive_id,
  3977. starting_plate_id,
  3978. )
  3979. elif stale_timelapse_relpath:
  3980. try:
  3981. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3982. if stale_path.is_file():
  3983. stale_path.unlink()
  3984. logger.info(
  3985. "Deleted stale timelapse %s on reprint of archive %s",
  3986. stale_timelapse_relpath,
  3987. expected_archive_id,
  3988. )
  3989. except OSError as e:
  3990. logger.warning(
  3991. "Failed to delete stale timelapse %s on reprint: %s",
  3992. stale_timelapse_relpath,
  3993. e,
  3994. )
  3995. # Persist a restart-stable id so a later restart resumes this
  3996. # archive by subtask_id instead of name-matching + duplicating
  3997. # it (#1485). The printer often hasn't echoed subtask_id back
  3998. # this soon after dispatch, so fall back to the id Bambuddy
  3999. # minted when it sent the print command. Scoped to this
  4000. # expected-print branch on purpose: an expected match means
  4001. # Bambuddy dispatched this exact print in this process, so the
  4002. # client's last-dispatch id genuinely belongs to it — using it
  4003. # for an externally-started print could mis-tag the archive.
  4004. effective_subtask_id = subtask_id
  4005. if not effective_subtask_id:
  4006. _client = printer_manager.get_client(printer_id)
  4007. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4008. if _dispatched:
  4009. effective_subtask_id = str(_dispatched).strip() or None
  4010. # Update on first-set OR on reprint (the queue dispatcher mints
  4011. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4012. # the rewrite for reprints leaves the archive holding the FIRST
  4013. # run's id; if MQTT then reconnects mid-print, the reconciler
  4014. # (#1542) compares the stale stored id against the printer's
  4015. # live id, sees a mismatch, and synthesises a bogus PRINT
  4016. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4017. # in #1807. Inequality check preserves the noop-on-stable-push
  4018. # behaviour the earlier `not archive.subtask_id` guard provided.
  4019. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4020. archive.subtask_id = effective_subtask_id
  4021. # #1403 follow-up: VP-queue archives are created with
  4022. # printer_id=None at queue-add time (we don't know which
  4023. # printer will run the job yet). When the print actually
  4024. # starts on a specific printer the expected-archive lookup
  4025. # used to skip this assignment, leaving printer_id=None
  4026. # forever — which then disables the "Scan for timelapse"
  4027. # button in ArchivesPage (gated on !archive.printer_id).
  4028. if archive.printer_id != printer_id:
  4029. archive.printer_id = printer_id
  4030. await db.commit()
  4031. # Track as active print
  4032. _active_prints[(printer_id, archive.filename)] = archive.id
  4033. if subtask_name:
  4034. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4035. # Start timelapse session if external camera is enabled (#1353).
  4036. # Queue / VP-dispatched prints land here in the expected-archive
  4037. # branch and used to skip start_session entirely — frames were
  4038. # never captured and the post-print stitch silently returned None.
  4039. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4040. # Inject ams_mapping into usage tracker session — the session was created
  4041. # before expected-print promotion, so it may have ams_mapping=None when
  4042. # the MQTT request topic subscription failed (common on P1S/A1).
  4043. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4044. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4045. if _stored_map or _stored_plate_id is not None:
  4046. try:
  4047. from backend.app.services.usage_tracker import _active_sessions
  4048. _ut_session = _active_sessions.get(printer_id)
  4049. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4050. _ut_session.ams_mapping = _stored_map
  4051. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4052. # plate_id injection covers direct-Print of plate N of a multi-plate
  4053. # 3MF — queue prints already capture it via the on_print_start queue
  4054. # lookup, but direct-Print never goes through the queue (#1697).
  4055. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4056. _ut_session.plate_id = _stored_plate_id
  4057. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4058. except Exception:
  4059. pass
  4060. # Set up energy tracking (#941: persist start on archive row)
  4061. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4062. await ws_manager.send_archive_updated(
  4063. {
  4064. "id": archive.id,
  4065. "status": "printing",
  4066. }
  4067. )
  4068. # Send notification with archive data (reprint/scheduled)
  4069. if not notification_sent:
  4070. # Use archive's created_by_id; fall back to the creator registered via
  4071. # register_expected_print (handles library-file-based queue items where
  4072. # the freshly-created archive has no created_by_id yet).
  4073. # Pop ALL matching keys so no stale entries remain in the dict.
  4074. fallback_creator = None
  4075. for key in expected_keys:
  4076. popped = _expected_print_creators.pop(key, None)
  4077. if fallback_creator is None:
  4078. fallback_creator = popped
  4079. archive_data = {
  4080. "print_time_seconds": archive.print_time_seconds,
  4081. "created_by_id": archive.created_by_id or fallback_creator,
  4082. }
  4083. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4084. # Extract printable objects from the archived 3MF file
  4085. _load_objects_from_archive(archive, printer_id, logger)
  4086. # Store Spoolman tracking data for per-filament usage reporting
  4087. try:
  4088. await _store_spoolman_print_data(
  4089. printer_id,
  4090. archive.id,
  4091. archive.file_path,
  4092. db,
  4093. printer_manager,
  4094. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4095. plate_id=_get_start_plate_id(archive.id),
  4096. )
  4097. except Exception as e:
  4098. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4099. # Price the print from its spools now rather than only at completion (#3261)
  4100. _schedule_archive_cost_estimate(
  4101. printer_id,
  4102. archive.id,
  4103. printer_manager,
  4104. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4105. plate_id=_get_start_plate_id(archive.id),
  4106. session_factory=async_session,
  4107. )
  4108. # Capture timelapse file baseline for snapshot-diff on completion
  4109. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4110. # hit this branch — without the baseline the completion-time scan
  4111. # falls into its "take baseline now" fallback, which snapshots
  4112. # AFTER the new MP4 already exists and never matches a diff
  4113. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4114. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4115. return # Skip creating a new archive
  4116. # Check if there's already a "printing" archive for this printer/file
  4117. # This prevents duplicates when backend restarts during an active print
  4118. from backend.app.models.archive import PrintArchive
  4119. existing_archive: PrintArchive | None = None
  4120. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4121. # across a backend restart for the same print, so this is the most
  4122. # reliable way to reattach. We also accept a previously stale-cancelled
  4123. # archive here so users upgrading mid-print get revived when the row
  4124. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4125. if subtask_id:
  4126. by_id = await db.execute(
  4127. select(PrintArchive)
  4128. .where(PrintArchive.printer_id == printer_id)
  4129. .where(PrintArchive.subtask_id == subtask_id)
  4130. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4131. .order_by(PrintArchive.created_at.desc())
  4132. .limit(1)
  4133. )
  4134. candidate = by_id.scalar_one_or_none()
  4135. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4136. existing_archive = candidate
  4137. # Fallback match: name-based lookup. Kept as-is for prints whose
  4138. # subtask_id is missing ("0" / local / non-cloud prints).
  4139. if existing_archive is None:
  4140. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4141. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4142. # A print started from the printer's screen names its file in full,
  4143. # so the forms above double its extension. The file itself is the
  4144. # one exact match, and nothing looser is added (#3009).
  4145. if _subtask_is_the_file(subtask_name, filename):
  4146. archive_filenames.append(subtask_name)
  4147. existing = await db.execute(
  4148. select(PrintArchive)
  4149. .where(PrintArchive.printer_id == printer_id)
  4150. .where(PrintArchive.status == "printing")
  4151. .where(
  4152. or_(
  4153. PrintArchive.print_name == check_name,
  4154. PrintArchive.filename.in_(archive_filenames),
  4155. )
  4156. )
  4157. .order_by(PrintArchive.created_at.desc())
  4158. .limit(1)
  4159. )
  4160. existing_archive = existing.scalar_one_or_none()
  4161. if existing_archive:
  4162. # subtask_id match → always resume, regardless of age. Same print,
  4163. # just a backend restart. Revive if it was previously stale-cancelled.
  4164. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4165. if subtask_match:
  4166. if existing_archive.status == "cancelled":
  4167. logger.warning(
  4168. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4169. existing_archive.id,
  4170. subtask_id,
  4171. )
  4172. existing_archive.status = "printing"
  4173. existing_archive.failure_reason = None
  4174. await db.commit()
  4175. else:
  4176. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4177. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4178. if existing_archive.energy_start_kwh is None:
  4179. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4180. if not notification_sent:
  4181. archive_data = {
  4182. "print_time_seconds": existing_archive.print_time_seconds,
  4183. "created_by_id": existing_archive.created_by_id,
  4184. }
  4185. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4186. _load_objects_from_archive(existing_archive, printer_id, logger)
  4187. return
  4188. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4189. # stale from the printer's *current* progress, not wall-clock age.
  4190. # A genuinely long print used to trip a blind 4h cutoff and have its
  4191. # live archive cancelled + duplicated on every backend restart
  4192. # (#1485). If the printer reports real progress, this name-matched
  4193. # 'printing' archive IS that ongoing print — resume it whatever its
  4194. # age. Only treat it as a stale leftover when the printer clearly
  4195. # shows a different, freshly-started print: near-0% progress on an
  4196. # archive far too old to still be at 0%. Unknown progress (printer
  4197. # not connected) never cancels — resuming is the safe default.
  4198. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4199. live_status = printer_manager.get_status(printer_id)
  4200. live_progress = getattr(live_status, "progress", None) if live_status else None
  4201. looks_stale = (
  4202. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4203. )
  4204. if looks_stale:
  4205. logger.warning(
  4206. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4207. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4208. )
  4209. existing_archive.status = "cancelled"
  4210. # Canonical key, not a sentence (issue #2974). "No status update
  4211. # received" is what both stale paths actually observed; which of
  4212. # the two it was is already carried by ``status`` -- cancelled
  4213. # here, the reconciled outcome at the reconnect site -- so one
  4214. # key loses no information and gives the Statistics breakdown a
  4215. # single bucket instead of two untranslatable prose strings.
  4216. existing_archive.failure_reason = "noStatusUpdate"
  4217. await db.commit()
  4218. # Fall through to create new archive (don't return)
  4219. else:
  4220. logger.info(
  4221. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4222. )
  4223. # Track this as the active print
  4224. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4225. # Attach subtask_id retroactively so future restarts can resume.
  4226. # Compare for inequality (not "is empty") to also pick up reprint
  4227. # dispatches that mint a fresh id — see #1807 for the bogus
  4228. # "Print Stopped" the strict-empty guard caused on reconnect.
  4229. if subtask_id and existing_archive.subtask_id != subtask_id:
  4230. existing_archive.subtask_id = subtask_id
  4231. await db.commit()
  4232. # Also set up energy tracking if not already tracked (#941: persisted column)
  4233. if existing_archive.energy_start_kwh is None:
  4234. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4235. # Send notification with archive data (existing archive)
  4236. if not notification_sent:
  4237. archive_data = {
  4238. "print_time_seconds": existing_archive.print_time_seconds,
  4239. "created_by_id": existing_archive.created_by_id,
  4240. }
  4241. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4242. # Extract printable objects from the archived 3MF file
  4243. _load_objects_from_archive(existing_archive, printer_id, logger)
  4244. return
  4245. # Build list of possible 3MF filenames to try
  4246. possible_names = []
  4247. # Bambu printers typically store files as "Name.gcode.3mf"
  4248. # The subtask_name is usually the best source for the filename
  4249. if subtask_name:
  4250. if _subtask_is_the_file(subtask_name, filename):
  4251. # A print started from the printer's own screen reports the
  4252. # file's full name, extension included. That is the file, so
  4253. # no extension is appended to it (#3009).
  4254. possible_names.append(subtask_name)
  4255. else:
  4256. # Try common Bambu naming patterns
  4257. possible_names.append(f"{subtask_name}.gcode.3mf")
  4258. possible_names.append(f"{subtask_name}.3mf")
  4259. # Try original filename with .3mf extension
  4260. if filename:
  4261. # Extract just the filename part, not the full path
  4262. fname = filename.split("/")[-1] if "/" in filename else filename
  4263. if fname.endswith(".3mf"):
  4264. possible_names.append(fname)
  4265. elif fname.endswith(".gcode"):
  4266. base = fname.rsplit(".", 1)[0]
  4267. possible_names.append(f"{base}.gcode.3mf")
  4268. possible_names.append(f"{base}.3mf")
  4269. else:
  4270. possible_names.append(f"{fname}.gcode.3mf")
  4271. possible_names.append(f"{fname}.3mf")
  4272. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4273. space_variants = []
  4274. for name in possible_names:
  4275. if " " in name:
  4276. space_variants.append(name.replace(" ", "_"))
  4277. possible_names.extend(space_variants)
  4278. # Remove duplicates while preserving order
  4279. seen = set()
  4280. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4281. logger.info("Trying filenames: %s", possible_names)
  4282. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4283. # here means none of the expected-/existing-archive write branches ran
  4284. # (they all return earlier) — only SELECTs have executed on this path, so
  4285. # this commit persists nothing; it ends the read transaction so the
  4286. # connection returns to the pool during the download. That download tries
  4287. # up to five remote paths per candidate filename with retry/backoff and
  4288. # can run for minutes under FTP contention; holding the session across it
  4289. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4290. # work runs during the download — the new-archive writes below re-acquire
  4291. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4292. await db.commit()
  4293. # Try to find and download the 3MF file
  4294. temp_path = None
  4295. downloaded_filename = None
  4296. # Cache check: cover endpoint may have already pulled this 3MF during
  4297. # the print (frontend opens the card and shows the thumbnail) — reuse
  4298. # that file instead of re-downloading 36MB over the same FTP link that
  4299. # just served it (#972). The cache keys on a normalized filename so
  4300. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4301. for try_filename in possible_names:
  4302. if not try_filename.endswith(".3mf"):
  4303. continue
  4304. cached = get_cached_3mf(printer_id, try_filename)
  4305. if cached:
  4306. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4307. temp_path = cached
  4308. downloaded_filename = try_filename
  4309. break
  4310. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4311. # H2-series and P2S the answer is routinely no — the file stays on
  4312. # internal eMMC and port 990 only ever serves external storage — and
  4313. # then the whole sweep below (six filenames x five directories x four
  4314. # retries, then the directory walk) is ~110 connections that cannot
  4315. # succeed. Skip it and say why (#2780).
  4316. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4317. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4318. # running rather than because the file is somewhere unreachable. The
  4319. # distinction is the whole of #2957: one is permanent, the other clears
  4320. # in minutes with the file still sitting on the printer.
  4321. blocked_by_ftps_cooloff = False
  4322. # Set when a probe reached the printer and still came back without the
  4323. # file -- a timeout mid-transfer, a refused connection, anything that is
  4324. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4325. # caught by name below, so a file that genuinely is not on the card
  4326. # leaves this False and schedules nothing. Anything else means the
  4327. # transfer, not the file, is what failed, and that does not last (#3063).
  4328. ftp_transfer_failed = False
  4329. # The print's name, for a fallback archive whose `subtask_name` the
  4330. # plate guard below had to disown. Display only, and deliberately kept
  4331. # apart from `subtask_name`: that variable is what every file lookup
  4332. # here is built from, and once a name has been shown to fetch another
  4333. # plate's 3MF it must not key `_active_prints` either, or the cover
  4334. # endpoint hands the same contradicted file to
  4335. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4336. display_name_after_plate_reject: str | None = None
  4337. # Get FTP retry settings
  4338. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4339. # ...but "the printer put it on eMMC" is where it went, not whether we
  4340. # can read it. An H2D with a card in mirrors the job to /cache and
  4341. # serves it happily, and skipping on the URL alone cost that reporter
  4342. # every archive for two days (#2856). So ask the printer instead of
  4343. # guessing: the dispatch named the exact file, which is one connection
  4344. # walking five paths rather than the sweep's ~110. Only when the probe
  4345. # comes back empty does the verdict's reason stand.
  4346. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4347. if ftps_handshake_blocked(printer.ip_address):
  4348. # Deliberately NOT recorded as a cool-off give-up. This branch
  4349. # only runs on an unreachable verdict, and that verdict is the
  4350. # honest, permanent reason the archive is empty — the probe was
  4351. # a long shot on top of it. Blaming the cool-off here would
  4352. # schedule a retry for a file sitting on internal eMMC, which is
  4353. # the sweep #2780 removed (#2957).
  4354. logger.debug(
  4355. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4356. storage.probe_filename,
  4357. printer_id,
  4358. )
  4359. else:
  4360. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4361. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4362. try:
  4363. probe_hit = await download_file_try_paths_async(
  4364. printer.ip_address,
  4365. printer.access_code,
  4366. ftp_probe_paths(storage.probe_filename),
  4367. probe_path,
  4368. socket_timeout=ftp_timeout,
  4369. printer_model=printer.model,
  4370. )
  4371. except Exception as e:
  4372. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4373. probe_hit = False
  4374. if probe_hit:
  4375. downloaded_filename = storage.probe_filename
  4376. temp_path = probe_path
  4377. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4378. # Naming the path, not just the file: a printer that keeps
  4379. # uploads around for weeks can serve a same-named copy of an
  4380. # earlier slice, and without the directory in the log that
  4381. # mismatch is invisible rather than merely rare (#1820).
  4382. logger.info(
  4383. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4384. downloaded_filename,
  4385. probe_hit,
  4386. printer_id,
  4387. storage.reason,
  4388. )
  4389. if not storage.reachable and not downloaded_filename:
  4390. # Same opening words whether or not a probe ran, because that is
  4391. # the phrase support asks people to grep for — only the tail says
  4392. # which of the two happened.
  4393. logger.info(
  4394. "Skipping the 3MF lookup for printer %s: %s — %s",
  4395. printer_id,
  4396. storage.reason,
  4397. "no copy of it on external storage either"
  4398. if storage.probe_filename
  4399. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4400. )
  4401. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4402. if not try_filename.endswith(".3mf"):
  4403. continue
  4404. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4405. # printers, so try it first — deferring it to last cost #972's reporter
  4406. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4407. # landing on the path that actually had the file.
  4408. remote_paths = [
  4409. f"/{try_filename}",
  4410. f"/cache/{try_filename}",
  4411. f"/model/{try_filename}",
  4412. f"/data/{try_filename}",
  4413. f"/data/Metadata/{try_filename}",
  4414. ]
  4415. temp_path = app_settings.archive_dir / "temp" / try_filename
  4416. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4417. for remote_path in remote_paths:
  4418. if ftps_handshake_blocked(printer.ip_address):
  4419. # The printer's FTPS service is not completing a TLS
  4420. # handshake, so it has no path we could reach — walking the
  4421. # remaining candidates only re-runs the same failure
  4422. # (#2780). Fall through to the no-3MF archive now.
  4423. #
  4424. # Remember *why*, though. This is the one give-up that is
  4425. # temporary: the cool-off clears in minutes and the file was
  4426. # on the printer the whole time. The fallback archive is
  4427. # stamped with it so a retry can be scheduled, and so the
  4428. # Archives banner stops blaming storage (#2957).
  4429. blocked_by_ftps_cooloff = True
  4430. logger.warning(
  4431. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4432. printer_id,
  4433. )
  4434. break
  4435. logger.debug("Trying FTP download: %s", remote_path)
  4436. try:
  4437. if ftp_retry_enabled:
  4438. downloaded = await with_ftp_retry(
  4439. download_file_async,
  4440. printer.ip_address,
  4441. printer.access_code,
  4442. remote_path,
  4443. temp_path,
  4444. timeout=ftp_timeout,
  4445. socket_timeout=ftp_timeout,
  4446. printer_model=printer.model,
  4447. max_retries=ftp_retry_count,
  4448. retry_delay=ftp_retry_delay,
  4449. operation_name=f"Download 3MF from {remote_path}",
  4450. cooloff_ip=printer.ip_address,
  4451. non_retry_exceptions=(FileNotOnPrinterError,),
  4452. )
  4453. else:
  4454. downloaded = await download_file_async(
  4455. printer.ip_address,
  4456. printer.access_code,
  4457. remote_path,
  4458. temp_path,
  4459. timeout=ftp_timeout,
  4460. socket_timeout=ftp_timeout,
  4461. printer_model=printer.model,
  4462. )
  4463. if downloaded:
  4464. downloaded_filename = try_filename
  4465. logger.info("Downloaded: %s", remote_path)
  4466. # Populate shared cache so the cover endpoint (if it
  4467. # runs next) doesn't refetch the same 36MB over FTP.
  4468. cache_3mf_download(printer_id, try_filename, temp_path)
  4469. break
  4470. # with_ftp_retry returns None once it has spent its budget,
  4471. # and download_file_async returns False on a timeout, so an
  4472. # exhausted transfer arrives here rather than as an
  4473. # exception (#3063).
  4474. ftp_transfer_failed = True
  4475. except FileNotOnPrinterError:
  4476. # 550 — file isn't at this path. Advance to next candidate
  4477. # without burning the retry budget.
  4478. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4479. except Exception as e:
  4480. ftp_transfer_failed = True
  4481. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4482. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4483. break
  4484. # If still not found, try listing directories to find matching file
  4485. # Different printer models use different directory structures. Skipped
  4486. # when the printer's FTPS handshake is failing — the directory walk is
  4487. # five more connections that cannot get further than the download did.
  4488. if (
  4489. not downloaded_filename
  4490. and storage.reachable
  4491. and (filename or subtask_name)
  4492. and not ftps_handshake_blocked(printer.ip_address)
  4493. ):
  4494. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4495. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4496. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4497. for search_dir in search_dirs:
  4498. if downloaded_filename:
  4499. break
  4500. try:
  4501. dir_files = await list_files_async(
  4502. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4503. )
  4504. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4505. if threemf_files:
  4506. logger.info(
  4507. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4508. )
  4509. for f in dir_files:
  4510. if f.get("is_directory"):
  4511. continue
  4512. fname = f.get("name", "")
  4513. # Normalize both for comparison (spaces and underscores are equivalent)
  4514. fname_normalized = fname.lower().replace(" ", "_")
  4515. search_normalized = search_term.replace(" ", "_")
  4516. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4517. logger.info("Found matching file in %s: %s", search_dir, fname)
  4518. temp_path = app_settings.archive_dir / "temp" / fname
  4519. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4520. remote_full_path = posixpath.join(search_dir, fname)
  4521. if ftp_retry_enabled:
  4522. downloaded = await with_ftp_retry(
  4523. download_file_async,
  4524. printer.ip_address,
  4525. printer.access_code,
  4526. remote_full_path,
  4527. temp_path,
  4528. timeout=ftp_timeout,
  4529. socket_timeout=ftp_timeout,
  4530. printer_model=printer.model,
  4531. max_retries=ftp_retry_count,
  4532. retry_delay=ftp_retry_delay,
  4533. operation_name=f"Download 3MF from {remote_full_path}",
  4534. cooloff_ip=printer.ip_address,
  4535. )
  4536. else:
  4537. downloaded = await download_file_async(
  4538. printer.ip_address,
  4539. printer.access_code,
  4540. remote_full_path,
  4541. temp_path,
  4542. timeout=ftp_timeout,
  4543. socket_timeout=ftp_timeout,
  4544. printer_model=printer.model,
  4545. )
  4546. if downloaded:
  4547. downloaded_filename = fname
  4548. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4549. cache_3mf_download(printer_id, fname, temp_path)
  4550. break
  4551. # The listing named the file, so it is on the card;
  4552. # only the transfer failed (#3063).
  4553. ftp_transfer_failed = True
  4554. except Exception as e:
  4555. logger.debug("Failed to list %s: %s", search_dir, e)
  4556. # Validate the downloaded 3MF actually matches the plate that's running
  4557. # (#1204): subtask_name lags across consecutive plates of the same model,
  4558. # so the first FTP candidate (built from subtask_name) can land on the
  4559. # previous plate's still-resident upload. Cross-check the slice_info
  4560. # plate index against the plate parsed from gcode_file (always fresh —
  4561. # it's the field whose change triggered this callback).
  4562. if downloaded_filename and temp_path:
  4563. expected_plate = parse_plate_id(filename)
  4564. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4565. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4566. logger.warning(
  4567. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4568. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4569. downloaded_filename,
  4570. actual_plate,
  4571. expected_plate,
  4572. subtask_name,
  4573. )
  4574. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4575. retry_succeeded = False
  4576. if corrected_subtask and corrected_subtask != subtask_name:
  4577. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4578. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4579. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4580. for remote_path in (
  4581. f"/{try_filename}",
  4582. f"/cache/{try_filename}",
  4583. f"/model/{try_filename}",
  4584. f"/data/{try_filename}",
  4585. f"/data/Metadata/{try_filename}",
  4586. ):
  4587. try:
  4588. if ftp_retry_enabled:
  4589. downloaded = await with_ftp_retry(
  4590. download_file_async,
  4591. printer.ip_address,
  4592. printer.access_code,
  4593. remote_path,
  4594. retry_temp_path,
  4595. timeout=ftp_timeout,
  4596. socket_timeout=ftp_timeout,
  4597. printer_model=printer.model,
  4598. max_retries=ftp_retry_count,
  4599. retry_delay=ftp_retry_delay,
  4600. operation_name=f"Re-download 3MF from {remote_path}",
  4601. cooloff_ip=printer.ip_address,
  4602. non_retry_exceptions=(FileNotOnPrinterError,),
  4603. )
  4604. else:
  4605. downloaded = await download_file_async(
  4606. printer.ip_address,
  4607. printer.access_code,
  4608. remote_path,
  4609. retry_temp_path,
  4610. timeout=ftp_timeout,
  4611. socket_timeout=ftp_timeout,
  4612. printer_model=printer.model,
  4613. )
  4614. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4615. logger.info(
  4616. "[CALLBACK] Re-download succeeded with corrected name %s "
  4617. "(plate %s) — replacing wrong file",
  4618. try_filename,
  4619. expected_plate,
  4620. )
  4621. try:
  4622. temp_path.unlink(missing_ok=True)
  4623. except OSError:
  4624. pass
  4625. temp_path = retry_temp_path
  4626. downloaded_filename = try_filename
  4627. subtask_name = corrected_subtask
  4628. cache_3mf_download(printer_id, try_filename, temp_path)
  4629. retry_succeeded = True
  4630. break
  4631. elif downloaded:
  4632. # Wrong plate again — discard and keep trying
  4633. try:
  4634. retry_temp_path.unlink(missing_ok=True)
  4635. except OSError:
  4636. pass
  4637. except FileNotOnPrinterError:
  4638. continue
  4639. except Exception as e:
  4640. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4641. if retry_succeeded:
  4642. break
  4643. # If the retry didn't find a matching file, drop the wrong 3MF
  4644. # so the no-3MF fallback below creates an archive whose name
  4645. # at least reflects the right plate.
  4646. if not retry_succeeded:
  4647. logger.warning(
  4648. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4649. expected_plate,
  4650. )
  4651. try:
  4652. temp_path.unlink(missing_ok=True)
  4653. except OSError:
  4654. pass
  4655. temp_path = None
  4656. downloaded_filename = None
  4657. # Whatever the sweep's transport did earlier, it is not why
  4658. # this archive ends up empty: a 3MF downloaded fine, it was
  4659. # just the wrong plate. Retrying would re-fetch that same
  4660. # contradicted file under the same stale names and hand it
  4661. # to _recover_fallback_archive, which checks that a
  4662. # candidate is a readable 3MF but not which plate it is --
  4663. # so the row would be filled in with another plate's
  4664. # filament and cost, the exact swap #2957 removed (#3063).
  4665. ftp_transfer_failed = False
  4666. # Disown the name for *lookups*: it has just been shown to
  4667. # fetch another plate's 3MF, and it keys `_active_prints`
  4668. # below, where the cover endpoint's own download of that
  4669. # same name would find this archive and fill it in with the
  4670. # file we are discarding here.
  4671. #
  4672. # Keep it for the *title*, which is a separate question.
  4673. # ``swap_plate_suffix`` returns None both for a name that
  4674. # carries no "- Plate N" / "_plate_N" suffix and for no
  4675. # name at all, and those are not the same situation: a name
  4676. # without a suffix holds no stale plate number to be wrong
  4677. # about. Blanking both uses at once dropped the project
  4678. # name too, and the row fell through to the gcode_file path
  4679. # titled "plate_1" though the real name was in hand.
  4680. # #1204's own premise is consecutive plates *of the same
  4681. # model*, so the project part is right either way (#3126).
  4682. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4683. subtask_name = corrected_subtask or ""
  4684. if not downloaded_filename or not temp_path:
  4685. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4686. # Create a fallback archive without 3MF data so the print is still tracked
  4687. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4688. try:
  4689. from backend.app.models.archive import PrintArchive
  4690. # Why the card is empty. The two temporary causes outrank the
  4691. # storage verdict because they say the sweep never got a fair
  4692. # answer: a cool-off skipped it at the transport, and a failed
  4693. # transfer reached the printer but never finished. Either way
  4694. # the file is still on the card, so reporting where the printer
  4695. # files its jobs would describe a setting that is not the
  4696. # problem (#2957, #3063).
  4697. if blocked_by_ftps_cooloff:
  4698. no_3mf_reason = REASON_FTPS_COOLOFF
  4699. elif storage.reachable and ftp_transfer_failed:
  4700. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4701. else:
  4702. no_3mf_reason = storage.reason
  4703. # Derive print name from subtask_name or filename. The
  4704. # plate guard's disowned name comes second: it is a real name
  4705. # for a real print, and only the gcode_file path is left
  4706. # otherwise -- which titles the row "plate_1" (#3126).
  4707. print_name = subtask_name or display_name_after_plate_reject or filename
  4708. if print_name:
  4709. # Clean up the name (remove extensions, path parts)
  4710. print_name = print_name.split("/")[-1]
  4711. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4712. else:
  4713. print_name = "Unknown Print"
  4714. # Recover estimated print time from MQTT (best-effort for notifications)
  4715. fallback_print_time = None
  4716. mqtt_remaining = data.get("remaining_time")
  4717. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4718. fallback_print_time = int(mqtt_remaining)
  4719. if fallback_print_time is None:
  4720. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4721. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4722. fallback_print_time = int(mc_remaining * 60)
  4723. # Best-effort filament metadata from MQTT — see
  4724. # _extract_filament_data_from_mqtt. Without this the fallback
  4725. # archive's filament fields stayed NULL even though the AMS
  4726. # state at print start was sitting right there in `data`.
  4727. # The slicer's ams_mapping (when present) narrows the result
  4728. # to slots actually used by the print (#1533).
  4729. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4730. # Create minimal archive entry
  4731. fallback_archive = PrintArchive(
  4732. printer_id=printer_id,
  4733. filename=filename or f"{print_name}.3mf",
  4734. file_path="", # Empty - no 3MF file available
  4735. file_size=0,
  4736. print_name=print_name,
  4737. print_time_seconds=fallback_print_time,
  4738. status="printing",
  4739. started_at=datetime.now(timezone.utc),
  4740. subtask_id=subtask_id,
  4741. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4742. filament_type=mqtt_filament_meta.get("filament_type"),
  4743. filament_color=mqtt_filament_meta.get("filament_color"),
  4744. extra_data={
  4745. "no_3mf_available": True,
  4746. # Why the card is empty, when we know -- see above. The
  4747. # banner reads this to stop telling H2/P2 owners to
  4748. # switch on a setting that is already on and would not
  4749. # have helped (#2780).
  4750. "no_3mf_reason": no_3mf_reason,
  4751. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4752. "_print_data": data,
  4753. },
  4754. )
  4755. db.add(fallback_archive)
  4756. await db.commit()
  4757. await db.refresh(fallback_archive)
  4758. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4759. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4760. # Track as active print
  4761. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4762. if filename:
  4763. _active_prints[(printer_id, filename)] = fallback_archive.id
  4764. if subtask_name:
  4765. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4766. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4767. # Record starting energy if smart plug available (#941: persisted column)
  4768. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4769. # Send WebSocket notification
  4770. await ws_manager.send_archive_created(
  4771. {
  4772. "id": fallback_archive.id,
  4773. "printer_id": fallback_archive.printer_id,
  4774. "filename": fallback_archive.filename,
  4775. "print_name": fallback_archive.print_name,
  4776. "status": fallback_archive.status,
  4777. }
  4778. )
  4779. # MQTT relay - publish archive created
  4780. try:
  4781. await mqtt_relay.on_archive_created(
  4782. archive_id=fallback_archive.id,
  4783. print_name=fallback_archive.print_name,
  4784. printer_name=printer.name,
  4785. status=fallback_archive.status,
  4786. )
  4787. except Exception:
  4788. pass # Don't fail if MQTT fails
  4789. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4790. try:
  4791. await _store_spoolman_print_data(
  4792. printer_id,
  4793. fallback_archive.id,
  4794. fallback_archive.file_path,
  4795. db,
  4796. printer_manager,
  4797. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4798. plate_id=_get_start_plate_id(fallback_archive.id),
  4799. )
  4800. except Exception as e:
  4801. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4802. # Both temporary give-ups are worth coming back for, and for
  4803. # the same reason: the file is on the printer and the last look
  4804. # failed at the transport rather than finding nothing. One waits
  4805. # out the handshake block (#2957), the other waits for the
  4806. # printer to stop being busy (#3063). Deliberately not scheduled
  4807. # for a storage verdict: a file on internal eMMC will not appear
  4808. # at any FTPS path however long we wait, and retrying it is
  4809. # exactly the sweep #2780 removed.
  4810. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4811. # `possible_names`, not the raw MQTT strings: it is the exact
  4812. # list this flow just tried, already stripped of any path
  4813. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4814. # some firmware) and deduped.
  4815. _schedule_fallback_3mf_retry(
  4816. printer_id=printer_id,
  4817. archive_id=fallback_archive.id,
  4818. filenames=list(possible_names),
  4819. reason=no_3mf_reason,
  4820. )
  4821. # Send notification without archive data (file not found)
  4822. if not notification_sent:
  4823. await _send_print_start_notification(printer_id, data, logger=logger)
  4824. # The same baseline the other two on_print_start branches take
  4825. # (#2704), and last for the same reason they are: it lists the
  4826. # printer's timelapse directory, so a slow card must not delay
  4827. # the _active_prints registration, the energy reading, the
  4828. # archive-created event or the start notification above it.
  4829. #
  4830. # This branch never took one, so every no-3MF archive reached
  4831. # completion with no baseline in memory and none on the row, and
  4832. # the completion scan fell into its "snapshot now" fallback --
  4833. # which runs after the printer has written the video, so the new
  4834. # file landed inside the baseline and no diff ever matched
  4835. # (#2957 follow-up).
  4836. #
  4837. # Skipped when the FTPS cool-off is what produced this fallback:
  4838. # the listing needs the same connection that just failed, so it
  4839. # could only record that the card was unreadable. The scan
  4840. # handles that case by refusing to choose between candidates.
  4841. if not blocked_by_ftps_cooloff:
  4842. await _capture_timelapse_baseline_at_start(
  4843. printer, printer_id, logger, archive_id=fallback_archive.id
  4844. )
  4845. return
  4846. except Exception as e:
  4847. logger.error("Failed to create fallback archive: %s", e)
  4848. # Send notification without archive data (file not found)
  4849. if not notification_sent:
  4850. await _send_print_start_notification(printer_id, data, logger=logger)
  4851. return
  4852. try:
  4853. # Archive the file with status "printing"
  4854. service = ArchiveService(db)
  4855. archive = await service.archive_print(
  4856. printer_id=printer_id,
  4857. source_file=temp_path,
  4858. print_data={**data, "status": "printing"},
  4859. subtask_id=subtask_id,
  4860. )
  4861. if archive:
  4862. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4863. # Set on the row rather than passed to archive_print, which also
  4864. # serves the queue dispatcher — there the queue item decides.
  4865. # Guarded because this branch has no ``except``: an unhandled
  4866. # write error would take the _active_prints registration, the
  4867. # start notification, the energy reading and the timelapse
  4868. # baseline below it with it, and a missing prompt is by far the
  4869. # cheaper failure.
  4870. archive_id = archive.id
  4871. try:
  4872. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4873. archive.confirm_requested = True
  4874. await db.commit()
  4875. except Exception as e:
  4876. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4877. # The rollback expires every loaded object, and on an async
  4878. # session reading one afterwards raises instead of
  4879. # reloading, so the two this branch goes on to use are
  4880. # fetched again. The archive itself was committed by
  4881. # archive_print; only the flag is lost.
  4882. try:
  4883. await db.rollback()
  4884. archive = await db.get(PrintArchive, archive_id)
  4885. printer = await db.get(Printer, printer_id)
  4886. except Exception as reload_error:
  4887. logger.warning(
  4888. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4889. )
  4890. # Track this active print (use both original filename and downloaded filename)
  4891. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4892. if filename and filename != downloaded_filename:
  4893. _active_prints[(printer_id, filename)] = archive.id
  4894. if subtask_name:
  4895. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4896. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4897. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4898. # Record starting energy from smart plug if available (#941: persisted column)
  4899. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4900. await ws_manager.send_archive_created(
  4901. {
  4902. "id": archive.id,
  4903. "printer_id": archive.printer_id,
  4904. "filename": archive.filename,
  4905. "print_name": archive.print_name,
  4906. "status": archive.status,
  4907. }
  4908. )
  4909. # MQTT relay - publish archive created
  4910. try:
  4911. await mqtt_relay.on_archive_created(
  4912. archive_id=archive.id,
  4913. print_name=archive.print_name,
  4914. printer_name=printer.name,
  4915. status=archive.status,
  4916. )
  4917. except Exception:
  4918. pass # Don't fail if MQTT fails
  4919. # Send notification with archive data (new archive created)
  4920. if not notification_sent:
  4921. archive_data = {
  4922. "print_time_seconds": archive.print_time_seconds,
  4923. "created_by_id": archive.created_by_id,
  4924. }
  4925. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4926. # Extract printable objects for skip object functionality
  4927. try:
  4928. from backend.app.services.archive import extract_printable_objects_from_3mf
  4929. client = printer_manager.get_client(printer_id)
  4930. if client:
  4931. with open(temp_path, "rb") as f:
  4932. threemf_data = f.read()
  4933. # Extract with positions for UI overlay, scoped to the
  4934. # plate that is printing — an all-plates 3MF carries
  4935. # every plate's objects (#2522).
  4936. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4937. threemf_data,
  4938. plate_number=resolve_plate_id(client.state),
  4939. include_positions=True,
  4940. )
  4941. if printable_objects:
  4942. # Store objects in printer state
  4943. client.state.printable_objects = printable_objects
  4944. client.state.printable_objects_bbox_all = bbox_all
  4945. client.state.skipped_objects = [] # Reset skipped objects for new print
  4946. logger.info(
  4947. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4948. )
  4949. except Exception as e:
  4950. logger.debug("Failed to extract printable objects: %s", e)
  4951. # Store Spoolman tracking data for per-filament usage reporting
  4952. try:
  4953. await _store_spoolman_print_data(
  4954. printer_id,
  4955. archive.id,
  4956. archive.file_path,
  4957. db,
  4958. printer_manager,
  4959. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4960. plate_id=_get_start_plate_id(archive.id),
  4961. )
  4962. except Exception as e:
  4963. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4964. # Price the print from its spools now rather than only at completion (#3261)
  4965. _schedule_archive_cost_estimate(
  4966. printer_id,
  4967. archive.id,
  4968. printer_manager,
  4969. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4970. plate_id=_get_start_plate_id(archive.id),
  4971. session_factory=async_session,
  4972. )
  4973. # Capture timelapse file baseline for snapshot-diff on completion
  4974. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4975. finally:
  4976. # Keep temp_path around until print completes so the cover endpoint
  4977. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4978. # the file. If the cache entry was evicted early (file vanished),
  4979. # clean up any stragglers here to avoid leaking disk on retries.
  4980. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4981. if temp_path and temp_path.exists() and cached_now != temp_path:
  4982. temp_path.unlink()
  4983. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4984. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4985. # tests can shrink them without waiting out real delays.
  4986. #
  4987. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4988. # looking. Across 247 support bundles the attempt that found the video was #1
  4989. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4990. # decaying one, which is the signature of a budget that expires while files are
  4991. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4992. # prints make big videos and the printer writes them after the print ends, so
  4993. # the poll now runs for minutes and costs one FTP LIST per round.
  4994. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4995. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4996. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4997. def _timelapse_scan_max_attempts() -> int:
  4998. """Round cap for the poll, derived from the wall-clock budget.
  4999. The deadline alone is not a sufficient bound: it assumes each round really
  5000. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5001. and an FTP list that fails immediately would otherwise spin against the
  5002. printer at full speed for the whole window. Whichever bound is reached
  5003. first ends the poll.
  5004. """
  5005. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5006. # A zero interval makes the wall-clock budget meaningless; fall back to
  5007. # the round count the production interval would have given.
  5008. return 32
  5009. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5010. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5011. """Video filenames already attached to some other archive of this printer.
  5012. Used to disambiguate when more than one file is new since the baseline —
  5013. which happens when a previous print's video landed after this print's
  5014. baseline was taken. Ordering the candidates would be the obvious fix and is
  5015. the wrong one: it can only be done on mtime or on the filename timestamp,
  5016. both of which come from the printer's own clock, and a LAN-only printer
  5017. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5018. ``attach_timelapse`` saves the video into the archive directory under the
  5019. printer's original filename, and the later MP4 conversion keeps the stem,
  5020. so the stem of ``timelapse_path`` recovers what was claimed.
  5021. """
  5022. from backend.app.models.archive import PrintArchive
  5023. rows = await db.execute(
  5024. select(PrintArchive.timelapse_path).where(
  5025. PrintArchive.printer_id == printer_id,
  5026. PrintArchive.id != exclude_archive_id,
  5027. PrintArchive.timelapse_path.is_not(None),
  5028. )
  5029. )
  5030. return {Path(p).stem for p in rows.scalars().all() if p}
  5031. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5032. """Whether an *empty* timelapse listing for *printer* can be believed.
  5033. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5034. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5035. from one holding no videos. Everywhere that only wants to know "is there a
  5036. video yet" the difference does not matter — both mean "not yet, retry".
  5037. It matters where an empty listing is recorded as a *baseline*. Recording
  5038. "the card held nothing" for a card that was never read means every video on
  5039. it counts as new once the cool-off expires, and the completion scan then
  5040. attaches a stale video to this print and deletes it from the printer
  5041. (#2957 follow-up). Those two callers ask this first.
  5042. """
  5043. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5044. ip_address = getattr(printer, "ip_address", None)
  5045. if not ip_address:
  5046. return True
  5047. return not ftps_handshake_blocked(ip_address)
  5048. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5049. """List video files from printer's timelapse directory.
  5050. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5051. Returns (video_files, found_path) where video_files is a list of file dicts
  5052. and found_path is the directory where they were found, or ([], None).
  5053. An empty return does not distinguish "no videos" from "could not read the
  5054. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5055. baseline callers consult before believing one.
  5056. """
  5057. from backend.app.services.bambu_ftp import list_files_async
  5058. logger = logging.getLogger(__name__)
  5059. # No card in the slot means no /timelapse to walk — four connections that
  5060. # can only fail, on a path whose failures are swallowed and so would go on
  5061. # costing time silently forever (#2780).
  5062. #
  5063. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5064. # inside the loop's own try/except, so a caller that passed something
  5065. # unexpected used to get an empty listing rather than an exception. Keep
  5066. # that, instead of making this gate the first thing that can raise here.
  5067. printer_id = getattr(printer, "id", None)
  5068. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5069. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5070. return [], None
  5071. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5072. try:
  5073. found_files = await list_files_async(
  5074. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5075. )
  5076. if found_files:
  5077. video_files = [
  5078. f
  5079. for f in found_files
  5080. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5081. ]
  5082. if video_files:
  5083. return video_files, timelapse_path
  5084. except Exception as e:
  5085. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5086. continue
  5087. return [], None
  5088. async def _capture_timelapse_baseline_at_start(
  5089. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5090. ) -> None:
  5091. """Snapshot the printer's timelapse directory at print start so the
  5092. completion-time scan can pick the new file by set-difference.
  5093. Must be called from every on_print_start path that proceeds to a real
  5094. print — both the new-archive branch and the expected-archive branch (which
  5095. queue / VP-dispatched prints take). Without a baseline,
  5096. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5097. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5098. so the new file ends up in the "baseline" set and no diff ever matches.
  5099. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5100. unreliable — the snapshot-diff approach sidesteps that entirely.
  5101. When ``archive_id`` is known the baseline is also written to the archive
  5102. row, so it survives a restart and the manual "Scan for Timelapse" button
  5103. can run the same diff instead of falling back to clock-based matching
  5104. (#2704). Only baselines taken at print start are persisted — one taken at
  5105. completion already contains the new video and would poison a later scan.
  5106. """
  5107. names: set[str] | None = None
  5108. try:
  5109. if not _timelapse_listing_is_trustworthy(printer):
  5110. # Recorded anyway, deliberately. An empty baseline taken off a card
  5111. # we could not read is not authoritative, but it is still the right
  5112. # *default*: Bambuddy deletes each video from the printer once it is
  5113. # attached, so the usual card holds exactly one video at completion
  5114. # and an empty baseline resolves it correctly. Persisting NULL
  5115. # instead would send completion to take its own snapshot, by which
  5116. # point this print's video is on the card and would be swallowed by
  5117. # it. The ambiguity is handled where it actually bites — see
  5118. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5119. logger.warning(
  5120. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5121. "handshake cool-off, so the card could not be read — treating it as empty",
  5122. printer_id,
  5123. )
  5124. baseline_files, _ = await _list_timelapse_videos(printer)
  5125. names = {f.get("name", "") for f in baseline_files}
  5126. _timelapse_baselines[printer_id] = names
  5127. logger.info(
  5128. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5129. len(names),
  5130. printer_id,
  5131. )
  5132. except Exception as e:
  5133. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5134. if archive_id is None:
  5135. return
  5136. try:
  5137. async with async_session() as db:
  5138. from backend.app.models.archive import PrintArchive
  5139. archive = await db.get(PrintArchive, archive_id)
  5140. if archive is not None:
  5141. # Written even when the listing failed, and then as NULL. A
  5142. # reprint reuses the archive row, so leaving the previous run's
  5143. # baseline in place would have the scan diff this print against
  5144. # the state of the printer before the *last* one — and a stale
  5145. # baseline reads as authoritative, where NULL correctly falls
  5146. # back to a fresh snapshot.
  5147. archive.timelapse_baseline = sorted(names) if names is not None else None
  5148. await db.commit()
  5149. except Exception as e:
  5150. # In-memory baseline still covers the normal completion path.
  5151. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5152. async def _scan_for_timelapse_with_retries(
  5153. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5154. ):
  5155. """Poll the printer for this print's timelapse and attach it.
  5156. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5157. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5158. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5159. (#2704). Comparing the current listing against the set of filenames that
  5160. existed when the print started needs no clock at all, because the printer
  5161. writes the video only once the print has ended.
  5162. Baseline precedence: the caller's in-memory set, then the one persisted on
  5163. the archive at print start, then a snapshot taken now. The last of those is
  5164. a poor substitute — by completion the new video may already be on the card,
  5165. in which case it lands in the "baseline" and no diff can ever match — but it
  5166. is all that is available for a print that began before Bambuddy started.
  5167. On success the video is deleted from the printer, which keeps ``/timelapse``
  5168. down to the unclaimed files and makes the next diff unambiguous.
  5169. """
  5170. logger = logging.getLogger(__name__)
  5171. # Cleared when the baseline had to be taken off a card we could not read, so
  5172. # the attach step refuses to choose between several candidates (#2957).
  5173. baseline_trusted = True
  5174. # --- Phase 1: establish the baseline -------------------------------------
  5175. try:
  5176. async with async_session() as db:
  5177. from backend.app.models.printer import Printer
  5178. service = ArchiveService(db)
  5179. archive = await service.get_archive(archive_id)
  5180. if not archive:
  5181. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5182. return
  5183. if archive.timelapse_path:
  5184. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5185. return
  5186. if not archive.printer_id:
  5187. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5188. return
  5189. if baseline_names is not None:
  5190. logger.info(
  5191. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5192. len(baseline_names),
  5193. archive_id,
  5194. )
  5195. elif archive.timelapse_baseline is not None:
  5196. # Persisted at print start — survives a restart mid-print.
  5197. baseline_names = set(archive.timelapse_baseline)
  5198. logger.info(
  5199. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5200. len(baseline_names),
  5201. archive_id,
  5202. )
  5203. else:
  5204. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5205. printer = result.scalar_one_or_none()
  5206. if not printer:
  5207. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5208. return
  5209. if not _timelapse_listing_is_trustworthy(printer):
  5210. # The card is unreadable at the one moment a baseline has to
  5211. # be taken, so the empty listing below means "we never
  5212. # looked", not "these are all new". Carry on with it anyway
  5213. # — the usual card holds exactly one video, which resolves
  5214. # correctly — but stop the poll from *choosing* between
  5215. # several, which is how a stale video got attached to this
  5216. # print and then deleted off the printer (#2957 follow-up).
  5217. baseline_trusted = False
  5218. logger.warning(
  5219. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5220. "handshake cool-off. A single new video still resolves; several will not be "
  5221. "guessed between — use Scan for Timelapse to pick one by hand",
  5222. archive_id,
  5223. archive.printer_id,
  5224. )
  5225. baseline_files, _ = await _list_timelapse_videos(printer)
  5226. baseline_names = {f.get("name", "") for f in baseline_files}
  5227. logger.info(
  5228. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5229. len(baseline_names),
  5230. archive_id,
  5231. )
  5232. except Exception as e:
  5233. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5234. return
  5235. # --- Phase 2: poll for a file that was not there when the print began -----
  5236. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5237. max_attempts = _timelapse_scan_max_attempts()
  5238. seen_names: set[str] = set()
  5239. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5240. attempt = 0
  5241. while True:
  5242. await asyncio.sleep(delay)
  5243. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5244. attempt += 1
  5245. try:
  5246. from backend.app.models.printer import Printer
  5247. # Read phase: fetch archive + printer in a short session and release
  5248. # the pooled connection BEFORE the FTP list/download below. Holding it
  5249. # across the FTP round-trips left one connection idle-in-transaction per
  5250. # in-flight scan (issue #2572).
  5251. async with async_session() as db:
  5252. service = ArchiveService(db)
  5253. archive = await service.get_archive(archive_id)
  5254. if not archive:
  5255. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5256. return
  5257. if archive.timelapse_path:
  5258. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5259. return
  5260. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5261. printer = result.scalar_one_or_none()
  5262. if not printer:
  5263. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5264. return
  5265. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5266. # I/O phase (no DB connection held): FTP list + download.
  5267. video_files, found_path = await _list_timelapse_videos(printer)
  5268. # The poll can run for dozens of rounds, so only narrate a round
  5269. # that saw something change. Repeating the whole listing every 30 s
  5270. # would bury the one interesting line in the support bundle.
  5271. names_now = {f.get("name", "") for f in video_files}
  5272. changed = attempt == 1 or names_now != seen_names
  5273. seen_names = names_now
  5274. speak = logger.info if changed else logger.debug
  5275. if video_files:
  5276. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5277. if changed:
  5278. for f in video_files[:5]:
  5279. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5280. attached = await _attach_first_unclaimed_timelapse(
  5281. archive_id,
  5282. printer,
  5283. video_files,
  5284. baseline_names,
  5285. claimed,
  5286. attempt,
  5287. logger,
  5288. quiet=not changed,
  5289. require_unambiguous=not baseline_trusted,
  5290. plate_id=plate_id,
  5291. )
  5292. if attached:
  5293. return
  5294. else:
  5295. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5296. except Exception as e:
  5297. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5298. if attempt >= max_attempts or time.monotonic() >= deadline:
  5299. break
  5300. # No name-match fallback: it compared the print name against the filename,
  5301. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5302. # bundles it fired 159 times and matched zero times, so all it added was a
  5303. # misleading log line before giving up.
  5304. logger.warning(
  5305. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5306. archive_id,
  5307. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5308. )
  5309. async def _attach_first_unclaimed_timelapse(
  5310. archive_id: int,
  5311. printer,
  5312. video_files: list[dict],
  5313. baseline_names: set[str],
  5314. claimed: set[str],
  5315. attempt: int,
  5316. logger: logging.Logger,
  5317. *,
  5318. quiet: bool = False,
  5319. require_unambiguous: bool = False,
  5320. plate_id: int | None = None,
  5321. ) -> bool:
  5322. """Download and attach the one video that belongs to this print.
  5323. A candidate is any file absent from the print-start baseline. More than one
  5324. can qualify when a previous print's video landed late, after this print's
  5325. baseline was taken — those are filtered out by name, because they are
  5326. already attached to another archive. Sorting the candidates instead would
  5327. mean sorting on mtime or on the filename timestamp, both of which come from
  5328. the printer's unsynced clock.
  5329. Returns True once a video is attached. The printer's copy is deleted only
  5330. after the attach succeeds on bytes whose length matched the listing.
  5331. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5332. already seen this exact listing — the poll runs for many rounds and only the
  5333. rounds where something changed are worth an INFO line.
  5334. """
  5335. from backend.app.services.bambu_ftp import (
  5336. delete_archived_timelapse,
  5337. download_file_bytes_async,
  5338. remote_file_settled,
  5339. )
  5340. speak = logger.debug if quiet else logger.info
  5341. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5342. if not new_files:
  5343. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5344. return False
  5345. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5346. if not candidates:
  5347. speak(
  5348. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5349. attempt,
  5350. len(new_files),
  5351. )
  5352. return False
  5353. if len(candidates) > 1:
  5354. if require_unambiguous:
  5355. # The baseline is not evidence -- it was taken off a card that could
  5356. # not be read -- so "new since the baseline" does not narrow these
  5357. # down at all. Taking the first would attach an arbitrary video to
  5358. # this print and then delete it from the printer.
  5359. logger.warning(
  5360. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5361. "leaving all of them on the printer for manual selection",
  5362. attempt,
  5363. len(candidates),
  5364. ", ".join(str(f.get("name")) for f in candidates),
  5365. )
  5366. return False
  5367. logger.warning(
  5368. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5369. "the rest stay on the printer for manual selection",
  5370. attempt,
  5371. len(candidates),
  5372. ", ".join(str(f.get("name")) for f in candidates),
  5373. )
  5374. target = candidates[0]
  5375. file_name = target.get("name")
  5376. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5377. logger.info(
  5378. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5379. attempt,
  5380. file_name,
  5381. archive_id,
  5382. )
  5383. # The listing always carries a size (`list_files` skips entries it can't
  5384. # parse), but read it explicitly: the delete below is destructive and must
  5385. # depend on a size we actually had, not on one we hoped was there.
  5386. expected_size = target.get("size")
  5387. timelapse_data = await download_file_bytes_async(
  5388. printer.ip_address,
  5389. printer.access_code,
  5390. remote_path,
  5391. printer_model=printer.model,
  5392. expected_size=expected_size,
  5393. )
  5394. if not timelapse_data:
  5395. # Short or failed transfer. The printer keeps its copy, so the next
  5396. # round can try again — which is exactly why the delete below is
  5397. # gated on a verified download.
  5398. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5399. return False
  5400. # The length check above proves we got what the listing said, not that the
  5401. # printer had finished writing. A video still being written can be listed
  5402. # short, served short, and pass — so confirm it has stopped growing before
  5403. # committing to it and deleting the original (#2704).
  5404. if not await remote_file_settled(
  5405. printer.ip_address,
  5406. printer.access_code,
  5407. remote_path,
  5408. len(timelapse_data),
  5409. printer_model=printer.model,
  5410. ):
  5411. return False
  5412. # Write phase: attach in a fresh short-lived session.
  5413. async with async_session() as db:
  5414. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5415. if not success:
  5416. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5417. return False
  5418. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5419. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5420. await delete_archived_timelapse(
  5421. printer.ip_address,
  5422. printer.access_code,
  5423. remote_path,
  5424. verified=expected_size is not None,
  5425. printer_model=printer.model,
  5426. printer_name=printer.name,
  5427. )
  5428. return True
  5429. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5430. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5431. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5432. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5433. # How long the *background* upgrade keeps waiting after the notification has
  5434. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5435. # printer can't hold up the print-complete notification; this one exists so the
  5436. # archive still ends up with the better frame afterwards.
  5437. #
  5438. # Measured across 261 attaches in the support bundles, the video lands a median
  5439. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5440. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5441. # was 546s. Every other model was inside 26s. The long budget is therefore
  5442. # almost entirely for P1-series users; on everything else the short wait already
  5443. # wins and this task never runs.
  5444. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5445. async def _capture_finish_photo_from_timelapse(
  5446. archive_id: int,
  5447. archive_dir: Path,
  5448. timeout: float | None = None,
  5449. rotation: int = 0,
  5450. ) -> tuple[str | None, bool]:
  5451. """Wait for the per-print timelapse to land on the archive and extract its
  5452. last frame as the finish photo (#1397).
  5453. Bambu firmware stops timelapse recording after the toolhead parks but
  5454. before the bed-drop end-gcode runs, so the last frame frames the finished
  5455. print correctly. A live camera grab at gcode_state=FINISH captures the
  5456. bed already lowered.
  5457. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5458. ``archive.timelapse_path`` when the file lands. This function polls for
  5459. that field.
  5460. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5461. the wait ran out with no video on the archive yet — i.e. the video may
  5462. still be coming and a later attempt could succeed. It is False when the
  5463. video landed (whether or not extraction worked), because in that case
  5464. waiting longer changes nothing. The caller uses that to decide between
  5465. falling back permanently and scheduling a background upgrade.
  5466. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5467. still (#2708) so this source agrees with every other finish-photo source.
  5468. The archived video itself is the printer's own file and is left alone —
  5469. rotating it would mean re-encoding it.
  5470. """
  5471. import uuid
  5472. from backend.app.models.archive import PrintArchive
  5473. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5474. logger = logging.getLogger(__name__)
  5475. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5476. deadline = asyncio.get_event_loop().time() + budget
  5477. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5478. while True:
  5479. async with async_session() as db:
  5480. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5481. archive = result.scalar_one_or_none()
  5482. timelapse_relpath = archive.timelapse_path if archive else None
  5483. if timelapse_relpath:
  5484. video_path = app_settings.base_dir / timelapse_relpath
  5485. if video_path.exists() and video_path.stat().st_size > 0:
  5486. photos_dir = archive_dir / "photos"
  5487. photos_dir.mkdir(parents=True, exist_ok=True)
  5488. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5489. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5490. output_path = photos_dir / filename
  5491. if await extract_video_last_frame(video_path, output_path):
  5492. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5493. logger.info(
  5494. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5495. video_path.name,
  5496. archive_id,
  5497. )
  5498. return filename, False
  5499. logger.warning(
  5500. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5501. video_path.name,
  5502. archive_id,
  5503. )
  5504. return None, False
  5505. if asyncio.get_event_loop().time() >= deadline:
  5506. logger.info(
  5507. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5508. archive_id,
  5509. budget,
  5510. )
  5511. return None, True
  5512. await asyncio.sleep(poll_interval)
  5513. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5514. """Add the timelapse's last frame to an archive after the fact (#2704).
  5515. The print-complete notification waits only ~60s for the video, because
  5516. holding a notification for minutes is worse than sending it with a live
  5517. camera grab. On a P1-series printer the video often lands well after that,
  5518. so the archive used to be stuck with the live grab — which is taken at
  5519. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5520. the worse photo of the two.
  5521. This keeps waiting in the background and, when the video arrives, extracts
  5522. the frame and puts it *first* in the archive's photo list, so opening the
  5523. gallery shows it. The live grab is deliberately kept: the notification that
  5524. already went out links to that exact file, and deleting it would leave a
  5525. broken image in Discord or Telegram.
  5526. """
  5527. logger = logging.getLogger(__name__)
  5528. filename, _ = await _capture_finish_photo_from_timelapse(
  5529. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5530. )
  5531. if not filename:
  5532. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5533. return
  5534. try:
  5535. async with async_session() as db:
  5536. from backend.app.models.archive import PrintArchive
  5537. archive = await db.get(PrintArchive, archive_id)
  5538. if archive is None:
  5539. return
  5540. photos = list(archive.photos or [])
  5541. if filename in photos:
  5542. return
  5543. # Front of the list: PhotoGalleryModal opens at index 0.
  5544. archive.photos = [filename, *photos]
  5545. await db.commit()
  5546. except Exception as e:
  5547. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5548. return
  5549. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5550. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5551. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5552. """Put the filament-attribution context back after a restart mid-print.
  5553. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5554. both die with the process. The print keeps running, so at completion the
  5555. tracker would fall back to whatever the printer reports *now* — and AMS
  5556. filament backup makes "now" the substitute tray, charging the whole print
  5557. to the spool that only finished it.
  5558. The persisted row is only trusted when its print name still matches what
  5559. the printer says it is running: a row left behind by a completion we never
  5560. saw must not attach itself to the next print.
  5561. """
  5562. try:
  5563. from backend.app.api.routes.settings import get_setting
  5564. from backend.app.services.usage_tracker import (
  5565. clear_persisted_session,
  5566. get_persisted_print_name,
  5567. restore_session,
  5568. )
  5569. persisted_name = await get_persisted_print_name(db, printer_id)
  5570. current_name = (state.subtask_name or "").strip()
  5571. if persisted_name and current_name and persisted_name.strip() != current_name:
  5572. logger.info(
  5573. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5574. printer_id,
  5575. persisted_name,
  5576. current_name,
  5577. )
  5578. await clear_persisted_session(db, printer_id)
  5579. # Fall through to seeding: the print on the printer is real, it just
  5580. # isn't the one the row described.
  5581. persisted_log = None
  5582. else:
  5583. # Spoolman users get the tray-change log back but no in-memory
  5584. # session — see ``on_print_start`` on why that dict is load-bearing
  5585. # for the remain%-sync guard.
  5586. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5587. persisted_log = await restore_session(
  5588. db,
  5589. printer_id,
  5590. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5591. )
  5592. if persisted_log:
  5593. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5594. # Anything this process already observed goes after the persisted
  5595. # history — the log is ordered by layer, and a fresh process can
  5596. # only have seen changes from later in the print.
  5597. for entry in state.tray_change_log or []:
  5598. if tuple(entry) not in restored:
  5599. restored.append(tuple(entry))
  5600. state.tray_change_log = restored
  5601. tray_now = state.tray_now
  5602. if 0 <= tray_now <= 254:
  5603. if not state.tray_change_log:
  5604. # No persisted history — a print that started before this build,
  5605. # or before the row existed. Seed with the tray feeding right
  5606. # now so the remainder of the print is at least attributable to
  5607. # the right spool.
  5608. state.tray_change_log = [(tray_now, state.layer_num)]
  5609. logger.info(
  5610. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5611. printer_id,
  5612. tray_now,
  5613. state.layer_num,
  5614. )
  5615. # The tray handler updates ``last_loaded_tray`` on every push
  5616. # regardless of whether it logged a change, so re-align it to avoid
  5617. # a duplicate entry on the next push. Only ever with a real tray:
  5618. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5619. # 255" fallback, and writing 255 into it would defeat that.
  5620. state.last_loaded_tray = tray_now
  5621. except Exception:
  5622. # Never let attribution recovery cost the caller its timelapse
  5623. # baseline — that capture has to happen before the printer uploads
  5624. # the in-flight MP4 and there is no second chance at it.
  5625. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5626. async def on_print_running_observed(printer_id: int, data: dict):
  5627. """Restart-recovery for a print that started before Bambuddy came up.
  5628. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5629. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5630. creation). This hook restores the persisted archive into ``_active_prints``
  5631. and captures the timelapse baseline that normally hangs off print start.
  5632. Fires once per session, in lieu of on_print_start when restart-recovery
  5633. kicks in. The printer doesn't upload the timelapse until after PRINT
  5634. COMPLETE, so a baseline captured any time during the print is still
  5635. pre-upload.
  5636. """
  5637. logger = logging.getLogger(__name__)
  5638. async with async_session() as db:
  5639. from backend.app.models.printer import Printer
  5640. state = printer_manager.get_status(printer_id)
  5641. if state is not None:
  5642. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5643. if authorization is True:
  5644. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5645. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5646. await _restore_printable_objects(printer_id, state, db, logger)
  5647. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5648. printer = result.scalar_one_or_none()
  5649. if not printer:
  5650. logger.warning(
  5651. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5652. printer_id,
  5653. )
  5654. return
  5655. # Avoid double-capture: ownership reconciliation above must still run when
  5656. # a baseline already exists, but the camera work itself is one-shot.
  5657. if printer_id in _timelapse_baselines:
  5658. logger.debug(
  5659. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5660. printer_id,
  5661. )
  5662. return
  5663. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5664. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5665. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5666. against the printer's current MQTT state.
  5667. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5668. COMPLETE events, typically a print finishing during an MQTT disconnect
  5669. window followed by a smart-plug power cycle):
  5670. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5671. provably not running anymore — only branch that should fire under
  5672. normal disconnect-then-reconnect timing.
  5673. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5674. firmware mints a fresh ``subtask_id`` for each print, including the
  5675. ghost replay it runs after a power cycle from a leftover SD file —
  5676. so a mismatch unambiguously means the in-DB archive is no longer
  5677. the print on the printer.
  5678. 3. Printer is running but ``subtask_name`` is empty. The printer
  5679. doesn't know what it's running; the archive's reference to it is
  5680. already broken.
  5681. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5682. with matching subtask_id+subtask_name is left alone. The cost of a false
  5683. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5684. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5685. clears on synthesis, so the real completion creates a fresh row instead
  5686. of overwriting the synthesised one (#1679). The cost of a false negative
  5687. is the ghost-print loop in #1542.
  5688. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5689. MQTT has connected but the first ``push_status`` response hasn't been
  5690. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5691. The reconcile caller in ``on_printer_status_change`` is already gated
  5692. on a real ``state.state``, so in normal operation this branch is
  5693. unreachable; it's kept as belt-and-braces for future callers and for
  5694. the narrow window where a partial state update could arrive
  5695. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5696. ``not stale`` on degenerate input is strictly conservative: a real
  5697. stale archive will still be caught by the next push_status arriving
  5698. with terminal state.
  5699. """
  5700. current_state = (state.state or "").upper()
  5701. if current_state in ("", "UNKNOWN"):
  5702. # No real push_status yet — PrinterState defaults are not evidence.
  5703. return False, ""
  5704. if current_state in ("IDLE", "FINISH", "FAILED"):
  5705. return True, f"printer state {current_state}"
  5706. # Below here the printer is in a running / pre-running state (RUNNING /
  5707. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5708. current_subtask_id = (state.subtask_id or "").strip()
  5709. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5710. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5711. current_subtask_name = (state.subtask_name or "").strip()
  5712. if not current_subtask_name:
  5713. return True, "printer subtask_name empty"
  5714. return False, ""
  5715. async def prime_kprofile_table(printer_id: int) -> int:
  5716. """Read the printer's calibration table once per connection.
  5717. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5718. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5719. report ``cali_idx`` and nothing else -- that number can only come from
  5720. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5721. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5722. backup, or the printer answering a query BambuStudio made on the report
  5723. topic we share. A Bambuddy that nobody visited showed a card with no K
  5724. values at all.
  5725. Only the diameters actually fitted are asked for, which is one request on a
  5726. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5727. what the backup does, and it is both wasteful and the thing that used to
  5728. blank the table.
  5729. Returns the number of nozzles whose table was read.
  5730. """
  5731. client = printer_manager.get_client(printer_id)
  5732. state = printer_manager.get_status(printer_id)
  5733. if client is None or state is None or not state.connected:
  5734. return 0
  5735. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5736. # ask once, and both entries are empty until the first push_status lands.
  5737. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5738. if not diameters:
  5739. logging.getLogger(__name__).debug(
  5740. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5741. printer_id,
  5742. )
  5743. return 0
  5744. primed = 0
  5745. for diameter in diameters:
  5746. try:
  5747. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5748. except Exception as exc: # noqa: BLE001
  5749. # A printer that won't answer costs the card its K values, nothing
  5750. # more — never the connection this runs on the back of.
  5751. logging.getLogger(__name__).warning(
  5752. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5753. )
  5754. continue
  5755. primed += 1
  5756. logging.getLogger(__name__).info(
  5757. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5758. )
  5759. return primed
  5760. def _sd_files_in_use(state) -> set[str]:
  5761. """Names of the SD-card files the printer may be printing right now (#3009).
  5762. The post-print cleanup works out what to delete from the finished archive,
  5763. not from the printer. When reconciliation closes an old archive because the
  5764. printer has moved on to a new job, and that job is the same file reprinted
  5765. from the printer's screen, the cleanup would delete the file mid-print.
  5766. Empty unless the printer is busy: on an ordinary completion the state is
  5767. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  5768. name, a path or a URL depending on firmware, and some report only the
  5769. plate's G-code, so the job name is matched as well, in the same spellings
  5770. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  5771. ignores case.
  5772. """
  5773. def _text(value) -> str:
  5774. return value.strip() if isinstance(value, str) else ""
  5775. if state is None:
  5776. return set()
  5777. current_state = _text(getattr(state, "state", None)).upper()
  5778. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  5779. return set()
  5780. in_use: set[str] = set()
  5781. gcode_file = _text(getattr(state, "gcode_file", None))
  5782. if gcode_file:
  5783. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  5784. # both legal in a file name, and raises on some inputs.
  5785. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  5786. if name:
  5787. in_use.add(name.lower())
  5788. subtask_name = _text(getattr(state, "subtask_name", None))
  5789. if subtask_name:
  5790. for name in (subtask_name, subtask_name.replace(" ", "_")):
  5791. for ext in (".3mf", ".gcode"):
  5792. in_use.add(f"{name}{ext}".lower())
  5793. return in_use
  5794. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5795. """Synthesise ``on_print_complete`` for archives whose print can't be
  5796. running on the printer anymore.
  5797. Called once per MQTT (re)connection (from on_printer_status_change when
  5798. the connected edge flips False → True) and at Bambuddy startup (from
  5799. the FastAPI lifespan). Without this, a print that completes during a
  5800. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5801. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5802. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5803. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5804. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5805. closes the loop by faking the missed PRINT COMPLETE — the existing
  5806. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5807. and notifications.
  5808. Synthesised ``status="aborted"`` is the conservative label: we have no
  5809. proof the print finished successfully (and no progress evidence to
  5810. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5811. fires later, overwrites the status with the correct value.
  5812. Returns the number of archives reconciled.
  5813. """
  5814. state = printer_manager.get_status(printer_id)
  5815. if not state:
  5816. return 0
  5817. # Don't reconcile while disconnected — we'd be making a decision against
  5818. # stale cached state. The connected → reconcile edge handles this.
  5819. if not state.connected:
  5820. return 0
  5821. from backend.app.models.archive import PrintArchive
  5822. reconciled = 0
  5823. async with async_session() as db:
  5824. result = await db.execute(
  5825. select(PrintArchive).where(
  5826. PrintArchive.printer_id == printer_id,
  5827. PrintArchive.status == "printing",
  5828. )
  5829. )
  5830. active = list(result.scalars().all())
  5831. if not active:
  5832. return 0
  5833. logger = logging.getLogger(__name__)
  5834. for archive in active:
  5835. is_stale, reason = _is_active_archive_stale(archive, state)
  5836. if not is_stale:
  5837. continue
  5838. logger.info(
  5839. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5840. printer_id,
  5841. archive.id,
  5842. archive.filename,
  5843. reason,
  5844. )
  5845. # Synthesised payload: minimal fields the on_print_complete chain
  5846. # needs. `_reconciled` marker lets downstream code distinguish this
  5847. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5848. # metrics / debug logging). raw_data is the live printer state so
  5849. # the usage tracker can compare end-of-print remain% against the
  5850. # captured start values.
  5851. try:
  5852. await on_print_complete(
  5853. printer_id,
  5854. {
  5855. "status": "aborted",
  5856. "filename": archive.filename,
  5857. "subtask_name": archive.print_name or "",
  5858. "subtask_id": archive.subtask_id or "",
  5859. "raw_data": state.raw_data or {},
  5860. "_reconciled": True,
  5861. },
  5862. )
  5863. reconciled += 1
  5864. except Exception as e:
  5865. # Catch-all: a reconciliation failure must not block the
  5866. # printer's normal status flow. The archive stays in
  5867. # ``status="printing"`` and the next reconnect retries.
  5868. logger.warning(
  5869. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5870. archive.id,
  5871. e,
  5872. )
  5873. return reconciled
  5874. # #2547: clearance left between the nozzle and the top of the print when the
  5875. # plate is commanded back into camera framing. The nozzle is parked away from
  5876. # the part by then, so this is belt-and-braces against a max_z_height that
  5877. # under-reports (e.g. a slicer that excludes a final Z hop).
  5878. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5879. # How far below the restored position to drop the plate again afterwards, so
  5880. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5881. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5882. # on machines with less headroom.
  5883. _PLATE_PARK_DROP_MM = 100.0
  5884. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5885. # this axis, so it is a proven-safe speed for the full travel.
  5886. _PLATE_RESTORE_FEEDRATE = 600
  5887. # Time allowed for the plate to reach the restored position before the camera
  5888. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5889. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5890. # How long `_background_finish_photo` waits for this producer. Must cover the
  5891. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5892. # notification path's own photo wait so a slow producer degrades to a
  5893. # photo-less notification rather than a missed one. The chamber light's
  5894. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  5895. # camera_light.MAX_DELAY_SECONDS stays below it.
  5896. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5897. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  5898. """The ``_active_prints`` keys a finished print may be registered under.
  5899. Matching how they were registered in on_print_start. Shared by
  5900. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  5901. to find the same binding.
  5902. """
  5903. possible_keys = []
  5904. # Try subtask_name variations first (most reliable for matching)
  5905. if subtask_name:
  5906. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5907. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5908. possible_keys.append((printer_id, subtask_name))
  5909. # Try filename variations
  5910. if filename:
  5911. # Extract just the filename if it's a path
  5912. fname = filename.split("/")[-1] if "/" in filename else filename
  5913. if fname.endswith(".3mf"):
  5914. possible_keys.append((printer_id, fname))
  5915. elif fname.endswith(".gcode"):
  5916. base_name = fname.rsplit(".", 1)[0]
  5917. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5918. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5919. possible_keys.append((printer_id, fname))
  5920. else:
  5921. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5922. possible_keys.append((printer_id, f"{fname}.3mf"))
  5923. possible_keys.append((printer_id, fname))
  5924. # Also try full path versions
  5925. if filename.endswith(".3mf"):
  5926. possible_keys.append((printer_id, filename))
  5927. elif filename.endswith(".gcode"):
  5928. base_name = filename.rsplit(".", 1)[0]
  5929. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5930. possible_keys.append((printer_id, filename))
  5931. else:
  5932. possible_keys.append((printer_id, f"{filename}.3mf"))
  5933. possible_keys.append((printer_id, filename))
  5934. return possible_keys
  5935. def _archive_name_forms(archive) -> set[str]:
  5936. """The names an archive could be echoed back as, in normalised form (#3240).
  5937. Its print name, and its filename with and without the 3MF extension.
  5938. """
  5939. forms = set()
  5940. if archive.print_name:
  5941. forms.add(_normalise_subtask_name(archive.print_name))
  5942. if archive.filename:
  5943. forms.add(_normalise_subtask_name(archive.filename))
  5944. for suffix in (".gcode.3mf", ".3mf"):
  5945. if archive.filename.lower().endswith(suffix):
  5946. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  5947. forms.discard("")
  5948. return forms
  5949. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  5950. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  5951. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  5952. from the plate recorded when the job was dispatched. Neither is touched:
  5953. ``on_print_complete`` pops both, which is why the finish-photo producer
  5954. calls this before its first await, while they are still there.
  5955. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  5956. archive, or that it only knows by a name -- and on any error: the producer
  5957. calls this before the ``try`` that always releases the photo consumer, so
  5958. it must not raise.
  5959. """
  5960. try:
  5961. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  5962. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  5963. if archive_id is None:
  5964. return None, None
  5965. return archive_id, _print_plate_ids.get(archive_id)
  5966. except Exception:
  5967. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  5968. return None, None
  5969. async def _max_z_for_current_print(
  5970. printer_id: int,
  5971. data: dict,
  5972. logger,
  5973. archive_id: int | None,
  5974. plate_id: int | None = None,
  5975. ) -> float | None:
  5976. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5977. This number becomes the target of a real Z move, so every step here refuses
  5978. rather than guesses. A height belonging to some *other* print is the one
  5979. failure that could drive the nozzle into the model: 20 mm carried onto a
  5980. 200 mm print would command the plate up through the part.
  5981. Three independent things therefore have to agree before a height is
  5982. returned:
  5983. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  5984. when it started (see ``_bound_print``), never one found by name. A name
  5985. is not an identity: every plate of a multi-plate file shares one, and a
  5986. reprint reuses its archive row, so the newest archive with the right
  5987. name can be another plate of the same file. Support bundles show the
  5988. old name lookup doing exactly that (archive 288 for a print bound to
  5989. 169, 313 layers against 125), stopped only by the layer check below.
  5990. No binding, no move.
  5991. 2. **Identity.** The bound archive's name still has to be the finished
  5992. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  5993. because the printer echoes spaces as underscores (#3240). Exact: not a
  5994. substring, and not the completion check's tolerance for a truncated
  5995. echo.
  5996. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5997. match the layer count the printer itself reported over MQTT for the print
  5998. that just ended. These come from genuinely different sources, so a
  5999. mismatch means the row is not this print, whatever its name says.
  6000. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6001. plate of a multi-plate file reuses the archive row without updating its
  6002. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6003. ``on_print_complete`` may already have flipped the status by the time we
  6004. run.
  6005. """
  6006. subtask_name = (data.get("subtask_name") or "").strip()
  6007. if not subtask_name:
  6008. # Nothing to identify the print by — refuse rather than fall back to
  6009. # "whatever ran last on this printer".
  6010. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6011. return None
  6012. if archive_id is None:
  6013. logger.info(
  6014. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6015. printer_id,
  6016. subtask_name,
  6017. )
  6018. return None
  6019. try:
  6020. from backend.app.models.archive import PrintArchive
  6021. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6022. async with async_session() as db:
  6023. result = await db.execute(
  6024. select(PrintArchive).where(
  6025. PrintArchive.id == archive_id,
  6026. PrintArchive.printer_id == printer_id,
  6027. PrintArchive.status.in_(("printing", "completed")),
  6028. PrintArchive.deleted_at.is_(None),
  6029. )
  6030. )
  6031. archive = result.scalar_one_or_none()
  6032. if archive is None or not archive.file_path:
  6033. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6034. return None
  6035. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6036. logger.warning(
  6037. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6038. printer_id,
  6039. archive_id,
  6040. subtask_name,
  6041. )
  6042. return None
  6043. client = printer_manager.get_client(printer_id)
  6044. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6045. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6046. logger.warning(
  6047. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6048. "— refusing to move the plate on a height that may not be this print's",
  6049. printer_id,
  6050. archive.id,
  6051. archive.total_layers,
  6052. reported_layers,
  6053. )
  6054. return None
  6055. # Stored relative to the data directory, like every other archive path
  6056. # (#3240: this read a `data_dir` setting that does not exist).
  6057. path = app_settings.base_dir / archive.file_path
  6058. plate = plate_id or archive.plate_id or 1
  6059. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6060. except Exception as e:
  6061. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6062. return None
  6063. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6064. """Raise the plate back into camera framing before the finish photo (#2547).
  6065. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6066. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6067. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6068. This commands an absolute ``G1 Z`` back to just above the last printed
  6069. layer.
  6070. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6071. clearance`` is a height the toolhead was physically at seconds earlier, so
  6072. it is inside the travel limits by construction and leaves the nozzle above
  6073. the part. It is also unambiguous across model families: Z is the
  6074. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6075. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6076. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6077. (#2579).
  6078. Returns True if the move was sent and waited out, False if it was skipped.
  6079. """
  6080. client = printer_manager.get_client(printer_id)
  6081. if client is None:
  6082. return False
  6083. # Re-read state immediately before commanding motion. If the queue has
  6084. # already started the next print, the printer is no longer ours to move.
  6085. state = getattr(client, "state", None)
  6086. if state is None or state.state != "FINISH":
  6087. logger.info(
  6088. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6089. printer_id,
  6090. getattr(state, "state", "unknown"),
  6091. )
  6092. return False
  6093. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6094. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6095. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6096. return False
  6097. logger.info(
  6098. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6099. printer_id,
  6100. target_z,
  6101. max_z_height,
  6102. _PLATE_RESTORE_CLEARANCE_MM,
  6103. _PLATE_RESTORE_SETTLE_SECONDS,
  6104. )
  6105. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6106. return True
  6107. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6108. """Drop the plate again after the finish photo (#2547).
  6109. Without this the user walks up to a finished print sitting just under the
  6110. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6111. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6112. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6113. print homes anyway.
  6114. """
  6115. client = printer_manager.get_client(printer_id)
  6116. state = getattr(client, "state", None) if client else None
  6117. if client is None or state is None or state.state != "FINISH":
  6118. return
  6119. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6120. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6121. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6122. """True if a queue item is about to take this printer (#2547).
  6123. The scheduler dispatches the next job the moment a print completes, and a
  6124. plate move interleaved with a print start is not a race worth having. The
  6125. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6126. this window; this closes the head of it.
  6127. """
  6128. try:
  6129. from backend.app.models.print_queue import PrintQueueItem
  6130. async with async_session() as db:
  6131. result = await db.execute(
  6132. select(PrintQueueItem.id)
  6133. .where(
  6134. PrintQueueItem.printer_id == printer_id,
  6135. PrintQueueItem.status.in_(("pending", "printing")),
  6136. )
  6137. .limit(1)
  6138. )
  6139. return result.scalar_one_or_none() is not None
  6140. except Exception as e:
  6141. # Fail closed: if we can't tell, don't move the plate.
  6142. logging.getLogger(__name__).debug(
  6143. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6144. )
  6145. return True
  6146. async def on_finish_photo_moment(printer_id: int, data: dict):
  6147. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6148. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6149. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6150. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6151. HMS halt, firmware variants). Grabs one frame via the same
  6152. external-camera / RTSP path the post-completion fallback uses, stores
  6153. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6154. ``_background_finish_photo`` consume the cached bytes when it runs.
  6155. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6156. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6157. set to Smooth (#1721). No force-on now means the user's explicit
  6158. timelapse=off in the slicer send dialog is respected.
  6159. """
  6160. logger = logging.getLogger(__name__)
  6161. trigger = data.get("trigger", "unknown")
  6162. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6163. logger.info(
  6164. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6165. printer_id,
  6166. trigger,
  6167. timelapse_was_active,
  6168. )
  6169. # If a timelapse is actively recording, skip the pre-capture — the
  6170. # post-completion path will extract the last frame from the recorded
  6171. # video, which still provides the best framing (toolhead parked,
  6172. # before bed drop) without the per-layer parking side effects.
  6173. if timelapse_was_active:
  6174. logger.info(
  6175. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6176. printer_id,
  6177. )
  6178. return
  6179. # #1790: register the producer-done event BEFORE the first await so the
  6180. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6181. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6182. # The `finally` below guarantees `set()` runs on every exit, including
  6183. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6184. producer_done = asyncio.Event()
  6185. _stage22_finish_in_flight[printer_id] = producer_done
  6186. # #3240: also before the first await. On the FINISH-state path
  6187. # `on_print_complete` is dispatched right behind us and pops both the
  6188. # print's archive binding and its plate; read here, they are still there.
  6189. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6190. # #2547: set once the plate has actually been raised, and read by the
  6191. # `finally` below. Declared out here so a failure anywhere after the move —
  6192. # a camera timeout, a DB error — still lowers the plate again.
  6193. restore_max_z: float | None = None
  6194. try:
  6195. async with async_session() as db:
  6196. from backend.app.api.routes.settings import get_setting
  6197. from backend.app.models.printer import Printer
  6198. capture_setting = await get_setting(db, "capture_finish_photo")
  6199. if capture_setting is not None and capture_setting.lower() != "true":
  6200. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6201. return
  6202. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6203. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6204. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6205. printer = result.scalar_one_or_none()
  6206. if printer is None:
  6207. logger.warning(
  6208. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6209. printer_id,
  6210. )
  6211. return
  6212. frame_bytes: bytes | None = None
  6213. # #2708: the banked frame arrives already rotated — it comes from
  6214. # `_capture_snapshot_for_notification`, which rotates before returning.
  6215. # Every other source below is a raw grab. Tracking which lets us store
  6216. # exactly one rotation in `_stage22_finish_frames` either way.
  6217. frame_already_rotated = False
  6218. # On the FINISH-state path the End G-code has already run, and two very
  6219. # different situations arrive here needing opposite answers.
  6220. #
  6221. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6222. # snippet may have ejected the plate — the scene in front of the camera
  6223. # is no longer the finished print, and no amount of moving the plate
  6224. # brings it back. Use the banked in-print frame instead.
  6225. #
  6226. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6227. # than the camera frames well, and the toolhead is parked out of the
  6228. # way. That is the *best* moment available on firmware that never emits
  6229. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6230. # back. Preferring the bank here unconditionally, as this code used to,
  6231. # is what shipped a mid-print photo with the toolhead over the part.
  6232. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6233. banked = _inprint_frame_bank.get(printer_id)
  6234. if banked:
  6235. frame_bytes = banked
  6236. frame_already_rotated = True
  6237. logger.info(
  6238. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6239. "frame (%d bytes) instead of a post-swap live grab",
  6240. len(banked),
  6241. )
  6242. else:
  6243. logger.warning(
  6244. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6245. "in-print bank is empty — falling back to a live grab, which may show a "
  6246. "swapped or empty plate",
  6247. printer_id,
  6248. )
  6249. # `restore_max_z` is set only once the plate is actually up, because the
  6250. # `finally` reads it to decide whether it owes a move back down.
  6251. #
  6252. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6253. # came up empty above: that machine may have just ejected its plate, and
  6254. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6255. # taking for a photo of a bed we already know may be bare.
  6256. if (
  6257. frame_bytes is None
  6258. and trigger == "finish_state"
  6259. and restore_plate_enabled
  6260. and not print_dispatch_context.end_gcode_injected(printer_id)
  6261. ):
  6262. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6263. if wants_restore is None:
  6264. logger.info(
  6265. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6266. printer_id,
  6267. )
  6268. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6269. logger.info(
  6270. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6271. printer_id,
  6272. )
  6273. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6274. restore_max_z = wants_restore
  6275. # Chamber light for the live capture below (#1655). The banked frame
  6276. # above was taken without it, like every in-print bank.
  6277. async with camera_light(printer if frame_bytes is None else None):
  6278. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6279. from backend.app.api.routes.camera import live_frame_for_capture
  6280. from backend.app.services.external_camera import capture_frame
  6281. # #2707: this used to collide with the live view and fail, which is
  6282. # how finish-photo notifications went out with no image attached.
  6283. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6284. defer, buffered = live_frame_for_capture(printer_id)
  6285. if defer:
  6286. frame_bytes = buffered
  6287. else:
  6288. frame_bytes = await capture_frame(
  6289. printer.external_camera_url,
  6290. printer.external_camera_type or "mjpeg",
  6291. snapshot_url=printer.external_camera_snapshot_url,
  6292. )
  6293. if frame_bytes:
  6294. logger.info(
  6295. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6296. len(frame_bytes),
  6297. )
  6298. elif frame_bytes is None:
  6299. from backend.app.api.routes.camera import get_buffered_frame
  6300. buffered = get_buffered_frame(printer_id)
  6301. if buffered:
  6302. frame_bytes = buffered
  6303. logger.info(
  6304. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6305. len(frame_bytes),
  6306. )
  6307. else:
  6308. from backend.app.services.camera import capture_camera_frame_bytes
  6309. frame_bytes = await capture_camera_frame_bytes(
  6310. ip_address=printer.ip_address,
  6311. access_code=printer.access_code,
  6312. model=printer.model,
  6313. timeout=15,
  6314. )
  6315. if frame_bytes:
  6316. logger.info(
  6317. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6318. len(frame_bytes),
  6319. )
  6320. if frame_bytes:
  6321. if not frame_already_rotated:
  6322. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6323. _stage22_finish_frames[printer_id] = frame_bytes
  6324. else:
  6325. logger.warning(
  6326. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6327. printer_id,
  6328. )
  6329. except Exception as e:
  6330. logger.warning(
  6331. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6332. printer_id,
  6333. e,
  6334. )
  6335. finally:
  6336. # #2547: we raised the plate, so we own lowering it — including when the
  6337. # capture above failed or threw partway through.
  6338. if restore_max_z is not None:
  6339. try:
  6340. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6341. except Exception as e:
  6342. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6343. # #1790: always unblock the consumer's bounded wait — whether we stored
  6344. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6345. # dict entry by the consumer doesn't affect signalling.
  6346. producer_done.set()
  6347. def _subtask_name_from_filename(filename: str) -> str:
  6348. """Recover the subtask name a print command would have carried for *filename*.
  6349. The dispatcher derives the printer-facing subtask name from the archive's
  6350. file name, so stripping the extensions back off gives the value MQTT echoes
  6351. on completion. Only the two extensions Bambuddy actually stores are removed,
  6352. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6353. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6354. """
  6355. name = PurePosixPath(filename).name
  6356. for suffix in (".3mf", ".gcode"):
  6357. if name.lower().endswith(suffix):
  6358. name = name[: -len(suffix)]
  6359. return name
  6360. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6361. """Whether the subtask name is the printed 3MF's own file name.
  6362. A print started from the printer's screen reports the same full name, with
  6363. its extension, as both subtask and file (#3009). A dispatched print reports
  6364. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6365. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6366. """
  6367. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6368. return False
  6369. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6370. # How the printer marks a subtask name it had to cut short. Observed on real
  6371. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6372. # (a name with multibyte characters came back at 98), so match the marker
  6373. # rather than a length.
  6374. _SUBTASK_TRUNCATION_MARKER = "..."
  6375. def _normalise_subtask_name(name: str) -> str:
  6376. """Canonical form for comparing a dispatched name against MQTT's echo.
  6377. The printer does not echo the name back verbatim: it substitutes
  6378. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6379. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6380. The 3MF lookup in this module has always known that -- it builds
  6381. space-to-underscore variants of every candidate filename, and its
  6382. directory search normalises both sides before comparing. This exists so
  6383. the completion check reads the same rule from the same place instead of
  6384. growing its own, which is exactly how it came to disagree (#2829).
  6385. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6386. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6387. are dropped after the substitution so both sides agree (#3241).
  6388. """
  6389. return name.strip().replace(" ", "_").strip("_").casefold()
  6390. def _subtask_names_match(expected: str, observed: str) -> bool:
  6391. """Whether two subtask names describe the same print.
  6392. Beyond the space/underscore substitution, the printer truncates long names
  6393. and marks the cut with ``...``. A truncated echo has to count as a match or
  6394. every print with a long name strands its queue item the same way.
  6395. """
  6396. expected_n = _normalise_subtask_name(expected)
  6397. observed_n = _normalise_subtask_name(observed)
  6398. if expected_n == observed_n:
  6399. return True
  6400. # Either side can be the truncated one: the printer truncates what it
  6401. # echoes, and an archive whose own filename was recorded from a previous
  6402. # truncated echo carries the marker too.
  6403. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6404. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6405. continue
  6406. # The full side has lost its edge underscores; a cut that lands right
  6407. # after one keeps it, so drop it here too (#3241). Nothing left before
  6408. # the marker is no evidence of anything, and must not match every name.
  6409. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6410. if kept and full.startswith(kept):
  6411. return True
  6412. return False
  6413. async def _queue_item_dispatched_name(db, item) -> str:
  6414. """The subtask name *item* was dispatched under, or "" when unknowable.
  6415. A row with no archive, or an archive with no file name, is unverifiable
  6416. rather than wrong; every caller answers that with its permissive branch.
  6417. """
  6418. if item.archive_id is None:
  6419. return ""
  6420. from backend.app.models.archive import PrintArchive
  6421. archive = await db.get(PrintArchive, item.archive_id)
  6422. if archive is None or not archive.filename:
  6423. return ""
  6424. return _subtask_name_from_filename(archive.filename)
  6425. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6426. """Whether this completion event is plausibly about *item*'s print.
  6427. The caller finds its queue row by printer and ``status='printing'`` alone,
  6428. which is all a completion event gives it -- there is no run identifier in
  6429. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6430. completion delivered for this printer closes whichever row happens to be
  6431. printing, however unrelated. Comparing the subtask name against the archive
  6432. the row was dispatched with costs one primary-key load and rules that out.
  6433. Deliberately permissive: it answers False only on a positive disagreement
  6434. between two names we actually have. A row with no archive, an archive with
  6435. no file name, or an event with no subtask name is unverifiable rather than
  6436. wrong, and refusing those would strand the item in ``printing`` and wedge
  6437. the printer's queue -- a worse failure than the one being prevented.
  6438. """
  6439. observed = (data.get("subtask_name") or "").strip()
  6440. if not observed or item.archive_id is None:
  6441. return True
  6442. from backend.app.models.archive import PrintArchive
  6443. archive = await db.get(PrintArchive, item.archive_id)
  6444. if archive is None or not archive.filename:
  6445. return True
  6446. expected = _subtask_name_from_filename(archive.filename)
  6447. if not expected or _subtask_names_match(expected, observed):
  6448. return True
  6449. logging.getLogger(__name__).warning(
  6450. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6451. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6452. "printing rather than closing a run this event is not about.",
  6453. item.id,
  6454. expected,
  6455. archive.id,
  6456. archive.filename,
  6457. observed,
  6458. )
  6459. return False
  6460. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6461. """Spend the 3MF download cache on a still-empty fallback archive.
  6462. ``on_print_complete`` drops the cache as its first act, which deletes the
  6463. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6464. print ran and the archive never got one, this is the last moment those bytes
  6465. exist (#2957).
  6466. """
  6467. logger = logging.getLogger(__name__)
  6468. names = [
  6469. n
  6470. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6471. if n
  6472. ]
  6473. for name in names:
  6474. try:
  6475. cached = get_cached_3mf(printer_id, name)
  6476. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6477. return
  6478. except Exception as e:
  6479. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6480. async def _cleanup_sd_card_after_print(
  6481. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6482. ) -> None:
  6483. """Delete a finished print's file from the printer's SD card."""
  6484. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6485. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6486. # auto-start files found in root on power cycle, causing ghost prints.
  6487. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6488. try:
  6489. if subtask_name:
  6490. archive_filename: str | None = None
  6491. async with async_session() as db:
  6492. from backend.app.models.archive import PrintArchive
  6493. from backend.app.models.printer import Printer
  6494. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6495. printer = result.scalar_one_or_none()
  6496. if archive_id:
  6497. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6498. archive_filename = archive_row.scalar_one_or_none()
  6499. if printer:
  6500. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6501. from backend.app.utils.filename import derive_remote_filename
  6502. # Primary candidate: the exact path the dispatcher uploaded to
  6503. # (derived from archive.filename via the same rule as upload).
  6504. # Without it, a library row that ended up with a doubled
  6505. # .gcode.3mf (#1542) leaves the real file behind because the
  6506. # subtask_name + ext fallbacks below don't match what's on the
  6507. # SD card. Fallbacks remain for archive-less prints (subtask
  6508. # never resolved to an archive) and for older naming variants.
  6509. candidate_paths: list[str] = []
  6510. if archive_filename:
  6511. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6512. for ext in (".3mf", ".gcode"):
  6513. fallback = f"/{subtask_name}{ext}"
  6514. if fallback not in candidate_paths:
  6515. candidate_paths.append(fallback)
  6516. # Three outcomes track across all candidates so the final log
  6517. # line reflects what actually happened. The A1 in #1721 always
  6518. # ends here with ``any_not_found=True`` and the others False
  6519. # — its firmware auto-cleans the SD card before our cleanup
  6520. # runs, every candidate FTP-DELE returns 550, and the old
  6521. # code burned 3 retries × 2 s × 3 candidates per print
  6522. # logging a misleading "may linger" WARNING on a successful
  6523. # print.
  6524. any_deleted = False
  6525. any_real_failure = False
  6526. any_not_found = False
  6527. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6528. for remote_path in candidate_paths:
  6529. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6530. logger.info(
  6531. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6532. remote_path,
  6533. printer.name,
  6534. )
  6535. continue
  6536. # Retry only the FAILED case — 550 NOT_FOUND will never
  6537. # recover by waiting, so a "file isn't here" answer
  6538. # advances immediately to the next candidate without
  6539. # consuming the retry budget.
  6540. for attempt in range(1, 4):
  6541. try:
  6542. delete_result = await delete_file_async(
  6543. printer.ip_address,
  6544. printer.access_code,
  6545. remote_path,
  6546. printer_model=printer.model,
  6547. )
  6548. except Exception as e:
  6549. delete_result = DeleteResult.FAILED
  6550. logger.warning(
  6551. "SD card cleanup attempt %d/3 raised for %s: %s",
  6552. attempt,
  6553. remote_path,
  6554. e,
  6555. )
  6556. if delete_result == DeleteResult.DELETED:
  6557. any_deleted = True
  6558. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6559. break
  6560. if delete_result == DeleteResult.NOT_FOUND:
  6561. any_not_found = True
  6562. break # 550 will not recover; try next candidate
  6563. # FAILED: real error — retry with backoff, then give up
  6564. if attempt < 3:
  6565. await asyncio.sleep(2)
  6566. else:
  6567. any_real_failure = True
  6568. logger.warning(
  6569. "SD card cleanup failed after 3 attempts for %s "
  6570. "(network/auth/transient error — file may linger on SD card)",
  6571. remote_path,
  6572. )
  6573. if not any_deleted and not any_real_failure and any_not_found:
  6574. # Every candidate said "not here." Either the printer
  6575. # firmware swept the SD card itself (common on A1) or the
  6576. # dispatcher's upload path doesn't match our candidate
  6577. # rule. Either way: nothing to clean up, no warning.
  6578. logger.debug(
  6579. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6580. "(printer likely self-cleaned)",
  6581. printer.name,
  6582. )
  6583. except Exception as e:
  6584. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6585. async def on_print_complete(printer_id: int, data: dict):
  6586. """Handle print completion - update the archive status."""
  6587. import time
  6588. logger = logging.getLogger(__name__)
  6589. start_time = time.time()
  6590. def log_timing(section: str):
  6591. elapsed = time.time() - start_time
  6592. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6593. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6594. # A kill-switch stop sends its provider notification immediately. Keep the
  6595. # task so the later notification path can await it and avoid a duplicate;
  6596. # if that immediate attempt failed, the regular completion path retries.
  6597. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6598. # Last chance before the bytes go: if this print's archive is still an empty
  6599. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6600. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6601. # below deletes the file (#2957).
  6602. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6603. # A pending cool-off retry has nothing left to recover for — the cache is
  6604. # about to be dropped and the print is over.
  6605. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6606. if retry_task and not retry_task.done():
  6607. retry_task.cancel()
  6608. # Drop the 3MF download cache for this printer (#972). The print is over,
  6609. # nothing else legitimately needs the bytes; keeping them would only risk
  6610. # handing a stale file to the next print if it reuses the same name.
  6611. clear_3mf_cache(printer_id)
  6612. try:
  6613. ws_data = {
  6614. "status": data.get("status"),
  6615. "filename": data.get("filename"),
  6616. "subtask_name": data.get("subtask_name"),
  6617. "timelapse_was_active": data.get("timelapse_was_active"),
  6618. }
  6619. await ws_manager.send_print_complete(printer_id, ws_data)
  6620. log_timing("WebSocket send_print_complete")
  6621. except Exception as e:
  6622. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6623. # Capture user info before clearing (needed for print log entry)
  6624. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6625. # Clear current print user tracking (Issue #206)
  6626. printer_manager.clear_current_print_user(printer_id)
  6627. # If the user explicitly stopped this print from the queue UI the printer will
  6628. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6629. # correct "print stopped" notification/email is sent instead of a failure alert.
  6630. _raw_status = data.get("status", "completed")
  6631. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6632. logger.info(
  6633. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6634. _raw_status,
  6635. printer_id,
  6636. )
  6637. data = {**data, "status": "cancelled"}
  6638. _user_stopped_printers.discard(printer_id)
  6639. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6640. # may have left material on the bed: a user can cancel ten hours into a
  6641. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6642. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6643. # `_user_stopped_printers` is only populated when the user stops via the
  6644. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6645. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6646. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6647. # Auto Off power cycles and Bambuddy restarts.
  6648. try:
  6649. notify_live_activities.print_finished(printer_id, data)
  6650. except Exception:
  6651. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  6652. _final_status = data.get("status", "completed")
  6653. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6654. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6655. # MQTT relay - publish print complete
  6656. try:
  6657. printer_info = printer_manager.get_printer(printer_id)
  6658. if printer_info:
  6659. await mqtt_relay.on_print_complete(
  6660. printer_id,
  6661. printer_info.name,
  6662. printer_info.serial_number,
  6663. data.get("filename", ""),
  6664. data.get("subtask_name", ""),
  6665. data.get("status", "completed"),
  6666. )
  6667. except Exception:
  6668. pass # Don't fail print complete callback if MQTT fails
  6669. filename = data.get("filename", "")
  6670. subtask_name = data.get("subtask_name", "")
  6671. if not filename and not subtask_name:
  6672. logger.warning("Print complete without filename or subtask_name")
  6673. return
  6674. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6675. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6676. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6677. # Find the archive for this print
  6678. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6679. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6680. archive_id = None
  6681. for key in possible_keys:
  6682. archive_id = _active_prints.pop(key, None)
  6683. if archive_id:
  6684. logger.info("Found archive %s with key %s", archive_id, key)
  6685. # Also clean up any other keys pointing to this archive
  6686. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6687. for k in keys_to_remove:
  6688. _active_prints.pop(k, None)
  6689. break
  6690. # The archive bound when the print started, before the name search below.
  6691. # Only this one may give the finish-photo plate restore a height (#3240):
  6692. # the search matches names by substring.
  6693. bound_archive_id = archive_id
  6694. if not archive_id:
  6695. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6696. async with async_session() as db:
  6697. from backend.app.models.archive import PrintArchive
  6698. # Try matching by subtask_name (stored as print_name) first
  6699. if subtask_name:
  6700. result = await db.execute(
  6701. select(PrintArchive)
  6702. .where(PrintArchive.printer_id == printer_id)
  6703. .where(PrintArchive.status == "printing")
  6704. .where(
  6705. or_(
  6706. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6707. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6708. )
  6709. )
  6710. .order_by(PrintArchive.created_at.desc())
  6711. .limit(1)
  6712. )
  6713. archive = result.scalar_one_or_none()
  6714. if archive:
  6715. archive_id = archive.id
  6716. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6717. # Also try by filename
  6718. if not archive_id and filename:
  6719. result = await db.execute(
  6720. select(PrintArchive)
  6721. .where(PrintArchive.printer_id == printer_id)
  6722. .where(PrintArchive.filename == filename)
  6723. .where(PrintArchive.status == "printing")
  6724. .order_by(PrintArchive.created_at.desc())
  6725. .limit(1)
  6726. )
  6727. archive = result.scalar_one_or_none()
  6728. if archive:
  6729. archive_id = archive.id
  6730. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6731. log_timing("SD card cleanup")
  6732. # Update queue item status early — must run before the archive_id early-return
  6733. # so queue items don't get stuck in "printing" when archive lookup fails.
  6734. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6735. queue_item_id = None
  6736. billing_run_id: str | None = None
  6737. billing_user_id: int | None = None
  6738. billing_cost_center_id: int | None = None
  6739. billing_plate_id: int | None = None
  6740. queue_status = None
  6741. queue_auto_off = False
  6742. try:
  6743. from backend.app.core.database import run_with_retry
  6744. from backend.app.models.print_queue import PrintQueueItem
  6745. async def _update_queue_status(db):
  6746. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6747. nonlocal queue_item_id, queue_status, queue_auto_off
  6748. result = await db.execute(
  6749. select(PrintQueueItem)
  6750. .where(PrintQueueItem.printer_id == printer_id)
  6751. .where(PrintQueueItem.status == "printing")
  6752. )
  6753. printing_items = list(result.scalars().all())
  6754. if len(printing_items) > 1:
  6755. logger.warning(
  6756. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6757. printer_id,
  6758. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6759. )
  6760. item = printing_items[0] if printing_items else None
  6761. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6762. return
  6763. if item:
  6764. queue_status = data.get("status", "completed")
  6765. # MQTT sends "aborted" for cancelled prints; normalise to
  6766. # "cancelled" so it matches the queue schema Literal.
  6767. if queue_status == "aborted":
  6768. queue_status = "cancelled"
  6769. item.status = queue_status
  6770. item.completed_at = datetime.now(timezone.utc)
  6771. if queue_status == "failed" and not item.error_message:
  6772. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6773. # Bump usage counters on the source library file so admins can
  6774. # sort by "last printed" and (eventually) auto-purge stale
  6775. # files — #1008.
  6776. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6777. await db.commit()
  6778. queue_item_id = item.id
  6779. billing_run_id = item.billing_run_id
  6780. billing_user_id = item.created_by_id
  6781. billing_cost_center_id = item.cost_center_id
  6782. billing_plate_id = item.plate_id
  6783. queue_auto_off = item.auto_off_after
  6784. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6785. await run_with_retry(_update_queue_status, label="queue status update")
  6786. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6787. # their own sessions and have their own error handling — no retry needed.
  6788. if queue_item_id is not None:
  6789. # Batch orders (#342): this run may have been the last one an order
  6790. # owed. Re-evaluate here rather than lazily on read, so a finished
  6791. # order reports itself complete without someone opening the page.
  6792. try:
  6793. from backend.app.services.print_batch import refresh_batch_status_for_item
  6794. async with async_session() as db:
  6795. await refresh_batch_status_for_item(db, queue_item_id)
  6796. await db.commit()
  6797. except Exception as e:
  6798. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6799. # MQTT relay - publish queue job completed
  6800. try:
  6801. printer_info = printer_manager.get_printer(printer_id)
  6802. await mqtt_relay.on_queue_job_completed(
  6803. job_id=queue_item_id,
  6804. filename=filename or subtask_name,
  6805. printer_id=printer_id,
  6806. printer_name=printer_info.name if printer_info else "Unknown",
  6807. status=queue_status,
  6808. )
  6809. except Exception:
  6810. pass # Don't fail if MQTT fails
  6811. # Check if queue is now empty and send notification
  6812. try:
  6813. from sqlalchemy import func as sa_func
  6814. async with async_session() as db:
  6815. count_result = await db.execute(
  6816. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6817. )
  6818. pending_count = count_result.scalar() or 0
  6819. if pending_count == 0:
  6820. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6821. completed_result = await db.execute(
  6822. select(sa_func.count(PrintQueueItem.id)).where(
  6823. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6824. PrintQueueItem.completed_at >= today_start,
  6825. )
  6826. )
  6827. completed_count = completed_result.scalar() or 1
  6828. await notification_service.on_queue_completed(
  6829. completed_count=completed_count,
  6830. db=db,
  6831. )
  6832. except Exception:
  6833. pass # Don't fail if notification fails
  6834. # Handle auto_off_after - power off printer if the queue item opted
  6835. # in. Delegates to the smart-plug manager so the off honours each
  6836. # plug's configured strategy (time delay or temperature threshold),
  6837. # is cancelled if the printer starts printing again, and never cuts
  6838. # power on a loaded print (#1890). Previously an inline block here
  6839. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6840. # timeout regardless of print state — cutting a touchscreen reprint.
  6841. if queue_auto_off:
  6842. try:
  6843. async with async_session() as db:
  6844. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6845. except Exception as e:
  6846. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6847. except Exception as e:
  6848. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6849. log_timing("Queue item update")
  6850. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6851. # Must run before archive_id early-return so it fires for all prints (including
  6852. # prints started from BambuStudio/touchscreen that have no archive).
  6853. if data.get("status") == "completed":
  6854. try:
  6855. from backend.app.api.routes.settings import get_setting
  6856. async with async_session() as db:
  6857. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6858. threshold = float(threshold_str) if threshold_str else 35.0
  6859. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6860. async with async_session() as db:
  6861. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6862. if providers:
  6863. _bed_cool_waiters[printer_id] = {
  6864. "threshold": threshold,
  6865. "filename": filename or subtask_name or "",
  6866. "registered_at": time.time(),
  6867. }
  6868. logger.info(
  6869. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6870. printer_id,
  6871. threshold,
  6872. )
  6873. else:
  6874. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6875. except Exception as e:
  6876. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6877. # Capture the slicer estimate before usage tracking runs. The tracker may
  6878. # update archive.cost with this run's measured cost; billing partial runs
  6879. # against that already-partial value would discount the charge twice.
  6880. billing_planned_grams: float | None = None
  6881. billing_base_cost: float | None = None
  6882. if archive_id:
  6883. try:
  6884. async with async_session() as db:
  6885. from backend.app.models.archive import PrintArchive
  6886. billing_archive = await db.get(PrintArchive, archive_id)
  6887. if billing_archive:
  6888. billing_path = (
  6889. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6890. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6891. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6892. billing_archive,
  6893. billing_path,
  6894. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6895. )
  6896. except Exception as e:
  6897. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6898. # --- Track filament consumption (must run before archive_id early-return so usage
  6899. # is recorded even when auto-archive is disabled) ---
  6900. usage_results: list[dict] = []
  6901. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6902. stored_ams_mapping = data.get("ams_mapping")
  6903. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6904. if not stored_ams_mapping and archive_id:
  6905. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6906. # Always drain the plate_id register on completion — the session already
  6907. # consumed it at print-start injection; leaving it would leak into the next
  6908. # print on the same archive_id (rare but possible with reprints) (#1697).
  6909. # Capture the popped value so the completion notification can scope the
  6910. # archive-level (summed-across-plates per #1593) filament + time totals
  6911. # down to the single plate that was actually printed (#1785).
  6912. notify_plate_id: int | None = None
  6913. if archive_id:
  6914. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6915. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6916. try:
  6917. async with async_session() as db:
  6918. from backend.app.api.routes.settings import get_setting
  6919. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6920. if not _spoolman_on or _spoolman_on.lower() != "true":
  6921. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6922. async with async_session() as db:
  6923. usage_results = await usage_on_print_complete(
  6924. printer_id,
  6925. data,
  6926. printer_manager,
  6927. db,
  6928. archive_id=archive_id,
  6929. ams_mapping=stored_ams_mapping,
  6930. )
  6931. if usage_results:
  6932. await ws_manager.broadcast(
  6933. {
  6934. "type": "spool_usage_logged",
  6935. "printer_id": printer_id,
  6936. "usage": usage_results,
  6937. }
  6938. )
  6939. log_timing("Usage tracker")
  6940. except Exception as e:
  6941. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6942. # Drop the print-start context unconditionally — the Spoolman branch above
  6943. # skips the internal tracker entirely, so nothing else would clear what
  6944. # print start captured, and a row surviving its print would be restored
  6945. # onto the next one after a restart.
  6946. try:
  6947. from backend.app.services.usage_tracker import discard_session
  6948. async with async_session() as db:
  6949. await discard_session(db, printer_id)
  6950. except Exception as e:
  6951. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6952. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6953. if archive_id:
  6954. if data.get("status") == "completed":
  6955. try:
  6956. await _report_spoolman_usage(printer_id, archive_id)
  6957. log_timing("Spoolman usage report")
  6958. except Exception as e:
  6959. logger.warning("Spoolman usage reporting failed: %s", e)
  6960. else:
  6961. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6962. try:
  6963. async with async_session() as db:
  6964. await _cleanup_spoolman_tracking(
  6965. printer_id,
  6966. archive_id,
  6967. db,
  6968. last_layer_num=data.get("last_layer_num"),
  6969. last_progress=data.get("last_progress"),
  6970. )
  6971. except Exception as e:
  6972. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6973. log_timing("Filament usage tracking")
  6974. if not archive_id:
  6975. # The printer's own calibration run has no archive by design, so this
  6976. # arrives here every time one finishes. Returning before the no-archive
  6977. # notification is not just noise control: that path attributes an
  6978. # unmatched completion to any queue item this printer finished in the
  6979. # last five minutes, which for a calibration that runs alongside a real
  6980. # print means emailing its owner that their print is done, twice and
  6981. # early. Everything above this point has already run — the plate-clear
  6982. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6983. # notification is skipped.
  6984. if is_internal_printer_job(filename, subtask_name):
  6985. logger.info(
  6986. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6987. filename,
  6988. subtask_name,
  6989. )
  6990. return
  6991. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6992. # Still send print-complete/failed/stopped notifications even without an archive.
  6993. # Try to enrich with queue/library-file data so user-specific emails work too.
  6994. async def _notify_no_archive():
  6995. try:
  6996. async with async_session() as db:
  6997. from backend.app.models.library import LibraryFile
  6998. from backend.app.models.print_queue import PrintQueueItem
  6999. from backend.app.models.printer import Printer
  7000. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7001. printer_obj = result.scalar_one_or_none()
  7002. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7003. # Try to find the most-recent queue item for this printer so we can
  7004. # recover created_by_id and estimated print time.
  7005. # NOTE: By the time this task runs the queue item status has already
  7006. # been updated to a terminal state (completed/failed/cancelled), so
  7007. # we look for recently-completed items (within the last 5 minutes).
  7008. no_archive_data: dict | None = None
  7009. try:
  7010. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  7011. q_result = await db.execute(
  7012. select(PrintQueueItem)
  7013. .where(PrintQueueItem.printer_id == printer_id)
  7014. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  7015. .where(PrintQueueItem.completed_at >= cutoff)
  7016. .order_by(PrintQueueItem.completed_at.desc())
  7017. .limit(1)
  7018. )
  7019. queue_item = q_result.scalar_one_or_none()
  7020. if queue_item:
  7021. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7022. # Pull estimated time from library file when available
  7023. if queue_item.library_file_id:
  7024. lib_result = await db.execute(
  7025. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7026. )
  7027. lib_file = lib_result.scalar_one_or_none()
  7028. if lib_file and lib_file.print_time_seconds:
  7029. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  7030. except Exception as lookup_err:
  7031. logger.debug(
  7032. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7033. )
  7034. # Enrich with usage tracker results (captured in enclosing scope)
  7035. if usage_results:
  7036. if no_archive_data is None:
  7037. no_archive_data = {}
  7038. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7039. if total_from_usage > 0:
  7040. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7041. no_archive_data["usage_results"] = usage_results
  7042. # Try MQTT remaining_time for print duration when no queue/library data
  7043. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7044. mqtt_remaining = data.get("remaining_time")
  7045. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7046. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7047. ps = data.get("status", "completed")
  7048. logger.info(
  7049. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7050. )
  7051. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7052. await notification_service.on_print_complete(
  7053. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7054. )
  7055. else:
  7056. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7057. # Send user-specific email if we have a created_by_id
  7058. if no_archive_data and no_archive_data.get("created_by_id"):
  7059. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7060. await _dispatch_user_print_email(
  7061. ps,
  7062. no_archive_data["created_by_id"],
  7063. p_name,
  7064. raw_filename,
  7065. db,
  7066. )
  7067. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7068. except Exception as e:
  7069. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7070. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7071. return
  7072. log_timing("Archive lookup")
  7073. # Update archive status
  7074. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7075. try:
  7076. async with async_session() as db:
  7077. service = ArchiveService(db)
  7078. status = data.get("status", "completed")
  7079. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7080. if hms_errors:
  7081. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7082. failure_reason = derive_failure_reason(status, hms_errors)
  7083. if data.get("_reconciled"):
  7084. # A reconciled completion closes out a stale archive at
  7085. # reconnect — it is not a user action, so don't mislabel it
  7086. # "userCancelled". It shares the stale-cleanup path's key
  7087. # (issue #2974) and records that the real end time is unknown,
  7088. # which is also why its logged duration is 0 (#2592).
  7089. failure_reason = "noStatusUpdate"
  7090. if failure_reason:
  7091. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7092. elif status == "failed" and hms_errors:
  7093. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7094. await service.update_archive_status(
  7095. archive_id,
  7096. status=status,
  7097. completed_at=(
  7098. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7099. ),
  7100. failure_reason=failure_reason,
  7101. )
  7102. logger.info(
  7103. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7104. )
  7105. await ws_manager.send_archive_updated(
  7106. {
  7107. "id": archive_id,
  7108. "status": status,
  7109. }
  7110. )
  7111. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7112. # MQTT relay - publish archive updated
  7113. try:
  7114. await mqtt_relay.on_archive_updated(
  7115. archive_id=archive_id,
  7116. print_name=filename or subtask_name,
  7117. status=status,
  7118. )
  7119. except Exception:
  7120. pass # Don't fail if MQTT fails
  7121. except Exception as e:
  7122. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7123. # Continue with other operations even if archive update fails
  7124. log_timing("Archive status update")
  7125. # Apply finance wallet charge or release reservations once. For all partial
  7126. # terminal states (failed, aborted at the printer display, or cancelled via
  7127. # Bambuddy) use this run's measured spool delta, falling back to the last
  7128. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7129. # estimate and therefore cannot represent an interrupted run.
  7130. try:
  7131. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7132. async with async_session() as db:
  7133. from backend.app.models.archive import PrintArchive
  7134. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7135. archive = await db.get(PrintArchive, archive_id)
  7136. if archive and billing_run_id is None:
  7137. billing_run_id = getattr(archive, "billing_run_id", None)
  7138. if archive and archive.created_by_id is None and _print_user_info:
  7139. archive.created_by_id = _print_user_info.get("user_id")
  7140. await db.flush()
  7141. run_status = data.get("status", "completed")
  7142. last_progress = data.get("last_progress")
  7143. if last_progress is None:
  7144. last_progress = data.get("progress")
  7145. actual_run_grams = _compute_run_filament_grams(
  7146. run_status,
  7147. billing_planned_grams,
  7148. last_progress,
  7149. usage_results,
  7150. )
  7151. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7152. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7153. charged = await apply_print_charge_for_archive(
  7154. db,
  7155. archive_id,
  7156. charged_user_id=billing_user_id,
  7157. cost_center_id=(
  7158. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7159. ),
  7160. print_queue_id=queue_item_id,
  7161. print_run_id=billing_run_id,
  7162. base_cost_override=billing_base_cost,
  7163. filament_usage=filament_usage,
  7164. )
  7165. await db.commit()
  7166. if charged:
  7167. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7168. except Exception as e:
  7169. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7170. printer_info = printer_manager.get_printer(printer_id)
  7171. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7172. billing_filename = filename or subtask_name or "Unknown"
  7173. billing_error = str(e)
  7174. try:
  7175. await ws_manager.broadcast(
  7176. {
  7177. "type": "billing_charge_failed",
  7178. "printer_id": printer_id,
  7179. "printer_name": billing_printer_name,
  7180. "filename": billing_filename,
  7181. "archive_id": archive_id,
  7182. }
  7183. )
  7184. except Exception as notification_error:
  7185. logger.error(
  7186. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7187. archive_id,
  7188. notification_error,
  7189. )
  7190. async def _notify_billing_charge_failed() -> None:
  7191. try:
  7192. async with async_session() as notification_db:
  7193. await notification_service.on_billing_charge_failed(
  7194. printer_id,
  7195. billing_printer_name,
  7196. billing_filename,
  7197. archive_id,
  7198. billing_error,
  7199. notification_db,
  7200. )
  7201. except Exception as provider_error:
  7202. logger.error(
  7203. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7204. archive_id,
  7205. provider_error,
  7206. exc_info=True,
  7207. )
  7208. spawn_background_task(
  7209. _notify_billing_charge_failed(),
  7210. name=f"billing-charge-failed-{archive_id}",
  7211. )
  7212. log_timing("Finance charge update")
  7213. # Write independent print log entry (separate table, never touches archives)
  7214. try:
  7215. async with async_session() as db:
  7216. from backend.app.models.archive import PrintArchive
  7217. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7218. archive = await db.get(PrintArchive, archive_id)
  7219. if archive:
  7220. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7221. # source archive row rather than creating a new one, so an
  7222. # archive that was auto-created from a printer-initiated
  7223. # print (created_by_id=NULL) would otherwise stay unattributed
  7224. # forever. When we have a print-session user AND the archive
  7225. # has no attribution yet, credit the current user. Never
  7226. # overwrite an existing attribution — the original uploader
  7227. # keeps ownership.
  7228. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  7229. if archive.created_by_id is None and _print_user_id is not None:
  7230. archive.created_by_id = _print_user_id
  7231. p_info = printer_manager.get_printer(printer_id)
  7232. # Per-run actuals — written to PrintLogEntry so stats reflect
  7233. # what THIS print actually used, not the source archive's
  7234. # first-run values (#1378). Helper handles the partial-print
  7235. # math (failed / cancelled / stopped get scaled to progress
  7236. # or to tracked spool deltas).
  7237. _run_status = data.get("status", "completed")
  7238. # #2614: scope the per-run estimate to the printed plate. For a
  7239. # multi-plate 3MF dispatched one plate at a time, the archive's
  7240. # filament/cost are the whole-file totals; the PrintLogEntry must
  7241. # reflect only this plate. No effect on single-plate archives (the
  7242. # plate estimate equals the whole-file value) or on the tracker
  7243. # path (measured spool deltas win in _compute_run_filament_grams).
  7244. _est_full_path = (
  7245. app_settings.base_dir / archive.file_path if archive.file_path else None
  7246. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7247. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7248. _run_grams = _compute_run_filament_grams(
  7249. _run_status,
  7250. _est_grams,
  7251. data.get("last_progress", data.get("progress")),
  7252. usage_results,
  7253. )
  7254. # Per-run cost — prefer usage_results sum. For partial prints
  7255. # we deliberately skip the topup-to-estimate logic in
  7256. # usage_tracker (which assumes the print completed); the raw
  7257. # tracked-spool sum is closer to what THIS run actually cost.
  7258. _run_cost: float | None = None
  7259. if usage_results:
  7260. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7261. if _run_cost is None and _run_status == "completed":
  7262. _run_cost = _est_cost
  7263. from backend.app.models.printer import Printer as _Printer
  7264. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7265. run_entry = await write_log_entry(
  7266. db,
  7267. archive_id=archive.id,
  7268. # Captured by _update_queue_status above; None for
  7269. # printer-initiated prints with no queue row. Batch
  7270. # cost/energy roll-up joins on it (#342).
  7271. queue_item_id=queue_item_id,
  7272. status=_run_status,
  7273. print_name=archive.print_name,
  7274. printer_name=p_info.name if p_info else None,
  7275. printer_id=printer_id,
  7276. started_at=archive.started_at,
  7277. completed_at=archive.completed_at,
  7278. filament_type=archive.filament_type,
  7279. filament_color=archive.filament_color,
  7280. filament_used_grams=_run_grams,
  7281. cost=_run_cost,
  7282. wear_cost_per_hour=_wear_rate,
  7283. failure_reason=archive.failure_reason,
  7284. thumbnail_path=archive.thumbnail_path,
  7285. created_by_id=archive.created_by_id,
  7286. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7287. # Reconciled completions have an unknown real end time —
  7288. # log 0 duration instead of the whole disconnect gap (#2592).
  7289. reconciled=bool(data.get("_reconciled")),
  7290. )
  7291. await record_archive_wear(db, archive, run_entry)
  7292. await db.commit()
  7293. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7294. except Exception as e:
  7295. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7296. log_timing("Print log entry")
  7297. # Run slow operations as background tasks to avoid blocking the event loop
  7298. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7299. async def _background_energy_calculation():
  7300. """Calculate and save energy usage in background.
  7301. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7302. backend restart no longer loses per-print energy data).
  7303. """
  7304. try:
  7305. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7306. async with async_session() as db:
  7307. from backend.app.models.archive import PrintArchive
  7308. archive = await db.get(PrintArchive, archive_id)
  7309. if archive is None:
  7310. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7311. return
  7312. starting_kwh = archive.energy_start_kwh
  7313. if starting_kwh is None:
  7314. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7315. return
  7316. candidates = await energy_plug_candidates(db, printer_id)
  7317. if not candidates:
  7318. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7319. return
  7320. # Same ordering as the start reading, so the delta below is
  7321. # against the counter that produced `starting_kwh` (#2859).
  7322. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7323. if selected is None:
  7324. logger.warning(
  7325. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7326. printer_id,
  7327. ", ".join(plug.name for plug in candidates),
  7328. )
  7329. return
  7330. plug, energy = selected
  7331. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7332. energy_used = round(energy["total"] - starting_kwh, 4)
  7333. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7334. if energy_used < 0:
  7335. logger.warning(
  7336. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7337. archive_id,
  7338. starting_kwh,
  7339. energy["total"],
  7340. )
  7341. return
  7342. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7343. # Each hour of the print at the price of that hour (#1251). If
  7344. # that fails, the last price known, as before, rather than no
  7345. # energy at all. Read first: the session may be unusable after.
  7346. last_price = await stored_price(db)
  7347. try:
  7348. energy_cost_value = round(
  7349. await print_energy_cost(
  7350. db,
  7351. plug_id=archive.energy_start_plug_id,
  7352. start_at=archive.energy_start_at,
  7353. start_kwh=starting_kwh,
  7354. start_price=archive.energy_start_price,
  7355. end_kwh=energy["total"],
  7356. end_plug_id=plug.id,
  7357. price_now=await current_price(db),
  7358. ),
  7359. 3,
  7360. )
  7361. except Exception as e:
  7362. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7363. energy_cost_value = round(energy_used * last_price, 3)
  7364. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7365. # reprint doesn't visually clobber the source archive's energy data
  7366. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7367. from sqlalchemy import func
  7368. from backend.app.models.print_log import PrintLogEntry
  7369. existing_runs = await db.scalar(
  7370. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7371. )
  7372. if (existing_runs or 0) <= 1:
  7373. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7374. # we just wrote for THIS print. Either way it's the first run.
  7375. archive.energy_kwh = energy_used
  7376. archive.energy_cost = energy_cost_value
  7377. # Backfill the latest PrintLogEntry for this archive with energy
  7378. # (write_log_entry above ran before this background task completed,
  7379. # so energy fields are still NULL on that row).
  7380. latest_run = await db.execute(
  7381. select(PrintLogEntry)
  7382. .where(PrintLogEntry.archive_id == archive_id)
  7383. .order_by(PrintLogEntry.id.desc())
  7384. .limit(1)
  7385. )
  7386. run_row = latest_run.scalar_one_or_none()
  7387. if run_row is not None:
  7388. run_row.energy_kwh = energy_used
  7389. run_row.energy_cost = energy_cost_value
  7390. await db.commit()
  7391. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7392. except Exception as e:
  7393. logger.warning("[ENERGY-BG] Failed: %s", e)
  7394. async def _background_finish_photo() -> str | None:
  7395. """Capture finish photo in background. Returns photo filename if captured."""
  7396. # #2547: set once this function has raised the plate itself (the
  7397. # timelapse path, where the moment producer returned without doing it).
  7398. # Declared out here so the `finally` can lower it again no matter where
  7399. # the capture below fails.
  7400. plate_restored_z: float | None = None
  7401. try:
  7402. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7403. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7404. # Read phase: settings + printer + archive in a short session, released
  7405. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7406. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7407. # tens of seconds; holding this session across it pinned one pooled
  7408. # connection idle-in-transaction per finishing print (issue #2572).
  7409. async with async_session() as db:
  7410. from backend.app.api.routes.settings import get_setting
  7411. from backend.app.models.archive import PrintArchive
  7412. from backend.app.models.printer import Printer
  7413. capture_enabled = await get_setting(db, "capture_finish_photo")
  7414. if capture_enabled is not None and capture_enabled.lower() != "true":
  7415. return None
  7416. if not archive_id:
  7417. return None
  7418. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7419. archive = (
  7420. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7421. ).scalar_one_or_none()
  7422. if not printer or not archive:
  7423. return None
  7424. import uuid
  7425. from datetime import datetime
  7426. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7427. if not archive.file_path:
  7428. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7429. archive_dir = resolve_archive_dir(archive)
  7430. photo_filename = None
  7431. # Prefer the timelapse last-frame source when a timelapse was
  7432. # recording — it captures the moment after the toolhead parks
  7433. # but before the bed drops, which the live-camera grab below
  7434. # would miss (#1397). Skipped for external cameras (those have
  7435. # their own framing and don't see a Bambu timelapse). Only
  7436. # runs when the USER explicitly enabled timelapse for this
  7437. # print — #1721 removed Bambuddy's force-on at dispatch
  7438. # because it caused per-layer nozzle parking on Smooth-mode
  7439. # slicer profiles.
  7440. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7441. printer.external_camera_enabled and printer.external_camera_url
  7442. )
  7443. timelapse_still_pending = False
  7444. if prefer_timelapse_source:
  7445. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7446. archive_id=archive_id,
  7447. archive_dir=archive_dir,
  7448. rotation=getattr(printer, "camera_rotation", 0),
  7449. )
  7450. # #1721: replacement framing path — on_finish_photo_moment
  7451. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7452. # parked, bed not yet dropped) and cached the JPEG bytes in
  7453. # _stage22_finish_frames. Consume them now so the saved photo
  7454. # has the better framing instead of the post-bed-drop angle
  7455. # the live-camera fallback below would give.
  7456. if not photo_filename:
  7457. # #1790: on the FINISH-state fallback path the producer
  7458. # task is dispatched back-to-back with this consumer, so
  7459. # a bare pop would race past with an empty result and
  7460. # the RTSP fallback below would collide with the
  7461. # producer's still-in-flight grab (single-client RTSP
  7462. # on Bambu printers). Wait for the producer to finish
  7463. # or give up before touching the cache.
  7464. #
  7465. # #2547: 20s was enough when the producer only ever grabbed a
  7466. # frame. It now also raises the plate first, which costs the
  7467. # settle window before the grab even starts — so the budget has
  7468. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7469. # under the notification's own photo wait below.
  7470. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7471. if in_flight is not None:
  7472. try:
  7473. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7474. except asyncio.TimeoutError:
  7475. logger.warning(
  7476. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7477. printer_id,
  7478. )
  7479. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7480. if cached_frame:
  7481. # Already rotated by the producer (#2708) — rotating again
  7482. # here would undo the fix on the banked-frame path, whose
  7483. # bytes reach the cache having been rotated once already.
  7484. photos_dir = archive_dir / "photos"
  7485. photos_dir.mkdir(parents=True, exist_ok=True)
  7486. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7487. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7488. photo_path = photos_dir / photo_filename
  7489. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7490. logger.info(
  7491. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7492. photo_filename,
  7493. len(cached_frame),
  7494. )
  7495. # #2547: the timelapse path reaches the live grab below whenever the
  7496. # video hasn't landed in time — the documented usual outcome on
  7497. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7498. # returned early for those prints without raising the plate, so
  7499. # without this the photo that actually ships in the notification is
  7500. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7501. # asked us to fix. The archive still gets the better video frame
  7502. # later; this is about the image the user is sent.
  7503. #
  7504. # Gated on `timelapse_was_active` precisely because that is the
  7505. # condition under which the producer skipped. On every other path it
  7506. # has already raised and lowered the plate, and repeating that here
  7507. # would be a second pointless round trip.
  7508. if (
  7509. not photo_filename
  7510. and data.get("timelapse_was_active")
  7511. and not print_dispatch_context.end_gcode_injected(printer_id)
  7512. ):
  7513. try:
  7514. async with async_session() as db:
  7515. from backend.app.api.routes.settings import get_setting
  7516. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7517. if restore_setting is None or restore_setting.lower() == "true":
  7518. max_z = await _max_z_for_current_print(
  7519. printer_id, data, logger, bound_archive_id, notify_plate_id
  7520. )
  7521. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7522. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7523. plate_restored_z = max_z
  7524. except Exception as e:
  7525. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7526. # Fallback chain: external camera → buffered live frame →
  7527. # fresh RTSP capture. Only runs if the timelapse path above
  7528. # didn't already produce a photo.
  7529. # Chamber light for the live capture below (#1655).
  7530. async with camera_light(printer if not photo_filename else None):
  7531. if not photo_filename:
  7532. if printer.external_camera_enabled and printer.external_camera_url:
  7533. logger.info("[PHOTO-BG] Using external camera")
  7534. from backend.app.api.routes.camera import live_frame_for_capture
  7535. from backend.app.services.external_camera import capture_frame
  7536. # #2707: the second half of the finish-photo failure — the
  7537. # pre-capture and this fallback both collided with the live
  7538. # view. None here continues down the fallback chain.
  7539. defer, buffered = live_frame_for_capture(printer_id)
  7540. if defer:
  7541. frame_data = buffered
  7542. else:
  7543. frame_data = await capture_frame(
  7544. printer.external_camera_url,
  7545. printer.external_camera_type or "mjpeg",
  7546. snapshot_url=printer.external_camera_snapshot_url,
  7547. )
  7548. if frame_data:
  7549. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7550. photos_dir = archive_dir / "photos"
  7551. photos_dir.mkdir(parents=True, exist_ok=True)
  7552. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7553. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7554. photo_path = photos_dir / photo_filename
  7555. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7556. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7557. else:
  7558. # Check if camera stream is active - use buffered frame to avoid freeze
  7559. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7560. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7561. active_chamber_for_printer = [
  7562. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7563. ]
  7564. buffered_frame = get_buffered_frame(printer_id)
  7565. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7566. # Use frame from active stream
  7567. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7568. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7569. photos_dir = archive_dir / "photos"
  7570. photos_dir.mkdir(parents=True, exist_ok=True)
  7571. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7572. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7573. photo_path = photos_dir / photo_filename
  7574. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7575. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7576. else:
  7577. # No active stream - capture new frame
  7578. from backend.app.services.camera import capture_finish_photo
  7579. photo_filename = await capture_finish_photo(
  7580. printer_id=printer_id,
  7581. ip_address=printer.ip_address,
  7582. access_code=printer.access_code,
  7583. model=printer.model,
  7584. archive_dir=archive_dir,
  7585. rotation=getattr(printer, "camera_rotation", 0),
  7586. )
  7587. # Write phase: attach the photo in a fresh short-lived session.
  7588. if photo_filename:
  7589. async with async_session() as db:
  7590. from backend.app.models.archive import PrintArchive
  7591. arch = await db.get(PrintArchive, archive_id)
  7592. if arch is not None:
  7593. photos = arch.photos or []
  7594. photos.append(photo_filename)
  7595. arch.photos = photos
  7596. await db.commit()
  7597. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7598. # The short wait above is bounded so a slow printer can't hold up
  7599. # the print-complete notification, which is what the caller is
  7600. # blocking on. When it ran out with the video still on its way,
  7601. # keep waiting off to the side and add the better frame to the
  7602. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7603. # users, whose videos routinely take minutes to transfer, never get
  7604. # the pre-bed-drop framing this path exists to provide.
  7605. #
  7606. # Spawned here rather than at the point the wait gave up: both this
  7607. # function and the upgrade do a read-modify-write on `photos`, and
  7608. # the live-camera fallback above can take tens of seconds. Starting
  7609. # the upgrade before that write means the two can interleave and one
  7610. # silently drops the other's entry, leaving a JPEG on disk that the
  7611. # gallery never lists.
  7612. if timelapse_still_pending:
  7613. spawn_background_task(
  7614. _upgrade_finish_photo_from_timelapse(
  7615. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7616. ),
  7617. name=f"finish-photo-upgrade-{archive_id}",
  7618. )
  7619. return photo_filename
  7620. except Exception as e:
  7621. logger.warning("[PHOTO-BG] Failed: %s", e)
  7622. return None
  7623. finally:
  7624. # #2547: we raised the plate, so we owe the move back down — even if
  7625. # the capture in between threw. Otherwise the user finds the print
  7626. # pinned under the nozzle.
  7627. if plate_restored_z is not None:
  7628. try:
  7629. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7630. except Exception as e:
  7631. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7632. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7633. # Photo capture task - result will be used by notifications
  7634. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7635. log_timing("Background tasks scheduled (energy, photo)")
  7636. # Also run smart plug, notifications, and maintenance as background tasks
  7637. print_status = data.get("status", "completed")
  7638. async def _background_smart_plug():
  7639. """Handle smart plug automation in background."""
  7640. try:
  7641. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7642. async with async_session() as db:
  7643. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7644. logger.info("[AUTO-OFF-BG] Completed")
  7645. except Exception as e:
  7646. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7647. async def _background_notifications(finish_photo_filename: str | None = None):
  7648. """Send print complete notifications in background."""
  7649. try:
  7650. logger.info(
  7651. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7652. )
  7653. async with async_session() as db:
  7654. from backend.app.models.archive import PrintArchive
  7655. from backend.app.models.printer import Printer
  7656. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7657. printer = result.scalar_one_or_none()
  7658. printer_name = printer.name if printer else f"Printer {printer_id}"
  7659. archive_data = None
  7660. if archive_id:
  7661. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7662. archive = archive_result.scalar_one_or_none()
  7663. if archive:
  7664. # Actual elapsed time from started_at/completed_at when both are
  7665. # populated (every terminal status sets completed_at after #1198).
  7666. # Falls back to None so the notification path can decide whether to
  7667. # render the slicer estimate as a last resort.
  7668. actual_time_seconds = None
  7669. if archive.started_at and archive.completed_at:
  7670. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7671. if elapsed > 0:
  7672. actual_time_seconds = int(elapsed)
  7673. archive_data = {
  7674. "print_time_seconds": archive.print_time_seconds,
  7675. "actual_time_seconds": actual_time_seconds,
  7676. "actual_filament_grams": archive.filament_used_grams,
  7677. "failure_reason": archive.failure_reason,
  7678. "created_by_id": archive.created_by_id,
  7679. }
  7680. # Scale filament usage for partial prints
  7681. if print_status != "completed" and archive.filament_used_grams:
  7682. progress = data.get("progress") or 0
  7683. scale = _partial_progress_scale(progress)
  7684. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7685. archive_data["progress"] = progress
  7686. # Pass per-slot data from archive.extra_data
  7687. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7688. slots = archive.extra_data["filament_slots"]
  7689. if print_status != "completed":
  7690. scale = _partial_progress_scale(data.get("progress"))
  7691. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7692. archive_data["filament_slots"] = slots
  7693. # Scope project-summed totals down to the plate that was
  7694. # actually printed — see _scope_notification_archive_data_to_plate
  7695. # for the why (#1785).
  7696. archive_data = _scope_notification_archive_data_to_plate(
  7697. archive_data,
  7698. archive.file_path,
  7699. notify_plate_id,
  7700. print_status,
  7701. data.get("progress"),
  7702. app_settings.base_dir,
  7703. )
  7704. # Enrich filament_grams from usage_results when archive has no 3MF data
  7705. if not archive_data.get("actual_filament_grams") and usage_results:
  7706. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7707. if total_from_usage > 0:
  7708. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7709. # Pass usage tracker results for AMS slot info in notifications
  7710. if usage_results:
  7711. archive_data["usage_results"] = usage_results
  7712. # Add finish photo URL and image bytes if available
  7713. if finish_photo_filename:
  7714. photo_url, photo_bytes = await _finish_photo_for_notification(
  7715. db, archive, archive_id, finish_photo_filename
  7716. )
  7717. if photo_url:
  7718. archive_data["finish_photo_url"] = photo_url
  7719. if photo_bytes:
  7720. archive_data["image_data"] = photo_bytes
  7721. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7722. await notification_service.on_print_complete(
  7723. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7724. )
  7725. else:
  7726. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7727. # Post-print outcome confirmation (#1898). Runs in this
  7728. # background task so the finish photo fetched above rides
  7729. # along with the prompt.
  7730. if print_status == "completed" and archive_id:
  7731. await _dispatch_outcome_confirmation_safely(
  7732. db, printer_id, printer_name, data, archive_id, archive_data
  7733. )
  7734. # Send user-specific email notification
  7735. if archive_data:
  7736. created_by_id = archive_data.get("created_by_id")
  7737. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7738. await _dispatch_user_print_email(
  7739. print_status,
  7740. created_by_id,
  7741. printer_name,
  7742. raw_filename,
  7743. db,
  7744. image_data=archive_data.get("image_data"),
  7745. finish_photo_url=archive_data.get("finish_photo_url"),
  7746. )
  7747. logger.info("[NOTIFY-BG] Completed")
  7748. except Exception as e:
  7749. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7750. async def _background_maintenance_check():
  7751. """Check for maintenance due in background."""
  7752. if print_status != "completed":
  7753. return
  7754. try:
  7755. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7756. async with async_session() as db:
  7757. from backend.app.models.printer import Printer
  7758. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7759. printer = result.scalar_one_or_none()
  7760. printer_name = printer.name if printer else f"Printer {printer_id}"
  7761. await ensure_default_types(db)
  7762. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7763. items_needing_attention = [
  7764. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7765. for item in overview.maintenance_items
  7766. if item.enabled and (item.is_due or item.is_warning)
  7767. ]
  7768. if items_needing_attention:
  7769. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7770. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7771. # MQTT relay - publish maintenance alerts
  7772. for item in items_needing_attention:
  7773. try:
  7774. await mqtt_relay.on_maintenance_alert(
  7775. printer_id=printer_id,
  7776. printer_name=printer_name,
  7777. maintenance_type=item["name"],
  7778. current_value=0, # Not easily available here
  7779. threshold=0, # Not easily available here
  7780. )
  7781. except Exception:
  7782. pass # Don't fail if MQTT fails
  7783. else:
  7784. logger.info("[MAINT-BG] Completed (no items need attention)")
  7785. except Exception as e:
  7786. logger.warning("[MAINT-BG] Failed: %s", e)
  7787. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7788. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7789. # Notification task waits for photo capture to complete first (with timeout).
  7790. # When a timelapse was recording, photo sourcing polls the per-print
  7791. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7792. # carries the correct bed-up photo instead of falling through to the
  7793. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7794. #
  7795. # #2547: both budgets now have to cover a plate restore as well.
  7796. #
  7797. # Without timelapse, the wait is on the moment producer, which raises the
  7798. # plate before its grab — so this has to outlast that producer's own budget.
  7799. #
  7800. # With timelapse, the capture polls up to
  7801. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7802. # falls back to a live grab, which is the case that raises the plate. At the
  7803. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7804. # restore would have moved the plate for a photo nobody waited for.
  7805. photo_wait_timeout = (
  7806. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7807. if data.get("timelapse_was_active")
  7808. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7809. )
  7810. async def _photo_then_notify():
  7811. """Wait for photo capture, then send notification with photo URL."""
  7812. finish_photo = None
  7813. try:
  7814. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7815. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7816. except TimeoutError:
  7817. logger.warning(
  7818. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7819. photo_wait_timeout,
  7820. )
  7821. except Exception as e:
  7822. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7823. try:
  7824. await _background_notifications(finish_photo)
  7825. except Exception as e:
  7826. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7827. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7828. # Stitch external camera layer timelapse if session was active
  7829. print_status = data.get("status", "completed")
  7830. async def _background_layer_timelapse():
  7831. """Stitch layer timelapse and attach to archive."""
  7832. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7833. try:
  7834. if print_status == "completed":
  7835. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7836. timelapse_path = await tl_complete(printer_id)
  7837. if timelapse_path and archive_id:
  7838. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7839. async with async_session() as db:
  7840. service = ArchiveService(db)
  7841. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7842. await service.attach_timelapse(
  7843. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  7844. )
  7845. # Clean up the temp file
  7846. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7847. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7848. elif timelapse_path:
  7849. # Timelapse created but no archive - just clean up
  7850. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7851. else:
  7852. # Print failed or cancelled - cancel timelapse session
  7853. cancel_session(printer_id)
  7854. logger.info(
  7855. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7856. )
  7857. except Exception as e:
  7858. logger.warning("[LAYER-TL] Failed: %s", e)
  7859. # Try to cancel session on error
  7860. try:
  7861. cancel_session(printer_id)
  7862. except Exception:
  7863. pass # Best-effort timelapse session cancellation on error
  7864. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7865. log_timing("All background tasks scheduled")
  7866. # Auto-scan for timelapse if recording was active during the print
  7867. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7868. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7869. # Schedule timelapse scan as background task with retries
  7870. # The printer needs time to encode the video after print completion
  7871. baseline = _timelapse_baselines.pop(printer_id, None)
  7872. spawn_background_task(
  7873. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  7874. name=f"scan-timelapse-{archive_id}",
  7875. )
  7876. log_timing("Timelapse scan scheduled")
  7877. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7878. # AMS sensor history recording
  7879. _ams_history_task: asyncio.Task | None = None
  7880. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7881. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7882. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7883. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7884. _ams_alarm_cooldown: dict[str, datetime] = {}
  7885. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7886. # (printer_id, ams_id) already reported as sending the drop index and no
  7887. # percentage. Logged once each so a supported printer that turns out to do this
  7888. # shows up in a support bundle rather than as a user wondering where the
  7889. # humidity reading went -- see the note at the read site below (#3140).
  7890. _ams_index_only_logged: set[tuple[int, int]] = set()
  7891. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7892. """Temperature at which the AMS alarm fires, falling back to the display band.
  7893. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7894. when a notification was sent as well, which is why a room above it made the
  7895. alarm fire once an hour for as long as the weather lasted -- and the only way
  7896. to stop that was to raise the display band and lose the colour that says the
  7897. unit is warm (#2905).
  7898. Unset resolves to the fair threshold, so an install that never sets one is
  7899. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7900. so that arrives here as a string and is handled by the same branch as any
  7901. other unparseable value -- there is no separate sentinel to keep in sync.
  7902. A non-positive value is refused rather than honoured: zero would alarm
  7903. permanently, and it is far more likely to be a cleared field than a
  7904. deliberate choice.
  7905. """
  7906. if raw_alarm_value is None:
  7907. return fair_threshold
  7908. try:
  7909. value = float(raw_alarm_value)
  7910. except (TypeError, ValueError):
  7911. return fair_threshold
  7912. if not math.isfinite(value) or value <= 0:
  7913. return fair_threshold
  7914. return value
  7915. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7916. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7917. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7918. # partway through a cool-down would otherwise resume alarming about heat the
  7919. # user asked for — the same internal-timestamp-row pattern as
  7920. # support.py's debug_logging_enabled_at.
  7921. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7922. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7923. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7924. # matters when it never does.
  7925. AMS_DRYING_GRACE_MINUTES = 120
  7926. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7927. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7928. Anything older than the grace cap would expire on its next visit anyway, so
  7929. discarding it here costs nothing and stops rows for deleted printers from
  7930. accumulating.
  7931. Stamps ahead of now get two defences, because a box whose clock jumps
  7932. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7933. ones are discarded outright, and the rest are clamped to now. Without the
  7934. clamp the cap would measure from a moment that has not happened yet and hold
  7935. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7936. after a clock jump is a far better failure than an alarm silently disabled
  7937. for hours.
  7938. """
  7939. from backend.app.models.settings import Settings
  7940. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7941. setting = result.scalar_one_or_none()
  7942. if not setting or not setting.value:
  7943. return {}
  7944. try:
  7945. raw = json.loads(setting.value)
  7946. except (ValueError, TypeError):
  7947. return {} # Corrupted row → no latch, alarms behave as they did before
  7948. if not isinstance(raw, dict):
  7949. return {}
  7950. now = datetime.now(timezone.utc)
  7951. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7952. latch: dict[str, datetime] = {}
  7953. for key, value in raw.items():
  7954. try:
  7955. stamp = datetime.fromisoformat(str(value))
  7956. except (ValueError, TypeError):
  7957. continue
  7958. if stamp.tzinfo is None:
  7959. stamp = stamp.replace(tzinfo=timezone.utc)
  7960. if not (now - window <= stamp <= now + window):
  7961. continue
  7962. # Nothing may sit in the future: suppression is measured as now minus
  7963. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7964. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7965. latch[str(key)] = min(stamp, now)
  7966. return latch
  7967. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7968. """Persist the latch, writing only when it actually changed.
  7969. Adds the session change but does not commit — the caller's own commit
  7970. carries it, so the latch lands in the same transaction as the sensor rows
  7971. that produced it.
  7972. """
  7973. from backend.app.models.settings import Settings
  7974. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7975. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7976. setting = result.scalar_one_or_none()
  7977. if setting is None:
  7978. # Don't create the row on installs that never dry anything.
  7979. if payload != "{}":
  7980. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7981. elif setting.value != payload:
  7982. setting.value = payload
  7983. def _ams_has_filament(ams_data: dict) -> bool:
  7984. """True if this AMS unit has at least one tray slot holding filament.
  7985. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7986. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7987. still report sensor readings, but those readings are ambient and not
  7988. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7989. humidity/temperature alarms on this check so empty units don't generate
  7990. hourly noise. Sensor history still records regardless so the UI charts
  7991. stay continuous.
  7992. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7993. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7994. """
  7995. bits = ams_data.get("tray_exist_bits")
  7996. if isinstance(bits, str) and bits.strip():
  7997. try:
  7998. return int(bits, 16) > 0
  7999. except ValueError:
  8000. pass
  8001. trays = ams_data.get("tray")
  8002. if isinstance(trays, list):
  8003. return any(
  8004. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8005. )
  8006. return False
  8007. async def record_ams_history():
  8008. """Background task to record AMS humidity and temperature data."""
  8009. logger = logging.getLogger(__name__)
  8010. # Wait a short time for MQTT connections to establish on startup
  8011. await asyncio.sleep(10)
  8012. while True:
  8013. try:
  8014. from backend.app.models.ams_history import AMSSensorHistory
  8015. from backend.app.models.printer import Printer
  8016. from backend.app.models.settings import Settings
  8017. async with async_session() as db:
  8018. # Get all active printers
  8019. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8020. printers = result.scalars().all()
  8021. # Get alarm thresholds from settings
  8022. humidity_threshold = 60.0 # Default: fair threshold
  8023. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8024. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8025. setting = result.scalar_one_or_none()
  8026. if setting:
  8027. try:
  8028. humidity_threshold = float(setting.value)
  8029. except (ValueError, TypeError):
  8030. pass # Keep default threshold if stored value is invalid
  8031. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8032. setting = result.scalar_one_or_none()
  8033. if setting:
  8034. try:
  8035. temp_fair_threshold = float(setting.value)
  8036. except (ValueError, TypeError):
  8037. pass # Keep default threshold if stored value is invalid
  8038. # The alarm gets its own threshold, seeded from the resolved fair
  8039. # value so an install that has never set one behaves exactly as
  8040. # it did before (#2905). ams_temp_fair decides when the card turns
  8041. # amber; 35 C is a reasonable place to change a colour and not a
  8042. # reasonable place to page someone. A room above it makes the
  8043. # alarm fire once an hour for as long as the weather lasts, and
  8044. # the only way to stop it was to raise the display band and lose
  8045. # the colour that says the unit is warm.
  8046. #
  8047. # An unset value is stored as the literal "None", which the except
  8048. # below swallows the same way it swallows garbage -- so the
  8049. # fallback costs nothing and needs no sentinel of its own.
  8050. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8051. setting = result.scalar_one_or_none()
  8052. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8053. temp_fair_threshold, setting.value if setting else None
  8054. )
  8055. # Per-filament humidity threshold overrides (#1605) — resolved
  8056. # per-AMS below from the loaded tray types. Reuses the same
  8057. # resolver as the auto-drying scheduler so behavior stays in
  8058. # lockstep across both consumers.
  8059. from backend.app.services.print_scheduler import PrintScheduler
  8060. per_type_humidity_thresholds: dict[str, int] = {}
  8061. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8062. setting = result.scalar_one_or_none()
  8063. if setting and setting.value:
  8064. try:
  8065. raw = json.loads(setting.value)
  8066. if isinstance(raw, dict):
  8067. for k, v in raw.items():
  8068. try:
  8069. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8070. v
  8071. )
  8072. except (TypeError, ValueError):
  8073. continue
  8074. except (ValueError, TypeError):
  8075. pass # Invalid JSON → no overrides, fall through to global threshold
  8076. # Per-AMS drying latch (#1802), loaded once per pass and written
  8077. # back below only if a unit changed it.
  8078. drying_latch = await _load_ams_drying_latch(db)
  8079. drying_latch_before = dict(drying_latch)
  8080. recorded_count = 0
  8081. for printer in printers:
  8082. # Get current state from printer manager
  8083. state = printer_manager.get_status(printer.id)
  8084. if not state or not state.connected or not state.raw_data:
  8085. continue # Skip disconnected printers - don't use stale data
  8086. raw_data = state.raw_data
  8087. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8088. continue
  8089. # Record data for each AMS unit
  8090. for ams_data in raw_data["ams"]:
  8091. ams_id = int(ams_data.get("id", 0))
  8092. # Percentage only. The 1-5 index is inverted, so
  8093. # charting it as a percentage drew the wettest units as
  8094. # the driest (#3140); a unit that reports no percentage
  8095. # leaves a gap in the chart instead. See
  8096. # utils/ams_humidity.
  8097. humidity = ams_humidity_percent(ams_data)
  8098. # No supported printer is known to send the index
  8099. # alone -- the report came from unsupported firmware,
  8100. # and no install has been seen using the old fallback.
  8101. # "Known" is doing work there, so say so once per unit:
  8102. # the alternative is a silent blank card.
  8103. if humidity is None and ams_data.get("humidity") is not None:
  8104. unit_key = (printer.id, ams_id)
  8105. if unit_key not in _ams_index_only_logged:
  8106. _ams_index_only_logged.add(unit_key)
  8107. logger.info(
  8108. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8109. "percentage. The index is inverted and is not shown as a percentage "
  8110. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8111. "Please report this with the printer and AMS firmware versions.",
  8112. printer.name,
  8113. ams_id,
  8114. )
  8115. # Get temperature
  8116. temperature = None
  8117. temp_str = ams_data.get("temp")
  8118. if temp_str is not None:
  8119. try:
  8120. temperature = float(temp_str)
  8121. except (ValueError, TypeError):
  8122. pass # Skip unparseable temperature value
  8123. # Skip if no data
  8124. if humidity is None and temperature is None:
  8125. continue
  8126. # Record the data point
  8127. history = AMSSensorHistory(
  8128. printer_id=printer.id,
  8129. ams_id=ams_id,
  8130. humidity=humidity,
  8131. # Both columns hold the same reading now that the
  8132. # index can no longer reach ``humidity``. Writing it
  8133. # through the same value also stops a genuine 0%
  8134. # from being stored as NULL, which the old truthiness
  8135. # test did.
  8136. humidity_raw=humidity,
  8137. temperature=temperature,
  8138. )
  8139. db.add(history)
  8140. recorded_count += 1
  8141. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8142. is_ams_ht = ams_id >= 128
  8143. if is_ams_ht:
  8144. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8145. else:
  8146. ams_label = f"AMS-{chr(65 + ams_id)}"
  8147. # Skip alarm dispatch for empty AMS units — humidity /
  8148. # temperature readings are ambient with no filament to
  8149. # protect, and the hourly notification just becomes
  8150. # noise. Sensor history was already recorded above so
  8151. # the UI charts stay continuous (#1619). Per-AMS check
  8152. # so a multi-AMS setup with one loaded + one empty
  8153. # still alarms on the loaded unit.
  8154. if not _ams_has_filament(ams_data):
  8155. continue
  8156. # Resolve per-filament humidity threshold for this AMS
  8157. # unit (#1605). Falls back to the global ams_humidity_fair
  8158. # when no per-type overrides are configured.
  8159. trays = ams_data.get("tray", []) or []
  8160. effective_humidity_threshold = float(
  8161. PrintScheduler.resolve_humidity_threshold(
  8162. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8163. )
  8164. )
  8165. # Check humidity alarm (only if above threshold)
  8166. if humidity is not None and humidity > effective_humidity_threshold:
  8167. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8168. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8169. now = datetime.now(timezone.utc)
  8170. if (
  8171. last_alarm is None
  8172. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8173. ):
  8174. _ams_alarm_cooldown[cooldown_key] = now
  8175. logger.info(
  8176. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8177. )
  8178. try:
  8179. # Call different notification method based on AMS type
  8180. if is_ams_ht:
  8181. await notification_service.on_ams_ht_humidity_high(
  8182. printer.id,
  8183. printer.name,
  8184. ams_label,
  8185. humidity,
  8186. effective_humidity_threshold,
  8187. db,
  8188. )
  8189. else:
  8190. await notification_service.on_ams_humidity_high(
  8191. printer.id,
  8192. printer.name,
  8193. ams_label,
  8194. humidity,
  8195. effective_humidity_threshold,
  8196. db,
  8197. )
  8198. except Exception as e:
  8199. logger.warning("Failed to send humidity alarm: %s", e)
  8200. # A drying cycle heats the unit far past ams_temp_fair on
  8201. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8202. # AMS-HT, against a 35 C default — so the alarm fired
  8203. # once an hour for the whole cycle and kept firing while
  8204. # the unit cooled back down (#1802). Latch on the
  8205. # firmware's own drying state and hold until the reading
  8206. # returns to normal. Humidity is deliberately left alone:
  8207. # it falls during drying, which is the whole point.
  8208. latch_key = f"{printer.id}:{ams_id}"
  8209. # The latch releases at `threshold`, so it takes the alarm
  8210. # number too. Handing it the display band would strand the
  8211. # latch on any unit that settles back above it -- a room
  8212. # where the AMS rests at 37.7 C never returns under a 35 C
  8213. # band, so the latch could only expire on the grace cap
  8214. # rather than releasing when the unit had actually cooled.
  8215. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8216. drying_active=is_drying_active(ams_data),
  8217. temperature=temperature,
  8218. threshold=temp_alarm_threshold,
  8219. latched_at=drying_latch.get(latch_key),
  8220. now=datetime.now(timezone.utc),
  8221. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8222. )
  8223. if new_latch is None:
  8224. drying_latch.pop(latch_key, None)
  8225. else:
  8226. drying_latch[latch_key] = new_latch
  8227. # Check temperature alarm (only if above threshold)
  8228. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8229. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8230. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8231. now = datetime.now(timezone.utc)
  8232. if (
  8233. last_alarm is None
  8234. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8235. ):
  8236. _ams_alarm_cooldown[cooldown_key] = now
  8237. logger.info(
  8238. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8239. f"{temperature}°C > {temp_alarm_threshold}°C"
  8240. )
  8241. try:
  8242. # Call different notification method based on AMS type
  8243. if is_ams_ht:
  8244. # The reported threshold has to be the one
  8245. # that fired, or the message says "> 35 °C"
  8246. # while firing at 45.
  8247. await notification_service.on_ams_ht_temperature_high(
  8248. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8249. )
  8250. else:
  8251. await notification_service.on_ams_temperature_high(
  8252. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8253. )
  8254. except Exception as e:
  8255. logger.warning("Failed to send temperature alarm: %s", e)
  8256. if drying_latch != drying_latch_before:
  8257. await _save_ams_drying_latch(db, drying_latch)
  8258. await db.commit()
  8259. if recorded_count > 0:
  8260. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8261. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8262. global _ams_cleanup_counter
  8263. _ams_cleanup_counter += 1
  8264. if _ams_cleanup_counter >= 288:
  8265. _ams_cleanup_counter = 0
  8266. # Get retention days from settings
  8267. from backend.app.models.settings import Settings
  8268. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8269. setting = result.scalar_one_or_none()
  8270. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8271. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8272. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8273. await db.commit()
  8274. if result.rowcount > 0:
  8275. logger.info(
  8276. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8277. )
  8278. # Wait until next recording interval
  8279. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8280. except asyncio.CancelledError:
  8281. break
  8282. except Exception as e:
  8283. logger.warning("AMS history recording failed: %s", e)
  8284. await asyncio.sleep(60) # Wait a bit before retrying
  8285. def start_ams_history_recording():
  8286. """Start the AMS history recording background task."""
  8287. global _ams_history_task
  8288. if _ams_history_task is None:
  8289. _ams_history_task = asyncio.create_task(record_ams_history())
  8290. logging.getLogger(__name__).info("AMS history recording started")
  8291. def stop_ams_history_recording():
  8292. """Stop the AMS history recording background task."""
  8293. global _ams_history_task
  8294. if _ams_history_task:
  8295. _ams_history_task.cancel()
  8296. _ams_history_task = None
  8297. logging.getLogger(__name__).info("AMS history recording stopped")
  8298. # Printer sensor history recording (nozzle / bed / chamber)
  8299. _printer_sensor_history_task: asyncio.Task | None = None
  8300. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8301. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8302. _printer_sensor_cleanup_counter = 0
  8303. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8304. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8305. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8306. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8307. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8308. _SENSOR_TARGET_KEYS = {
  8309. "nozzle": "nozzle_target",
  8310. "nozzle_2": "nozzle_2_target",
  8311. "bed": "bed_target",
  8312. "chamber": "chamber_target",
  8313. }
  8314. async def record_printer_sensor_history():
  8315. """Background task to record nozzle / bed / chamber readings.
  8316. Pulls from `state.temperatures` (already normalised across all printer
  8317. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8318. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8319. """
  8320. logger = logging.getLogger(__name__)
  8321. await asyncio.sleep(10)
  8322. while True:
  8323. try:
  8324. from backend.app.models.printer import Printer
  8325. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8326. from backend.app.models.settings import Settings
  8327. async with async_session() as db:
  8328. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8329. printers = result.scalars().all()
  8330. recorded_count = 0
  8331. for printer in printers:
  8332. state = printer_manager.get_status(printer.id)
  8333. if not state or not state.connected:
  8334. continue
  8335. temps = getattr(state, "temperatures", None) or {}
  8336. if not isinstance(temps, dict):
  8337. continue
  8338. for kind in _SENSOR_KINDS:
  8339. if kind not in temps:
  8340. continue
  8341. try:
  8342. value = float(temps[kind])
  8343. except (ValueError, TypeError):
  8344. continue
  8345. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8346. target_val: float | None = None
  8347. if target_raw is not None:
  8348. try:
  8349. target_val = float(target_raw)
  8350. except (ValueError, TypeError):
  8351. target_val = None
  8352. db.add(
  8353. PrinterSensorHistory(
  8354. printer_id=printer.id,
  8355. sensor_kind=kind,
  8356. value=value,
  8357. target=target_val,
  8358. )
  8359. )
  8360. recorded_count += 1
  8361. await db.commit()
  8362. if recorded_count > 0:
  8363. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8364. # Periodic cleanup — once every ~24h at this interval.
  8365. global _printer_sensor_cleanup_counter
  8366. _printer_sensor_cleanup_counter += 1
  8367. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8368. if _printer_sensor_cleanup_counter >= cleanup_every:
  8369. _printer_sensor_cleanup_counter = 0
  8370. result = await db.execute(
  8371. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8372. )
  8373. setting = result.scalar_one_or_none()
  8374. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8375. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8376. cleanup = await db.execute(
  8377. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8378. )
  8379. await db.commit()
  8380. if cleanup.rowcount > 0:
  8381. logger.info(
  8382. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8383. cleanup.rowcount,
  8384. retention_days,
  8385. )
  8386. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8387. except asyncio.CancelledError:
  8388. break
  8389. except Exception as e:
  8390. logger.warning("Printer sensor history recording failed: %s", e)
  8391. await asyncio.sleep(60)
  8392. def start_printer_sensor_history_recording():
  8393. global _printer_sensor_history_task
  8394. if _printer_sensor_history_task is None:
  8395. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8396. logging.getLogger(__name__).info("Printer sensor history recording started")
  8397. def stop_printer_sensor_history_recording():
  8398. global _printer_sensor_history_task
  8399. if _printer_sensor_history_task:
  8400. _printer_sensor_history_task.cancel()
  8401. _printer_sensor_history_task = None
  8402. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8403. # Printer runtime tracking
  8404. _runtime_tracking_task: asyncio.Task | None = None
  8405. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8406. async def track_printer_runtime():
  8407. """Background task to track printer active runtime (RUNNING state only).
  8408. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8409. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8410. which track mechanical wear. Pause time has no motion and no wear, so
  8411. counting it inflates maintenance warnings (#1521).
  8412. """
  8413. logger = logging.getLogger(__name__)
  8414. # Wait for MQTT connections to establish on startup
  8415. await asyncio.sleep(15)
  8416. while True:
  8417. try:
  8418. from backend.app.models.printer import Printer
  8419. # Fetch printer IDs in a short-lived read-only session
  8420. async with async_session() as db:
  8421. result = await db.execute(
  8422. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8423. Printer.is_active.is_(True)
  8424. )
  8425. )
  8426. printer_rows = result.all()
  8427. now = datetime.now(timezone.utc)
  8428. updated_count = 0
  8429. # Update each printer in its own short session to minimise write-lock
  8430. # hold time and avoid blocking critical commits like queue status
  8431. # updates (#897).
  8432. for pid, pname, runtime_secs, last_update in printer_rows:
  8433. state = printer_manager.get_status(pid)
  8434. if not state:
  8435. logger.debug("[%s] Runtime tracking: no state available", pname)
  8436. continue
  8437. if not state.connected:
  8438. logger.debug("[%s] Runtime tracking: not connected", pname)
  8439. continue
  8440. needs_commit = False
  8441. new_runtime = runtime_secs
  8442. new_last_update = last_update
  8443. if state.state == "RUNNING":
  8444. if last_update:
  8445. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8446. elapsed = (now - lu).total_seconds()
  8447. if elapsed > 0:
  8448. new_runtime = runtime_secs + int(elapsed)
  8449. updated_count += 1
  8450. needs_commit = True
  8451. logger.debug(
  8452. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8453. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8454. )
  8455. else:
  8456. needs_commit = True
  8457. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8458. new_last_update = now
  8459. else:
  8460. if last_update is not None:
  8461. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8462. new_last_update = None
  8463. needs_commit = True
  8464. if needs_commit:
  8465. try:
  8466. async with async_session() as db:
  8467. result = await db.execute(select(Printer).where(Printer.id == pid))
  8468. printer = result.scalar_one_or_none()
  8469. if printer:
  8470. printer.runtime_seconds = new_runtime
  8471. printer.last_runtime_update = new_last_update
  8472. await db.commit()
  8473. except Exception as e:
  8474. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8475. if updated_count > 0:
  8476. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8477. except asyncio.CancelledError:
  8478. logger.info("Runtime tracking cancelled")
  8479. break
  8480. except Exception as e:
  8481. logger.warning("Runtime tracking failed: %s", e)
  8482. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8483. def start_runtime_tracking():
  8484. """Start the printer runtime tracking background task."""
  8485. global _runtime_tracking_task
  8486. if _runtime_tracking_task is None:
  8487. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8488. logging.getLogger(__name__).info("Printer runtime tracking started")
  8489. def stop_runtime_tracking():
  8490. """Stop the printer runtime tracking background task."""
  8491. global _runtime_tracking_task
  8492. if _runtime_tracking_task:
  8493. _runtime_tracking_task.cancel()
  8494. _runtime_tracking_task = None
  8495. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8496. # SpoolBuddy device watchdog
  8497. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8498. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8499. async def _spoolbuddy_watchdog_loop():
  8500. """Periodic check for SpoolBuddy devices that have gone offline."""
  8501. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8502. while True:
  8503. try:
  8504. await spoolbuddy_watchdog()
  8505. except asyncio.CancelledError:
  8506. break
  8507. except Exception as e:
  8508. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8509. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8510. def start_spoolbuddy_watchdog():
  8511. global _spoolbuddy_watchdog_task
  8512. if _spoolbuddy_watchdog_task is None:
  8513. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8514. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8515. def stop_spoolbuddy_watchdog():
  8516. global _spoolbuddy_watchdog_task
  8517. if _spoolbuddy_watchdog_task:
  8518. _spoolbuddy_watchdog_task.cancel()
  8519. _spoolbuddy_watchdog_task = None
  8520. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8521. # Dead-MQTT-session recovery
  8522. #
  8523. # check_staleness() covers the "connected but silent" half-broken session. It
  8524. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8525. # is the only thing left watching at that point. When paho stops making
  8526. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8527. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8528. # offline with the UI open the whole time, recovered only when something
  8529. # happened to nudge it.
  8530. #
  8531. # This loop is that backstop. It only touches printers that had a working
  8532. # session and lost it, and only when the MQTT port still answers — a printer
  8533. # that is simply switched off is left to paho, since rebuilding a client
  8534. # against an unreachable host achieves nothing and would fill the log every
  8535. # night.
  8536. _connection_watchdog_task: asyncio.Task | None = None
  8537. CONNECTION_WATCHDOG_INTERVAL = 60
  8538. # How long a printer must have been silent before we stop trusting paho.
  8539. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8540. # so a session that is recovering on its own is never interrupted.
  8541. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8542. # Per-printer floor between rebuild attempts.
  8543. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8544. _connection_watchdog_last_attempt: dict[int, float] = {}
  8545. async def _recover_dead_printer_sessions() -> int:
  8546. """Rebuild MQTT clients that have been offline too long to still be trying.
  8547. Returns the number of printers a rebuild was attempted for (for tests and
  8548. for the caller's logging). Never raises: one unreachable printer must not
  8549. stop the sweep for the rest of the farm.
  8550. """
  8551. logger = logging.getLogger(__name__)
  8552. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8553. now = time.monotonic()
  8554. recovered = 0
  8555. for printer_id, client in list(printer_manager._clients.items()):
  8556. try:
  8557. if client.state.connected:
  8558. _connection_watchdog_last_attempt.pop(printer_id, None)
  8559. continue
  8560. # Time since the last inbound message is the age of the last known
  8561. # good session — no extra bookkeeping needed, and it is the same
  8562. # clock is_stale() reads. 0 means this client has never had one:
  8563. # that is the initial-connect path, where paho retrying is the
  8564. # correct and only behaviour, so leave it be.
  8565. last_msg = client._last_message_time
  8566. if not last_msg:
  8567. continue
  8568. offline_for = time.time() - last_msg
  8569. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8570. continue
  8571. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8572. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8573. continue
  8574. if not await check_port(client.ip_address, PORT_MQTT):
  8575. # Switched off, unplugged, or off the network. Paho's retry is
  8576. # the right handler; say so at debug level and move on.
  8577. logger.debug(
  8578. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8579. "— leaving the reconnect to paho",
  8580. printer_id,
  8581. offline_for,
  8582. )
  8583. _connection_watchdog_last_attempt[printer_id] = now
  8584. continue
  8585. _connection_watchdog_last_attempt[printer_id] = now
  8586. recovered += 1
  8587. logger.warning(
  8588. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8589. "rebuilding the client with a fresh session (last connect error: %s)",
  8590. printer_id,
  8591. offline_for,
  8592. PORT_MQTT,
  8593. client.last_connect_error or "none recorded",
  8594. )
  8595. # Async context, so this takes the hard-reset path: fresh client_id,
  8596. # paho's QoS 1 queue dropped. That matters — a project_file left
  8597. # unacked on the dead session would otherwise replay into the new
  8598. # one and trip 0500_4003 on the printer (#1136).
  8599. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8600. except Exception as e:
  8601. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8602. return recovered
  8603. async def _connection_watchdog_loop():
  8604. logger = logging.getLogger(__name__)
  8605. # Let the initial connects settle before judging anyone offline.
  8606. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8607. while True:
  8608. try:
  8609. await _recover_dead_printer_sessions()
  8610. except asyncio.CancelledError:
  8611. break
  8612. except Exception as e:
  8613. logger.warning("Connection watchdog sweep failed: %s", e)
  8614. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8615. def start_connection_watchdog():
  8616. global _connection_watchdog_task
  8617. if _connection_watchdog_task is None:
  8618. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8619. logging.getLogger(__name__).info("Printer connection watchdog started")
  8620. def stop_connection_watchdog():
  8621. global _connection_watchdog_task
  8622. if _connection_watchdog_task:
  8623. _connection_watchdog_task.cancel()
  8624. _connection_watchdog_task = None
  8625. _connection_watchdog_last_attempt.clear()
  8626. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8627. # Camera stream orphan cleanup
  8628. _camera_cleanup_task: asyncio.Task | None = None
  8629. CAMERA_CLEANUP_INTERVAL = 60
  8630. async def _camera_cleanup_loop():
  8631. """Periodically clean up orphaned ffmpeg processes."""
  8632. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8633. while True:
  8634. try:
  8635. await cleanup_orphaned_streams()
  8636. except asyncio.CancelledError:
  8637. break
  8638. except Exception as e:
  8639. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8640. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8641. def start_camera_cleanup():
  8642. global _camera_cleanup_task
  8643. if _camera_cleanup_task is None:
  8644. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8645. logging.getLogger(__name__).info("Camera stream cleanup started")
  8646. def stop_camera_cleanup():
  8647. global _camera_cleanup_task
  8648. if _camera_cleanup_task:
  8649. _camera_cleanup_task.cancel()
  8650. _camera_cleanup_task = None
  8651. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8652. # ---------------------------------------------------------------------------
  8653. # Expected-print TTL eviction
  8654. # ---------------------------------------------------------------------------
  8655. def _evict_stale_expected_prints() -> None:
  8656. """Remove entries from _expected_prints / _expected_print_creators that are
  8657. older than _EXPECTED_PRINT_TTL_SECONDS.
  8658. This prevents unbounded growth when a print is registered (via
  8659. register_expected_print) but on_print_start never fires — e.g. because the
  8660. printer disconnects, the app restarts, or the print is started directly from
  8661. the printer panel without going through the queue.
  8662. """
  8663. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8664. # (e.g. NTP sync, DST changes).
  8665. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8666. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8667. if not stale_keys:
  8668. return
  8669. evicted_archive_ids: set[int] = set()
  8670. for key in stale_keys:
  8671. archive_id = _expected_prints.pop(key, None)
  8672. if archive_id is not None:
  8673. evicted_archive_ids.add(archive_id)
  8674. _expected_print_creators.pop(key, None)
  8675. _expected_print_registered_at.pop(key, None)
  8676. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8677. # that have no remaining live keys in _expected_prints (all variants
  8678. # were just evicted) and are not printing right now. Print start pops
  8679. # only the names the printer reported, so the "<base>.gcode" variant
  8680. # outlives it; without the printing check its eviction two hours after
  8681. # dispatch threw away a running print's plate, AMS mapping and cost
  8682. # centre, which completion still reads (#3275).
  8683. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  8684. for archive_id in evicted_archive_ids:
  8685. if archive_id not in live_archive_ids:
  8686. _print_ams_mappings.pop(archive_id, None)
  8687. _print_cost_center_ids.pop(archive_id, None)
  8688. _print_plate_ids.pop(archive_id, None)
  8689. logging.getLogger(__name__).info(
  8690. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8691. )
  8692. async def _expected_prints_cleanup_loop() -> None:
  8693. """Background task: periodically evict stale expected-print entries."""
  8694. while True:
  8695. try:
  8696. _evict_stale_expected_prints()
  8697. except asyncio.CancelledError:
  8698. raise
  8699. except Exception as e:
  8700. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8701. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8702. def start_expected_prints_cleanup() -> None:
  8703. global _expected_prints_cleanup_task
  8704. if _expected_prints_cleanup_task is None:
  8705. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8706. logging.getLogger(__name__).info("Expected prints cleanup started")
  8707. def stop_expected_prints_cleanup() -> None:
  8708. global _expected_prints_cleanup_task
  8709. if _expected_prints_cleanup_task:
  8710. _expected_prints_cleanup_task.cancel()
  8711. _expected_prints_cleanup_task = None
  8712. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8713. # ---------------------------------------------------------------------------
  8714. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8715. # ---------------------------------------------------------------------------
  8716. _auth_cleanup_task: asyncio.Task | None = None
  8717. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8718. async def _run_auth_cleanup() -> None:
  8719. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8720. from backend.app.core.database import async_session
  8721. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8722. from backend.app.models.user_totp import UserTOTP
  8723. now = datetime.now(timezone.utc)
  8724. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8725. try:
  8726. async with async_session() as db:
  8727. stale_cutoff = now - timedelta(hours=1)
  8728. result = await db.execute(
  8729. select(UserTOTP).where(
  8730. UserTOTP.is_enabled.is_(False),
  8731. UserTOTP.created_at < stale_cutoff,
  8732. )
  8733. )
  8734. stale_records = result.scalars().all()
  8735. if stale_records:
  8736. for rec in stale_records:
  8737. await db.delete(rec)
  8738. await db.commit()
  8739. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8740. except Exception as e:
  8741. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8742. # Remove expired revoked-JTI entries (they are no longer needed once the
  8743. # original token's exp has passed — the token would be rejected by JWT
  8744. # signature verification regardless).
  8745. try:
  8746. async with async_session() as db:
  8747. await db.execute(
  8748. delete(AuthEphemeralToken).where(
  8749. AuthEphemeralToken.token_type == "revoked_jti",
  8750. AuthEphemeralToken.expires_at < now,
  8751. )
  8752. )
  8753. await db.commit()
  8754. except Exception as e:
  8755. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8756. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8757. # Events outside this window can never affect rate-limit decisions — they only
  8758. # consume DB space. Use the same window constant as the rate limiter so the
  8759. # two are always in sync.
  8760. try:
  8761. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8762. async with async_session() as db:
  8763. await db.execute(
  8764. delete(AuthRateLimitEvent).where(
  8765. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8766. )
  8767. )
  8768. await db.commit()
  8769. except Exception as e:
  8770. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8771. async def _auth_cleanup_loop() -> None:
  8772. """Periodic background task: run auth cleanup every hour."""
  8773. while True:
  8774. try:
  8775. await _run_auth_cleanup()
  8776. except asyncio.CancelledError:
  8777. break
  8778. except Exception as e:
  8779. logging.warning("Auth cleanup loop error: %s", e)
  8780. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8781. def start_auth_cleanup() -> None:
  8782. global _auth_cleanup_task
  8783. if _auth_cleanup_task is None:
  8784. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8785. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8786. def stop_auth_cleanup() -> None:
  8787. global _auth_cleanup_task
  8788. if _auth_cleanup_task:
  8789. _auth_cleanup_task.cancel()
  8790. _auth_cleanup_task = None
  8791. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8792. @asynccontextmanager
  8793. async def lifespan(app: FastAPI):
  8794. # Startup
  8795. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8796. # anything else can spawn tasks that might trip it.
  8797. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8798. install_proactor_reset_filter()
  8799. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  8800. # what turned descriptor exhaustion into a corrupted database (#2883).
  8801. from backend.app.core.fd_limit import raise_open_file_limit
  8802. raise_open_file_limit()
  8803. # Before init_db, so the warning is near the top of the log rather than
  8804. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8805. warn_if_running_on_uvloop()
  8806. await init_db()
  8807. # Browser download tokens expire after five minutes. Remove abandoned
  8808. # prepared ZIPs at startup as well as before each new preparation so a
  8809. # quiet appliance cannot retain an unusable bundle indefinitely.
  8810. try:
  8811. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8812. await prune_stale_printer_file_bundles()
  8813. except Exception as exc:
  8814. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8815. # After migrations, so the is_env_managed column exists. Never raises --
  8816. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8817. # startup (see apply_env_oidc_provider).
  8818. from backend.app.core.oidc_env import apply_env_oidc_provider
  8819. async with async_session() as oidc_db:
  8820. await apply_env_oidc_provider(oidc_db)
  8821. # Close out batches that finished before `completed` was a reachable status
  8822. # (#342). Without this the Batches tab opens on every batch created since
  8823. # the feature shipped, all still marked active. Never blocks startup.
  8824. try:
  8825. from backend.app.services.print_batch import backfill_batch_statuses
  8826. async with async_session() as batch_db:
  8827. await backfill_batch_statuses(batch_db)
  8828. except Exception as exc:
  8829. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8830. # Register an app-scoped httpx client for Bambu Cloud services so
  8831. # per-request BambuCloudService instances reuse the same connection pool
  8832. # (important for routes like /cloud/filament-info that chain many
  8833. # get_setting_detail calls). The shared client stores no region/token
  8834. # state, so the per-request ownership pattern that fixed the region-bleed
  8835. # bug is preserved.
  8836. import httpx as _httpx
  8837. from backend.app.services.bambu_cloud import set_shared_http_client
  8838. from backend.app.services.model_providers.makerworld.service import (
  8839. set_shared_http_client as set_shared_makerworld_http_client,
  8840. )
  8841. from backend.app.services.orca_cloud import (
  8842. set_shared_http_client as set_shared_orca_http_client,
  8843. )
  8844. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8845. set_shared_http_client(_shared_cloud_http_client)
  8846. # Reuse the same connection pool for MakerWorld — different host, same
  8847. # keep-alive pool saves a TLS handshake per request.
  8848. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8849. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8850. # each spun up (and never closed) its own client, leaking sockets.
  8851. set_shared_orca_http_client(_shared_cloud_http_client)
  8852. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8853. # This can happen when a print was cancelled mid-print on versions before this fix.
  8854. try:
  8855. async with async_session() as db:
  8856. from backend.app.models.print_queue import PrintQueueItem
  8857. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8858. aborted_items = result.scalars().all()
  8859. if aborted_items:
  8860. for item in aborted_items:
  8861. item.status = "cancelled"
  8862. await db.commit()
  8863. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8864. except Exception as e:
  8865. logging.warning("Failed to fix aborted queue items: %s", e)
  8866. # Restore debug logging state from previous session
  8867. await init_debug_logging()
  8868. # Set up printer manager callbacks
  8869. loop = asyncio.get_event_loop()
  8870. printer_manager.set_event_loop(loop)
  8871. printer_manager.set_status_change_callback(on_printer_status_change)
  8872. printer_manager.set_print_start_callback(on_print_start)
  8873. printer_manager.set_print_complete_callback(on_print_complete)
  8874. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8875. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8876. printer_manager.set_ams_change_callback(on_ams_change)
  8877. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8878. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8879. await printer_manager.load_awaiting_plate_clear_from_db()
  8880. # Layer change callback for external camera timelapse
  8881. async def on_layer_change(printer_id: int, layer_num: int):
  8882. """Capture timelapse frame on layer change + first layer notification."""
  8883. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8884. await tl_layer_change(printer_id, layer_num)
  8885. # #1867: bank a recent in-print frame so the finish-photo path has a
  8886. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8887. # #2547 added `on_print_progress` as a second driver — this one alone
  8888. # stops firing once the final layer begins.
  8889. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8890. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8891. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8892. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8893. # nozzle clean), so a bare layer_num check can fire minutes before the
  8894. # first real extrusion. We require gcode_state == RUNNING and
  8895. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8896. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8897. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8898. # edge fires later; _first_layer_notified stays clear until we actually send
  8899. # so a deferred re-evaluation can win. See issue #1837.
  8900. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8901. client = printer_manager.get_client(printer_id)
  8902. state = client.state if client else None
  8903. if not state or state.state != "RUNNING":
  8904. return
  8905. if state.mc_print_sub_stage not in (None, 0):
  8906. return
  8907. _first_layer_notified[printer_id] = True
  8908. try:
  8909. async with async_session() as db:
  8910. from backend.app.models.printer import Printer
  8911. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8912. printer = result.scalar_one_or_none()
  8913. if not printer:
  8914. return
  8915. printer_name = printer.name
  8916. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8917. total_layers = state.total_layers if state else 0
  8918. image_data = await _capture_snapshot_for_notification(
  8919. printer_id, printer, logging.getLogger(__name__)
  8920. )
  8921. await notification_service.on_first_layer_complete(
  8922. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8923. )
  8924. except Exception as e:
  8925. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8926. printer_manager.set_layer_change_callback(on_layer_change)
  8927. async def on_print_progress(printer_id: int, percent: int):
  8928. """#2547: keep the in-print frame bank fresh through the final layer.
  8929. `on_layer_change` stops the moment the last layer starts, which on the
  8930. H2C capture that closed #2547 left the bank stale for the three minutes
  8931. that layer took. Progress is the only field that keeps advancing there,
  8932. and it freezes before the End G-code runs — so banking on it stays
  8933. inside the print and never sees a swapped plate.
  8934. """
  8935. client = printer_manager.get_client(printer_id)
  8936. state = client.state if client else None
  8937. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8938. printer_manager.set_print_progress_callback(on_print_progress)
  8939. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8940. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8941. waiter = _bed_cool_waiters.get(printer_id)
  8942. if not waiter:
  8943. return
  8944. threshold = waiter["threshold"]
  8945. if bed_temp > threshold:
  8946. return
  8947. # Bed is at or below threshold — fire notification and remove waiter
  8948. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8949. if not waiter_info:
  8950. return # Another callback already handled it
  8951. bed_cool_logger = logging.getLogger(__name__)
  8952. bed_cool_logger.info(
  8953. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8954. bed_temp,
  8955. printer_id,
  8956. threshold,
  8957. )
  8958. try:
  8959. printer_info = printer_manager.get_printer(printer_id)
  8960. p_name = printer_info.name if printer_info else "Unknown"
  8961. async with async_session() as db:
  8962. await notification_service.on_bed_cooled(
  8963. printer_id=printer_id,
  8964. printer_name=p_name,
  8965. bed_temp=bed_temp,
  8966. threshold=threshold,
  8967. filename=waiter_info["filename"],
  8968. db=db,
  8969. )
  8970. except Exception as e:
  8971. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8972. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8973. async def on_drying_complete(printer_id: int, ams_id: int):
  8974. """Smart-plug auto-off-after-drying trigger (#1349).
  8975. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8976. manager walks all plugs linked to this printer and turns off only
  8977. the ones with ``auto_off_after_drying`` enabled, after their
  8978. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8979. dual-AMS dry that ends within the same MQTT push) call this once
  8980. per unit — the manager's ``_cancel_pending_off`` collapses
  8981. repeated scheduling on the same plug to one timer, so duplicate
  8982. fires are safe.
  8983. """
  8984. try:
  8985. async with async_session() as db:
  8986. await smart_plug_manager.on_drying_complete(printer_id, db)
  8987. except Exception as e:
  8988. logging.getLogger(__name__).warning(
  8989. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8990. printer_id,
  8991. ams_id,
  8992. e,
  8993. )
  8994. printer_manager.set_drying_complete_callback(on_drying_complete)
  8995. async def on_drying_cycle_end(printer_id: int, cycle):
  8996. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  8997. from backend.app.services.spool_drying import record_drying_cycle
  8998. try:
  8999. async with async_session() as db:
  9000. await record_drying_cycle(db, printer_id, cycle)
  9001. except Exception as e:
  9002. logging.getLogger(__name__).warning(
  9003. "Failed to record drying for printer %d (AMS %d): %s",
  9004. printer_id,
  9005. cycle.ams_id,
  9006. e,
  9007. )
  9008. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9009. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9010. """Surface the read-back result of a spool assignment to the UI (#2582).
  9011. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9012. echoed back the filament id we pushed. We relay that as a websocket
  9013. event so the frontend can toast "loaded" / "assignment didn't take"
  9014. instead of the historic silent fire-and-forget, which made the
  9015. AMS→Studio hand-off feel random to users.
  9016. """
  9017. try:
  9018. from backend.app.services.spool_assignment_notifications import (
  9019. _slot_label_from_global_tray,
  9020. )
  9021. if ams_id == 255:
  9022. global_id = 254 + tray_id
  9023. elif ams_id >= 128:
  9024. global_id = ams_id
  9025. else:
  9026. global_id = ams_id * 4 + tray_id
  9027. slot_label = _slot_label_from_global_tray(global_id)
  9028. printer_info = printer_manager.get_printer(printer_id)
  9029. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9030. await ws_manager.broadcast(
  9031. {
  9032. "type": "spool_assignment_verified",
  9033. "printer_id": printer_id,
  9034. "printer_name": printer_name,
  9035. "ams_id": ams_id,
  9036. "tray_id": tray_id,
  9037. "slot": slot_label,
  9038. "verified": verified,
  9039. # Present on success: False means the filament setting landed
  9040. # but the K-profile (cali_idx) did not — the reporter's exact
  9041. # "loaded but no flow profile" symptom.
  9042. "kprofile_applied": detail.get("kprofile_applied", True),
  9043. # Present on failure: whether any tray telemetry was seen in
  9044. # the window (distinguishes "printer silent" from "printer
  9045. # stored something else").
  9046. "saw_tray": detail.get("saw_tray", False),
  9047. }
  9048. )
  9049. except Exception as e:
  9050. logging.getLogger(__name__).warning(
  9051. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9052. printer_id,
  9053. ams_id,
  9054. tray_id,
  9055. e,
  9056. )
  9057. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9058. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9059. """Persist a mid-print tray change for completion-time attribution.
  9060. AMS filament backup switches trays without telling the slicer, so the
  9061. tray-change log is the only record of which spool fed which layers.
  9062. Keeping it only in memory meant a restart mid-print charged everything
  9063. to the tray that finished the job.
  9064. """
  9065. try:
  9066. from backend.app.services.usage_tracker import record_tray_change
  9067. async with async_session() as db:
  9068. await record_tray_change(db, printer_id, tray_global, layer_num)
  9069. except Exception as e:
  9070. logging.getLogger(__name__).warning(
  9071. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9072. printer_id,
  9073. tray_global,
  9074. layer_num,
  9075. e,
  9076. )
  9077. printer_manager.set_tray_change_callback(on_tray_change)
  9078. # Initialize MQTT relay from settings
  9079. async with async_session() as db:
  9080. from backend.app.api.routes.settings import get_setting
  9081. mqtt_settings = {
  9082. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9083. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9084. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9085. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9086. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9087. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9088. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9089. }
  9090. await mqtt_relay.configure(mqtt_settings)
  9091. # Restore MQTT smart plug subscriptions
  9092. if mqtt_settings.get("mqtt_enabled"):
  9093. from backend.app.models.smart_plug import SmartPlug
  9094. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9095. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9096. mqtt_plugs = result.scalars().all()
  9097. restored = 0
  9098. for plug in mqtt_plugs:
  9099. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9100. restored += 1
  9101. if restored:
  9102. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9103. # Connect to all active printers
  9104. async with async_session() as db:
  9105. await init_printer_connections(db)
  9106. # Auto-connect to Spoolman if enabled
  9107. async with async_session() as db:
  9108. from backend.app.api.routes.settings import get_setting
  9109. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9110. spoolman_url = await get_setting(db, "spoolman_url")
  9111. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9112. try:
  9113. client = await init_spoolman_client(spoolman_url)
  9114. if await client.health_check():
  9115. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9116. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9117. field_ok = await client.ensure_tag_extra_field()
  9118. if not field_ok:
  9119. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9120. # Register the BambuStudio slicer-preset fields used by the
  9121. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9122. # unknown extra keys, so these must exist before any update
  9123. # that touches them.
  9124. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9125. if not await client.ensure_extra_field(field_name):
  9126. logging.warning(
  9127. "Spoolman extra field %r registration failed — "
  9128. "spool slicer-preset edits will return 502",
  9129. field_name,
  9130. )
  9131. else:
  9132. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9133. except Exception as e:
  9134. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9135. # Start the print scheduler
  9136. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9137. # Start the smart plug scheduler for time-based on/off
  9138. smart_plug_manager.start_scheduler()
  9139. # Start the Home Assistant sensor poller (#1148)
  9140. ha_sensor_manager.start()
  9141. location_ha_sensor_manager.start()
  9142. # Resume any pending auto-offs that were interrupted by restart
  9143. await smart_plug_manager.resume_pending_auto_offs()
  9144. # Start the notification digest scheduler
  9145. notification_service.start_digest_scheduler()
  9146. notify_live_activities.start()
  9147. notify_widgets.start()
  9148. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9149. # provider in reactions/both mode; the notification routes resync them.
  9150. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9151. # until the next provider save, not the whole startup.
  9152. try:
  9153. await telegram_reaction_poller.start()
  9154. except Exception as e:
  9155. logging.warning("Telegram reaction poller did not start: %s", e)
  9156. # Start the GitHub backup scheduler
  9157. await github_backup_service.start_scheduler()
  9158. # Start the local backup scheduler
  9159. await local_backup_service.start_scheduler()
  9160. await obico_detection_service.start()
  9161. # Start the library trash sweeper (#1008)
  9162. await library_trash_service.start_scheduler()
  9163. # Start the archive auto-purge sweeper (#1008 follow-up)
  9164. await archive_purge_service.start_scheduler()
  9165. # Start AMS history recording
  9166. start_ams_history_recording()
  9167. # Start printer sensor (nozzle / bed / chamber) history recording
  9168. start_printer_sensor_history_recording()
  9169. # Start printer runtime tracking
  9170. start_runtime_tracking()
  9171. # Start SpoolBuddy device watchdog
  9172. start_spoolbuddy_watchdog()
  9173. # Start camera stream orphan cleanup
  9174. start_camera_cleanup()
  9175. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9176. start_connection_watchdog()
  9177. # One-shot sweep for timelapse session directories orphaned by a crash
  9178. # or restart that happened mid-print (in-memory session tracking can't
  9179. # survive that, and nothing else reaps the leftover frames/output file)
  9180. try:
  9181. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9182. removed = cleanup_orphaned_timelapse_sessions()
  9183. if removed:
  9184. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9185. except Exception as e:
  9186. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9187. # Start expected-print TTL eviction (prevents memory leak when prints are
  9188. # registered but on_print_start never fires)
  9189. start_expected_prints_cleanup()
  9190. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9191. start_auth_cleanup()
  9192. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9193. from backend.app.services import announcements as announcements_service
  9194. announcements_service.start()
  9195. from backend.app.services.printer_media import start_printer_download_cleanup
  9196. start_printer_download_cleanup()
  9197. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9198. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9199. from backend.app.services.loop_watchdog import start_loop_watchdog
  9200. start_loop_watchdog()
  9201. # Initialize virtual printer manager and sync from DB
  9202. from backend.app.services.virtual_printer import virtual_printer_manager
  9203. virtual_printer_manager.set_session_factory(async_session)
  9204. virtual_printer_manager.set_printer_manager(printer_manager)
  9205. try:
  9206. await virtual_printer_manager.sync_from_db()
  9207. logging.info("Virtual printer manager synced from database")
  9208. except Exception as e:
  9209. logging.warning("Failed to sync virtual printers: %s", e)
  9210. yield
  9211. # Shutdown
  9212. print_scheduler.stop()
  9213. smart_plug_manager.stop_scheduler()
  9214. ha_sensor_manager.stop()
  9215. location_ha_sensor_manager.stop()
  9216. notification_service.stop_digest_scheduler()
  9217. await notify_live_activities.close()
  9218. await notify_widgets.close()
  9219. await telegram_reaction_poller.aclose()
  9220. github_backup_service.stop_scheduler()
  9221. local_backup_service.stop_scheduler()
  9222. library_trash_service.stop_scheduler()
  9223. archive_purge_service.stop_scheduler()
  9224. obico_detection_service.stop()
  9225. stop_ams_history_recording()
  9226. stop_printer_sensor_history_recording()
  9227. stop_runtime_tracking()
  9228. stop_spoolbuddy_watchdog()
  9229. stop_camera_cleanup()
  9230. stop_connection_watchdog()
  9231. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9232. stop_loop_watchdog()
  9233. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9234. # cleanly rather than waiting on a queue that nothing will ever fill.
  9235. try:
  9236. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9237. await shutdown_all_broadcasters()
  9238. except Exception as e:
  9239. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9240. stop_expected_prints_cleanup()
  9241. stop_auth_cleanup()
  9242. from backend.app.services import announcements as announcements_service
  9243. announcements_service.stop()
  9244. from backend.app.services.printer_media import stop_printer_download_cleanup
  9245. await stop_printer_download_cleanup()
  9246. printer_manager.disconnect_all()
  9247. slot_unlink_grace.reset()
  9248. await close_spoolman_client()
  9249. # Stop all virtual printer services
  9250. await virtual_printer_manager.stop_all()
  9251. await mqtt_smart_plug_service.disconnect(timeout=2)
  9252. await mqtt_relay.disconnect(timeout=2)
  9253. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9254. set_shared_http_client(None)
  9255. set_shared_makerworld_http_client(None)
  9256. set_shared_orca_http_client(None)
  9257. await _shared_cloud_http_client.aclose()
  9258. # Checkpoint WAL (SQLite only) and close all database connections
  9259. from backend.app.core.db_dialect import is_sqlite
  9260. if is_sqlite():
  9261. try:
  9262. async with engine.begin() as conn:
  9263. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9264. logging.info("WAL checkpoint completed")
  9265. except Exception as e:
  9266. logging.warning("WAL checkpoint failed: %s", e)
  9267. await engine.dispose()
  9268. app = FastAPI(
  9269. title=app_settings.app_name,
  9270. description="Archive and manage Bambu Lab 3MF files",
  9271. version=APP_VERSION,
  9272. lifespan=lifespan,
  9273. )
  9274. # =============================================================================
  9275. # Authentication Middleware - Secures ALL API routes by default
  9276. # =============================================================================
  9277. # Public routes that don't require authentication even when auth is enabled
  9278. PUBLIC_API_ROUTES = {
  9279. # Auth routes needed before/during login
  9280. "/api/v1/auth/status",
  9281. "/api/v1/auth/login",
  9282. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9283. # Advanced auth status needed for login page
  9284. "/api/v1/auth/advanced-auth/status",
  9285. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9286. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9287. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9288. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9289. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9290. # OIDC routes that must be reachable without a JWT
  9291. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9292. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9293. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9294. # Connected apps: the app's server swaps a code for the user's identity,
  9295. # authenticated by its client secret rather than a login token.
  9296. "/api/v1/connect/token",
  9297. # Version check for updates (no sensitive data)
  9298. "/api/v1/updates/version",
  9299. # Metrics endpoint handles its own prometheus_token authentication
  9300. "/api/v1/metrics",
  9301. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9302. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9303. # hostname / timezone / locale and the chrony NTP-gate state. The
  9304. # response contains user-set defaults and a public sync flag — no
  9305. # secrets. Without this entry the global auth middleware returns 401
  9306. # before the route handler runs, regardless of the route's own
  9307. # "no auth required" intent.
  9308. "/api/v1/system/appliance",
  9309. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9310. # authenticates with a long-lived ``camwall``-scoped token in the query
  9311. # string — exactly like the camera streams two lists below, and for the same
  9312. # reason (no header to put a JWT in). "Public" here only means the middleware
  9313. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9314. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9315. # plain ``camera_stream`` token does NOT open this door.
  9316. "/api/v1/camwall/printers",
  9317. # Overlay branding: the route enforces overlay-scoped token authentication.
  9318. "/api/v1/overlay-branding/logo",
  9319. }
  9320. # Route prefixes that are public (for routes with dynamic segments)
  9321. PUBLIC_API_PREFIXES = [
  9322. # WebSocket connections handle their own auth
  9323. "/api/v1/ws",
  9324. # OIDC authorize redirects — include provider_id in path
  9325. "/api/v1/auth/oidc/authorize/",
  9326. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9327. # a phone with no session, so no header can carry a JWT — the single-use
  9328. # capability token in the path IS the credential (same reasoning as the
  9329. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9330. # good/reject on the one archive the token was minted for.
  9331. "/api/v1/archives/confirm/",
  9332. ]
  9333. # Route patterns that are public (read-only display data)
  9334. # These are checked with "in path" - needed because browsers load images/videos
  9335. # via <img src> and <video src> which don't include Authorization headers
  9336. PUBLIC_API_PATTERNS = [
  9337. # Thumbnails
  9338. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9339. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9340. # Images and media
  9341. "/photos/", # /archives/{id}/photos/{filename}
  9342. "/project-image/", # /archives/{id}/project-image/{path}
  9343. "/qrcode", # /archives/{id}/qrcode
  9344. "/timelapse", # /archives/{id}/timelapse (video)
  9345. "/cover", # /printers/{id}/cover
  9346. "/icon", # /external-links/{id}/icon
  9347. # Camera (streams loaded via <img> tag)
  9348. "/camera/stream", # /printers/{id}/camera/stream
  9349. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9350. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9351. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9352. # string (same reasoning as the camera streams above — no header to carry a
  9353. # JWT). "Public" only means the middleware steps aside; the route still runs
  9354. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9355. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9356. "/overlay-status", # /printers/{id}/overlay-status
  9357. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9358. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9359. # download token in the URL path instead.
  9360. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9361. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9362. # and these patterns match by substring. Without its own entry the middleware
  9363. # 401s the slicer's header-less request before the route's token check runs,
  9364. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9365. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9366. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9367. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9368. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9369. ]
  9370. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9371. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9372. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9373. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9374. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9375. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9376. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9377. Invalid entries are dropped with a warning rather than failing startup, so
  9378. a typo in one origin doesn't take the whole deployment down.
  9379. """
  9380. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9381. if not raw:
  9382. return ()
  9383. valid: list[str] = []
  9384. for item in raw.split(","):
  9385. candidate = item.strip()
  9386. if not candidate:
  9387. continue
  9388. try:
  9389. parsed = urlparse(candidate)
  9390. except ValueError as e:
  9391. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9392. continue
  9393. if parsed.scheme not in ("http", "https"):
  9394. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9395. continue
  9396. if not parsed.netloc:
  9397. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9398. continue
  9399. if parsed.path and parsed.path != "/":
  9400. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9401. continue
  9402. if parsed.query or parsed.fragment:
  9403. _security_headers_logger.warning(
  9404. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9405. )
  9406. continue
  9407. if "*" in parsed.netloc:
  9408. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9409. continue
  9410. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9411. if valid:
  9412. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9413. return tuple(valid)
  9414. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9415. def _frame_ancestors(default_value: str) -> str:
  9416. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9417. ``default_value`` is the strict directive used when the operator has not
  9418. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9419. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9420. Settings URL builder's preview). When trusted origins
  9421. are configured, ``'self'`` is always included so same-origin embedding never
  9422. breaks even if an operator forgets to add their own origin to the list.
  9423. """
  9424. if _TRUSTED_FRAME_ORIGINS:
  9425. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9426. return f"frame-ancestors {default_value};"
  9427. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9428. # patterns are anchored on the exact emitted name so the relaxed policies
  9429. # below can never apply to any other asset.
  9430. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9431. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9432. # -> /assets/pdf.worker.min-<hash>.js
  9433. # Vite also emits a one-line chunk under the second name that only exports the
  9434. # worker's URL. The page imports it as a module, and a module script is run
  9435. # under the importing document's policy, never its own response's, so it
  9436. # matching as well changes nothing.
  9437. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9438. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9439. @app.middleware("http")
  9440. async def security_headers_middleware(request, call_next):
  9441. """Add standard HTTP security headers to every response."""
  9442. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9443. # changes nothing for Bambuddy's own pages — index.html has no inline
  9444. # scripts since the SW registration moved to /sw-register.js. The reason
  9445. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9446. # script injected into the HTML on the edge, with a fresh hash on every
  9447. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9448. # it clones the same nonce onto its injected <script>, and the inline
  9449. # script passes the policy without us needing 'unsafe-inline'. See
  9450. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9451. csp_nonce = secrets.token_urlsafe(16)
  9452. # Routes that render their own HTML need it too, or their inline script is
  9453. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9454. # one that does: it submits its own form so a verdict still costs one tap.
  9455. request.state.csp_nonce = csp_nonce
  9456. response = await call_next(request)
  9457. response.headers["X-Content-Type-Options"] = "nosniff"
  9458. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9459. # browsers honour CSP frame-ancestors instead, and the legacy
  9460. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9461. # When operators have explicitly allowlisted trusted frame origins (#1191
  9462. # — typically Home Assistant on a different port), drop X-Frame-Options
  9463. # and let the CSP-side frame-ancestors directive govern embedding.
  9464. if not _TRUSTED_FRAME_ORIGINS:
  9465. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9466. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9467. # Content-Security-Policy for the React SPA.
  9468. # Notes:
  9469. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9470. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9471. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9472. # - media-src blob:: timelapse video player uses Blob URLs.
  9473. # - font-src data:: some icon fonts are embedded as data URIs.
  9474. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9475. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9476. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9477. # default CSP would render a blank page.
  9478. response.headers["Content-Security-Policy"] = (
  9479. "default-src 'self'; "
  9480. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9481. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9482. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9483. "connect-src 'self'; "
  9484. "font-src 'self' data: https://fonts.gstatic.com; "
  9485. "worker-src 'self' blob:; "
  9486. "object-src 'none'; "
  9487. "base-uri 'self'; " + _frame_ancestors("'none'")
  9488. )
  9489. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9490. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9491. # its emscripten/embind glue generates invoker functions with `new
  9492. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9493. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9494. # own response — not the document's — so relaxing it here confines
  9495. # eval to that DOM-less worker context. The document policy below
  9496. # stays nonce-strict, and this response header has no effect when the
  9497. # file is merely fetched (a fetch's CSP is enforced against the
  9498. # requesting document, not the resource's own headers).
  9499. response.headers["Content-Security-Policy"] = (
  9500. "default-src 'self'; "
  9501. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9502. "connect-src 'self'; "
  9503. "object-src 'none'; "
  9504. "base-uri 'self'; " + _frame_ancestors("'none'")
  9505. )
  9506. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9507. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9508. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9509. # rule as the STEP worker above: the policy that governs a dedicated
  9510. # worker is the one delivered with its own script, so the wasm compile
  9511. # has to be permitted here rather than on the document. Unlike the STEP
  9512. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9513. response.headers["Content-Security-Policy"] = (
  9514. "default-src 'self'; "
  9515. "script-src 'self' 'wasm-unsafe-eval'; "
  9516. "connect-src 'self'; "
  9517. "object-src 'none'; "
  9518. "base-uri 'self'; " + _frame_ancestors("'none'")
  9519. )
  9520. else:
  9521. # The streaming overlay is embedded same-origin by the URL builder's
  9522. # preview in Settings (#1422), so this branch allows 'self'.
  9523. # Embedding from anywhere else is still refused: 'self'
  9524. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9525. # a clickjacking page on another host is blocked exactly as before.
  9526. # (The overlay draws status over a camera feed and its only interactive
  9527. # element is the logo link, so there is nothing to bait a click into
  9528. # even from a same-origin framer.) Cross-origin embedding of the
  9529. # overlay — Home Assistant on another port — remains what
  9530. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9531. # allowlist in.
  9532. #
  9533. # The connected-app consent page (/connect/authorize) gets the same
  9534. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9535. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9536. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9537. # requires every ancestor to be this origin, so a foreign page -- a
  9538. # sidebar link's site included -- still cannot frame the consent
  9539. # screen to bait a click.
  9540. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9541. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9542. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9543. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9544. # the policy served with their own script, so each gets it in its own
  9545. # branch above and the document policy stays as strict as it was.
  9546. response.headers["Content-Security-Policy"] = (
  9547. "default-src 'self'; "
  9548. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9549. "style-src 'self' 'unsafe-inline'; "
  9550. "img-src 'self' data: blob:; "
  9551. "media-src 'self' blob:; "
  9552. "connect-src 'self' ws: wss:; "
  9553. "font-src 'self' data:; "
  9554. "object-src 'none'; "
  9555. "base-uri 'self'; "
  9556. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9557. )
  9558. if request.url.scheme == "https":
  9559. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9560. return response
  9561. @app.middleware("http")
  9562. async def auth_middleware(request, call_next):
  9563. """Enforce authentication on all API routes when auth is enabled.
  9564. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9565. regardless of whether individual routes have auth dependencies.
  9566. """
  9567. from starlette.responses import JSONResponse
  9568. path = request.url.path
  9569. # Only apply to API routes
  9570. if not path.startswith("/api/"):
  9571. return await call_next(request)
  9572. # Allow public routes
  9573. if path in PUBLIC_API_ROUTES:
  9574. return await call_next(request)
  9575. # Allow public prefixes
  9576. for prefix in PUBLIC_API_PREFIXES:
  9577. if path.startswith(prefix):
  9578. return await call_next(request)
  9579. # Allow public patterns (read-only display data like thumbnails)
  9580. for pattern in PUBLIC_API_PATTERNS:
  9581. if pattern in path:
  9582. return await call_next(request)
  9583. # Check if auth is enabled. Fail CLOSED on any exception during the
  9584. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9585. # an attacker who could force a DB exception (e.g. file-descriptor
  9586. # exhaustion via login flood) bypass auth on every protected endpoint.
  9587. try:
  9588. async with async_session() as db:
  9589. from backend.app.core.auth import is_auth_enabled
  9590. auth_enabled = await is_auth_enabled(db)
  9591. if not auth_enabled:
  9592. # Auth disabled, allow all requests
  9593. return await call_next(request)
  9594. except Exception:
  9595. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9596. return JSONResponse(
  9597. status_code=503,
  9598. content={"detail": "Authentication service temporarily unavailable"},
  9599. )
  9600. # Auth is enabled - require valid token
  9601. auth_header = request.headers.get("Authorization")
  9602. x_api_key = request.headers.get("X-API-Key")
  9603. # Check for API key auth first
  9604. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9605. # API key authentication - let the request through to be validated by route handler
  9606. # API keys are validated per-route since they have different permission levels
  9607. return await call_next(request)
  9608. # Check for JWT auth
  9609. if not auth_header or not auth_header.startswith("Bearer "):
  9610. return JSONResponse(
  9611. status_code=401,
  9612. content={"detail": "Authentication required"},
  9613. headers={"WWW-Authenticate": "Bearer"},
  9614. )
  9615. # Validate JWT token
  9616. import jwt
  9617. try:
  9618. from backend.app.core.auth import (
  9619. ALGORITHM,
  9620. SECRET_KEY,
  9621. _is_token_fresh,
  9622. get_user_by_username,
  9623. is_jti_revoked,
  9624. )
  9625. token = auth_header.replace("Bearer ", "")
  9626. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9627. username = payload.get("sub")
  9628. if not username:
  9629. raise ValueError("No username in token")
  9630. jti = payload.get("jti")
  9631. if not jti:
  9632. raise ValueError("No jti in token")
  9633. iat = payload.get("iat")
  9634. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9635. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9636. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9637. async with async_session() as db:
  9638. if await is_jti_revoked(jti, db):
  9639. return JSONResponse(
  9640. status_code=401,
  9641. content={"detail": "Token has been revoked"},
  9642. headers={"WWW-Authenticate": "Bearer"},
  9643. )
  9644. user = await get_user_by_username(db, username)
  9645. if not user or not user.is_active:
  9646. return JSONResponse(
  9647. status_code=401,
  9648. content={"detail": "User not found or inactive"},
  9649. headers={"WWW-Authenticate": "Bearer"},
  9650. )
  9651. if not _is_token_fresh(iat, user):
  9652. return JSONResponse(
  9653. status_code=401,
  9654. content={"detail": "Token no longer valid"},
  9655. headers={"WWW-Authenticate": "Bearer"},
  9656. )
  9657. except jwt.ExpiredSignatureError:
  9658. return JSONResponse(
  9659. status_code=401,
  9660. content={"detail": "Token has expired"},
  9661. headers={"WWW-Authenticate": "Bearer"},
  9662. )
  9663. except (jwt.InvalidTokenError, ValueError, Exception):
  9664. return JSONResponse(
  9665. status_code=401,
  9666. content={"detail": "Invalid token"},
  9667. headers={"WWW-Authenticate": "Bearer"},
  9668. )
  9669. return await call_next(request)
  9670. @app.middleware("http")
  9671. async def trace_id_middleware(request, call_next):
  9672. """Stamp every HTTP request with a trace ID and echo it back.
  9673. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9674. @app.middleware decorators LIFO, so the last-decorated runs first
  9675. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9676. which means auth-middleware log lines (and every line emitted on the
  9677. way down to and back from the route handler) all carry the same
  9678. trace ID. If we put it before auth, auth's logs would be stamped
  9679. with the *previous* request's ID — useless for correlation.
  9680. Honours an inbound ``X-Trace-Id`` header so callers running their
  9681. own tracing can correlate their span IDs with our log lines, but
  9682. only if the value passes the whitelist gate in
  9683. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9684. rejected (too long, contains control chars, etc.) silently triggers
  9685. a freshly minted server-side ID rather than failing the request.
  9686. The minted (or echoed) ID is set on a ContextVar so that every log
  9687. record emitted during the request — application logs *and* uvicorn's
  9688. access log — carries it via TraceIDFilter, and is also written to
  9689. the ``X-Trace-Id`` response header so clients can pin a server-side
  9690. log search to the exact request they made.
  9691. """
  9692. from backend.app.core.trace import (
  9693. generate_trace_id,
  9694. normalise_inbound_trace_id,
  9695. trace_id_var,
  9696. )
  9697. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9698. trace_id = inbound if inbound is not None else generate_trace_id()
  9699. token = trace_id_var.set(trace_id)
  9700. try:
  9701. response = await call_next(request)
  9702. finally:
  9703. # Reset the ContextVar so a record emitted in a totally
  9704. # unrelated background task that just happens to inherit this
  9705. # context doesn't keep referencing this request's ID forever.
  9706. # In practice ContextVar.reset is best-effort under asyncio
  9707. # task-spawn semantics, but the cost is one attribute write so
  9708. # we may as well do it.
  9709. trace_id_var.reset(token)
  9710. response.headers["X-Trace-Id"] = trace_id
  9711. return response
  9712. # API routes
  9713. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9714. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9715. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9716. app.include_router(users.router, prefix=app_settings.api_prefix)
  9717. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9718. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9719. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9720. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9721. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9722. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9723. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9724. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9725. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9726. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9727. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9728. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9729. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9730. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9731. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9732. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9733. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9734. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9735. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9736. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9737. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9738. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9739. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9740. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9741. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9742. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9743. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9744. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  9745. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9746. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9747. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9748. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9749. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9750. app.include_router(library.router, prefix=app_settings.api_prefix)
  9751. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9752. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9753. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9754. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9755. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9756. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9757. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9758. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9759. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9760. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9761. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  9762. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9763. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9764. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9765. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9766. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9767. app.include_router(system.router, prefix=app_settings.api_prefix)
  9768. app.include_router(support.router, prefix=app_settings.api_prefix)
  9769. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9770. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9771. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9772. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9773. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9774. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9775. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9776. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9777. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9778. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9779. # Serve static files (React build)
  9780. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9781. # Compressed, and cached for good where Vite hashed the name (#3175).
  9782. app.mount(
  9783. "/assets",
  9784. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  9785. name="assets",
  9786. )
  9787. if (app_settings.static_dir / "img").exists():
  9788. app.mount(
  9789. "/img",
  9790. StaticFiles(directory=app_settings.static_dir / "img"),
  9791. name="img",
  9792. )
  9793. if (app_settings.static_dir / "icons").exists():
  9794. app.mount(
  9795. "/icons",
  9796. StaticFiles(directory=app_settings.static_dir / "icons"),
  9797. name="icons",
  9798. )
  9799. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9800. # falls through to the SPA catch-all and returns index.html, which the
  9801. # browser's font sanitizer rejects ("downloadable font: rejected by
  9802. # sanitizer").
  9803. if (app_settings.static_dir / "fonts").exists():
  9804. app.mount(
  9805. "/fonts",
  9806. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9807. name="fonts",
  9808. )
  9809. @app.get("/")
  9810. async def serve_frontend():
  9811. """Serve the React frontend."""
  9812. index_file = app_settings.static_dir / "index.html"
  9813. if index_file.exists():
  9814. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9815. return {
  9816. "message": "Bambuddy API",
  9817. "docs": "/docs",
  9818. "frontend": "Build and place React app in /static directory",
  9819. }
  9820. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9821. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9822. # forever, but the HTML wrapping it is the only file that knows which hash
  9823. # is current. Without explicit cache-control headers Chromium decides
  9824. # heuristically (typically 10% of the time since Last-Modified) and on
  9825. # long-running kiosks happily serves stale HTML across browser restarts.
  9826. # That stale HTML references an old bundle hash, the old bundle is also
  9827. # in the disk cache, and the user ends up running pre-update JS forever
  9828. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9829. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9830. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9831. @app.get("/health")
  9832. async def health_check():
  9833. """Health check endpoint."""
  9834. return {"status": "healthy"}
  9835. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9836. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9837. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9838. # in deployment debugging.
  9839. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9840. async def serve_manifest():
  9841. """Serve PWA manifest."""
  9842. manifest_file = app_settings.static_dir / "manifest.json"
  9843. if manifest_file.exists():
  9844. return FileResponse(manifest_file, media_type="application/manifest+json")
  9845. return {"error": "Manifest not found"}
  9846. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9847. async def serve_service_worker():
  9848. """Serve service worker."""
  9849. sw_file = app_settings.static_dir / "sw.js"
  9850. if sw_file.exists():
  9851. return FileResponse(
  9852. sw_file,
  9853. media_type="application/javascript",
  9854. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9855. )
  9856. return {"error": "Service worker not found"}
  9857. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9858. async def serve_sw_register():
  9859. """Serve the service-worker registration bootstrap script.
  9860. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9861. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9862. """
  9863. reg_file = app_settings.static_dir / "sw-register.js"
  9864. if reg_file.exists():
  9865. return FileResponse(reg_file, media_type="application/javascript")
  9866. return {"error": "sw-register.js not found"}
  9867. # ── GCode viewer static files ────────────────────────────────────────────────
  9868. # Catch-all route for React Router (must be last)
  9869. @app.get("/{full_path:path}")
  9870. async def serve_spa(full_path: str):
  9871. """Serve React app for client-side routing."""
  9872. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9873. if full_path.startswith("api/"):
  9874. from fastapi import HTTPException
  9875. raise HTTPException(status_code=404, detail="Not found")
  9876. index_file = app_settings.static_dir / "index.html"
  9877. if index_file.exists():
  9878. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9879. return {"error": "Frontend not built"}